@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
@@ -1,214 +1,15 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
- import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, buildConformanceFilter } from "./decorators";
5
- import { propertyNameToSetterName } from "./util";
6
- import { escapeSurrealString } from "../utils";
7
- import { formatSurrealValue as _formatSurrealValue, compileWhereClause } from "./surreal-utils";
8
- function capitalize(word) {
9
- return word.charAt(0).toUpperCase() + word.slice(1);
10
- }
11
- /**
12
- * Resolves the predicate for a parent query.
13
- *
14
- * Uses TS discriminated union narrowing:
15
- * - Raw form (`{ id, predicate }`) → predicate used as-is
16
- * - Model form (`{ model, id, field? }`) → lookup from relation metadata
17
- * - With `field`: direct key lookup
18
- * - Without `field`: scan for a relation whose `target()` matches `childCtor`
19
- */
20
- function resolveParentPredicate(parent, childCtor) {
21
- // Raw form — explicit predicate
22
- if ('predicate' in parent)
23
- return parent.predicate;
24
- // Model form — resolve from relation metadata
25
- const { model } = parent;
26
- const relMeta = getRelationsMetadata(model);
27
- // Direct lookup by field name when provided
28
- if (parent.field) {
29
- const entry = relMeta[parent.field];
30
- if (!entry) {
31
- throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
32
- }
33
- return entry.predicate;
34
- }
35
- // Fallback: scan for a relation whose target matches the child class
36
- for (const [, entry] of Object.entries(relMeta)) {
37
- if (entry.target && entry.target() === childCtor) {
38
- return entry.predicate;
39
- }
40
- }
41
- throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
42
- }
43
- function buildParentQuery(parent, resolvedPredicate) {
44
- if (!parent || !resolvedPredicate)
45
- return '';
46
- return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
47
- }
48
- // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
49
- function buildAuthorAndTimestampQuery() {
50
- // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
51
- return `
52
- findall(
53
- [T, A],
54
- link(Base, _, _, T, A),
55
- AllLinks
56
- ),
57
- sort(AllLinks, SortedLinks),
58
- SortedLinks = [[Timestamp, Author]|_]
59
- `;
60
- }
61
- function buildPropertiesQuery(properties) {
62
- // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
63
- // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
64
- // an Expression in JSON literal, or the direct literal value if it is a simple literal
65
- // If no properties are provided, all are included
66
- return `
67
- findall([PropertyName, PropertyValue, Resolve], (
68
- % Constrain to specified properties if provided
69
- ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
70
- resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
71
- ), Properties)
72
- `;
73
- }
74
- function buildWhereQuery(where = {}) {
75
- // Constrains the query to instances that match the provided where conditions
76
- // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
77
- function formatValue(value) {
78
- // Wrap strings in quotes
79
- return typeof value === "string" ? `"${value}"` : value;
80
- }
81
- return Object.entries(where)
82
- .map(([key, value]) => {
83
- const isSpecial = ["id", "author", "timestamp"].includes(key);
84
- const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
85
- // For 'id' the Prolog variable is always 'Base'
86
- const field = key === "id" ? "Base" : capitalize(key);
87
- // Handle direct array values (for IN conditions)
88
- if (Array.isArray(value)) {
89
- const formattedValues = value.map((v) => formatValue(v)).join(", ");
90
- if (isSpecial)
91
- return `member(${field}, [${formattedValues}])`;
92
- else
93
- return `${getter}, member(Value${key}, [${formattedValues}])`;
94
- }
95
- // Handle operation object
96
- if (typeof value === "object" && value !== null) {
97
- const { not, between, lt, lte, gt, gte } = value;
98
- // Handle NOT operation
99
- if (not !== undefined) {
100
- if (Array.isArray(not)) {
101
- // NOT IN array
102
- const formattedValues = not.map((v) => formatValue(v)).join(", ");
103
- if (isSpecial)
104
- return `\\+ member(${field}, [${formattedValues}])`;
105
- else
106
- return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
107
- }
108
- else {
109
- // NOT EQUAL
110
- if (isSpecial)
111
- return `${field} \\= ${formatValue(not)}`;
112
- else
113
- return `${getter}, Value${key} \\= ${formatValue(not)}`;
114
- }
115
- }
116
- // Handle BETWEEN
117
- if (between !== undefined && Array.isArray(between) && between.length === 2) {
118
- if (isSpecial)
119
- return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
120
- else
121
- return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
122
- }
123
- // Handle lt, lte, gt, & gte operations
124
- const operators = [
125
- { value: lt, symbol: "<" },
126
- { value: lte, symbol: "=<" },
127
- { value: gt, symbol: ">" },
128
- { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
129
- ];
130
- for (const { value, symbol } of operators) {
131
- if (value !== undefined)
132
- return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
133
- }
134
- }
135
- // Default to direct equality
136
- if (isSpecial)
137
- return `${field} = ${formatValue(value)}`;
138
- else
139
- return `${getter}, Value${key} = ${formatValue(value)}`;
140
- })
141
- .join(", ");
142
- }
143
- function buildCountQuery(count) {
144
- return count ? "length(UnsortedInstances, TotalCount)" : "";
145
- }
146
- function buildOrderQuery(order) {
147
- if (!order)
148
- return "SortedInstances = UnsortedInstances";
149
- const entries = Object.entries(order);
150
- if (entries.length === 1) {
151
- const [propertyName, direction] = entries[0];
152
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
153
- }
154
- // Multi-field sort: sort from least-significant to most-significant key
155
- // so that the final (primary) sort preserves secondary-key ordering for equal values.
156
- // The merge_sort implementation is stable (equal elements keep original order).
157
- const clauses = [];
158
- for (let i = entries.length - 1; i >= 0; i--) {
159
- const [propertyName, direction] = entries[i];
160
- const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
161
- const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
162
- clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
163
- }
164
- return clauses.join(",\n ");
165
- }
166
- function buildOffsetQuery(offset) {
167
- if (!offset || offset < 0)
168
- return "InstancesWithOffset = SortedInstances";
169
- return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
170
- }
171
- function buildLimitQuery(limit) {
172
- if (!limit || limit < 0)
173
- return "AllInstances = InstancesWithOffset";
174
- return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
175
- }
176
- function normalizeNamespaceString(namespace) {
177
- if (!namespace)
178
- return '';
179
- if (namespace.includes('://')) {
180
- const [scheme, rest] = namespace.split('://');
181
- const path = (rest || '').replace(/\/+$/, '');
182
- return `${scheme}://${path}`;
183
- }
184
- else {
185
- return namespace.replace(/\/+$/, '');
186
- }
187
- }
188
- function normalizeSchemaType(type) {
189
- if (!type)
190
- return undefined;
191
- if (typeof type === "string")
192
- return type;
193
- if (Array.isArray(type) && type.length > 0) {
194
- const nonNull = type.find((t) => t !== "null");
195
- return nonNull || type[0];
196
- }
197
- return undefined;
198
- }
199
- function isSchemaType(schema, expectedType) {
200
- return normalizeSchemaType(schema.type) === expectedType;
201
- }
202
- function isArrayType(schema) {
203
- return isSchemaType(schema, "array");
204
- }
205
- function isObjectType(schema) {
206
- return isSchemaType(schema, "object");
207
- }
208
- function isNumericType(schema) {
209
- const normalized = normalizeSchemaType(schema.type);
210
- return normalized === "number" || normalized === "integer";
211
- }
4
+ import { makeRandomId } from "./util";
5
+ import { getPropertiesMetadata, getRelationsMetadata } from "./decorators";
6
+ import { formatSurrealValue } from "./surreal-utils";
7
+ import { resolveParentPredicate } from "./query-common";
8
+ import { buildParentQuery, buildAuthorAndTimestampQuery, buildPropertiesQuery, buildWhereQuery, buildCountQuery, buildOrderQuery, buildOffsetQuery, buildLimitQuery } from "./query-prolog";
9
+ import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
10
+ import { buildSurrealQLQuery } from "./query-surreal";
11
+ import { ModelQueryBuilder } from "./ModelQueryBuilder";
12
+ import { normalizeValue, matchesCondition, hydrateFromLinks, assignValuesToInstance as _assignValuesToInstance, evaluateCustomGettersForInstance, hydrateRelations, } from "./hydration";
212
13
  /**
213
14
  * Base class for defining data models in AD4M.
214
15
  *
@@ -447,7 +248,7 @@ export class Ad4mModel {
447
248
  if (schema.properties) {
448
249
  for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
449
250
  const isArray = isArrayType(propertySchema);
450
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
251
+ const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, options), options);
451
252
  if (isArray) {
452
253
  relationsMetadata[propertyName] = {
453
254
  name: propertyName,
@@ -518,7 +319,7 @@ export class Ad4mModel {
518
319
  return this._perspective;
519
320
  }
520
321
  /**
521
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
322
+ * Get property metadata from decorator.
522
323
  * @private
523
324
  */
524
325
  getPropertyMetadata(key) {
@@ -536,8 +337,7 @@ export class Ad4mModel {
536
337
  return rels[key];
537
338
  }
538
339
  /**
539
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
540
- * Replaces Prolog query: property_setter(C, key, Setter)
340
+ * Generate property setter action from metadata.
541
341
  * @private
542
342
  */
543
343
  generatePropertySetterAction(key, metadata) {
@@ -567,8 +367,7 @@ export class Ad4mModel {
567
367
  }];
568
368
  }
569
369
  /**
570
- * Generate relation action from metadata (Phase 1: Prolog-free refactor)
571
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
370
+ * Generate relation action from metadata.
572
371
  * @private
573
372
  */
574
373
  generateRelationAction(key, actionType) {
@@ -592,297 +391,16 @@ export class Ad4mModel {
592
391
  ...(metadata.local && { local: true })
593
392
  }];
594
393
  }
595
- // ──────────────────────────────────────────────────────────
596
- // Unified hydration helpers
597
- // ──────────────────────────────────────────────────────────
598
- /**
599
- * Resolves a raw link target value into a hydrated property value.
600
- *
601
- * Handles, in order:
602
- * 1. Non-literal expression resolution (`perspective.getExpression`)
603
- * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
604
- * 3. Primitive type coercion (string → number / boolean)
605
- * 4. Transform function application
606
- *
607
- * @param target - The raw target string from the link
608
- * @param propMeta - Property metadata from the decorator registry
609
- * @param perspective - The perspective for expression resolution
610
- * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
611
- * @returns The resolved value
612
- * @private
613
- */
614
- static async hydratePropertyValue(target, propMeta, perspective, expectedType) {
615
- let value = target;
616
- if (target !== undefined && target !== null && target !== '') {
617
- // Non-literal expression resolution
618
- if (propMeta.resolveLanguage != null &&
619
- propMeta.resolveLanguage !== 'literal' &&
620
- typeof target === 'string' &&
621
- !target.startsWith('literal://')) {
622
- try {
623
- const expression = await perspective.getExpression(target);
624
- if (expression) {
625
- try {
626
- value = JSON.parse(expression.data);
627
- }
628
- catch {
629
- value = expression.data;
630
- }
631
- }
632
- }
633
- catch (e) {
634
- console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
635
- }
636
- }
637
- // Literal URI parsing
638
- else if (propMeta.resolveLanguage === 'literal' &&
639
- typeof target === 'string' &&
640
- target.startsWith('literal://')) {
641
- try {
642
- const parsed = Literal.fromUrl(target).get();
643
- value = parsed.data !== undefined ? parsed.data : parsed;
644
- }
645
- catch {
646
- // Keep raw value
647
- }
648
- }
649
- // Primitive type coercion
650
- else if (typeof target === 'string' && expectedType) {
651
- if (expectedType === 'number')
652
- value = Number(target);
653
- else if (expectedType === 'boolean')
654
- value = target === 'true' || target === '1';
655
- }
656
- }
657
- // Transform function
658
- if (propMeta.transform && typeof propMeta.transform === 'function') {
659
- value = propMeta.transform(value);
660
- }
661
- return value;
662
- }
663
394
  /**
664
- * Hydrates an instance from an array of raw links.
665
- *
666
- * Processes properties (latest-wins semantics), relations
667
- * (chronological accumulation), and timestamps/author in a single
668
- * pass over the links array.
669
- *
670
- * @param instance - The blank model instance to populate
671
- * @param links - Array of link objects (predicate, target, author?, timestamp?)
672
- * @param metadata - Model metadata from `getModelMetadata()`
673
- * @param perspective - The perspective for expression resolution
674
- * @param requestedProperties - Optional sparse fieldset; when provided, only these
675
- * property names are hydrated (relations are unaffected).
676
- * Omit or pass `undefined` to hydrate all properties.
677
- * @private
395
+ * Assigns decoded Prolog property values to an instance.
396
+ * Delegates to the standalone function in hydration.ts.
678
397
  */
679
- static async hydrateFromLinks(instance, links, metadata, perspective, requestedProperties) {
680
- if (!links || links.length === 0)
681
- return;
682
- let minTimestamp = null;
683
- let maxTimestamp = null;
684
- let originalAuthor = null;
685
- let latestAuthor = null;
686
- // Build predicate→propName and predicate→relName lookup maps for O(1) matching
687
- // When requestedProperties is provided, only include those properties in the map
688
- const propFilter = requestedProperties && requestedProperties.length > 0
689
- ? new Set(requestedProperties)
690
- : null;
691
- const predToProperty = new Map();
692
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
693
- if (propMeta.getter)
694
- continue; // Handled via custom getter evaluation
695
- if (propFilter && !propFilter.has(propName))
696
- continue; // Skip unrequested properties
697
- predToProperty.set(propMeta.predicate, [propName, propMeta]);
698
- }
699
- const predToRelation = new Map();
700
- // Two-pass approach: first add all non-getter, non-target-filtered relations,
701
- // then try to add target+filter relations only if their predicate isn't
702
- // already claimed. This prevents predicate collisions (e.g. entries +
703
- // messages sharing the same predicate) while still populating unique-
704
- // predicate relations normally via link hydration.
705
- const deferredTargetRelations = [];
706
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
707
- if (relMeta.getter)
708
- continue; // Handled via explicit custom getter evaluation
709
- if (relMeta.target && relMeta.filter !== false) {
710
- deferredTargetRelations.push([relName, relMeta]);
711
- continue;
712
- }
713
- predToRelation.set(relMeta.predicate, [relName, relMeta]);
714
- }
715
- // Second pass: add deferred target+filter relations only if their predicate
716
- // is not already claimed by a base relation. When a collision exists, the
717
- // conformance getter will handle the filtered view instead.
718
- for (const [relName, relMeta] of deferredTargetRelations) {
719
- if (!predToRelation.has(relMeta.predicate)) {
720
- predToRelation.set(relMeta.predicate, [relName, relMeta]);
721
- }
722
- }
723
- // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
724
- const propertyLatest = new Map();
725
- // Per-relation accumulator: ordered targets with metadata for sorting
726
- const relationAccum = new Map();
727
- // Single pass over all links
728
- for (let i = 0; i < links.length; i++) {
729
- const link = links[i];
730
- const { predicate, target, author, timestamp } = link;
731
- if (target === 'None' || target === undefined || target === null)
732
- continue;
733
- // Track timestamps/authors
734
- if (timestamp != null) {
735
- if (minTimestamp == null || timestamp < minTimestamp) {
736
- minTimestamp = timestamp;
737
- originalAuthor = author ?? null;
738
- }
739
- if (maxTimestamp == null || timestamp > maxTimestamp) {
740
- maxTimestamp = timestamp;
741
- latestAuthor = author ?? null;
742
- }
743
- }
744
- // Property match — accumulate for latest-wins
745
- const propEntry = predToProperty.get(predicate);
746
- if (propEntry) {
747
- const existing = propertyLatest.get(propEntry[0]);
748
- // Latest-wins: always overwrite (links are ordered ASC so last = latest)
749
- propertyLatest.set(propEntry[0], { target, timestamp });
750
- continue;
751
- }
752
- // Relation match — accumulate all
753
- const relEntry = predToRelation.get(predicate);
754
- if (relEntry) {
755
- const [relName] = relEntry;
756
- let arr = relationAccum.get(relName);
757
- if (!arr) {
758
- arr = [];
759
- relationAccum.set(relName, arr);
760
- }
761
- arr.push({ target, timestamp: timestamp ?? '', index: i });
762
- }
763
- }
764
- // Resolve properties
765
- for (const [propName, { target }] of propertyLatest) {
766
- const [, propMeta] = predToProperty.get(metadata.properties[propName].predicate);
767
- const expectedType = typeof instance[propName];
768
- instance[propName] = await this.hydratePropertyValue(target, propMeta, perspective, expectedType !== 'undefined' ? expectedType : undefined);
769
- }
770
- // Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
771
- for (const [relName, items] of relationAccum) {
772
- items.sort((a, b) => {
773
- const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
774
- return cmp !== 0 ? cmp : a.index - b.index;
775
- });
776
- instance[relName] = items
777
- .map(i => i.target)
778
- .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
779
- }
780
- // Assign author / timestamps
781
- if (originalAuthor)
782
- instance.author = originalAuthor;
783
- if (minTimestamp != null) {
784
- instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
785
- ? new Date(minTimestamp).getTime()
786
- : typeof minTimestamp === 'string'
787
- ? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
788
- : minTimestamp;
789
- }
790
- if (maxTimestamp != null) {
791
- instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
792
- ? new Date(maxTimestamp).getTime()
793
- : typeof maxTimestamp === 'string'
794
- ? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
795
- : maxTimestamp;
796
- }
797
- }
798
398
  static async assignValuesToInstance(perspective, instance, values) {
799
- // Map properties to object
800
- const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
801
- let finalValue = value;
802
- // Handle UTF-8 byte sequences from Prolog URL decoding
803
- if (!resolve && typeof value === 'string') {
804
- // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
805
- // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
806
- const codePoints = Array.from(value, ch => ch.codePointAt(0));
807
- const looksByteString = codePoints.every(cp => cp <= 0xFF);
808
- const hasHighByte = codePoints.some(cp => cp >= 0x80);
809
- if (looksByteString && hasHighByte) {
810
- try {
811
- const bytes = Uint8Array.from(codePoints);
812
- const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
813
- if (decoded !== value)
814
- finalValue = decoded;
815
- }
816
- catch (error) {
817
- // If UTF-8 conversion fails, keep the original value
818
- console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
819
- }
820
- }
821
- }
822
- // Resolve the value if necessary
823
- if (resolve) {
824
- let resolvedExpression = await perspective.getExpression(value);
825
- if (resolvedExpression) {
826
- try {
827
- // Attempt to parse the data as JSON
828
- finalValue = JSON.parse(resolvedExpression.data);
829
- }
830
- catch (error) {
831
- // If parsing fails, keep the original data
832
- finalValue = resolvedExpression.data;
833
- }
834
- }
835
- }
836
- // Apply transform function if it exists
837
- const propsMeta = getPropertiesMetadata(instance.constructor);
838
- const transform = propsMeta[name]?.transform;
839
- if (transform && typeof transform === "function") {
840
- finalValue = transform(finalValue);
841
- }
842
- return [name, finalValue];
843
- })));
844
- // Filter out properties that are read-only (getters without setters)
845
- const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
846
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
847
- if (!descriptor) {
848
- // No descriptor means it's a regular property on the instance, allow it
849
- return true;
850
- }
851
- // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
852
- const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
853
- if (isAccessor) {
854
- // Accessor descriptor: only allow if it has a setter
855
- return descriptor.set !== undefined;
856
- }
857
- else {
858
- // Data descriptor: only allow if writable is not explicitly false
859
- return descriptor.writable !== false;
860
- }
861
- }));
862
- // Assign properties to instance
863
- Object.assign(instance, writableProps);
399
+ return _assignValuesToInstance(perspective, instance, values);
864
400
  }
865
401
  // ──────────────────────────────────────────────────────────
866
402
  // Snapshot / dirty tracking
867
403
  // ──────────────────────────────────────────────────────────
868
- /**
869
- * Captures a shallow snapshot of the instance's current property and
870
- * relation values. Called automatically after hydration (`get()`,
871
- * query results). The snapshot is used by `isDirty()`,
872
- * `changedFields()`, and by `update()` to skip unchanged fields.
873
- * @private
874
- */
875
- /**
876
- * Normalize a value for snapshot storage.
877
- * Arrays of model instances are reduced to their `.id` strings so that
878
- * dirty-tracking compares stable identifiers instead of object references.
879
- */
880
- static normalizeValue(value) {
881
- if (Array.isArray(value)) {
882
- return value.map((v) => v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v);
883
- }
884
- return value;
885
- }
886
404
  /**
887
405
  * @param includedRelations Controls which relation fields are recorded
888
406
  * in the snapshot for dirty-tracking:
@@ -901,7 +419,7 @@ export class Ad4mModel {
901
419
  // Always snapshot properties
902
420
  for (const propName of Object.keys(metadata.properties)) {
903
421
  const val = this[propName];
904
- snap[propName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
422
+ snap[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);
905
423
  }
906
424
  // Snapshot relations only when appropriate:
907
425
  // undefined → all relations (backward compat)
@@ -911,7 +429,7 @@ export class Ad4mModel {
911
429
  // Full snapshot — e.g. after getData() / create()
912
430
  for (const relName of Object.keys(metadata.relations)) {
913
431
  const val = this[relName];
914
- snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
432
+ snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);
915
433
  }
916
434
  }
917
435
  else if (includedRelations && Object.keys(includedRelations).length > 0) {
@@ -919,7 +437,7 @@ export class Ad4mModel {
919
437
  for (const relName of Object.keys(includedRelations)) {
920
438
  if (relName in metadata.relations) {
921
439
  const val = this[relName];
922
- snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
440
+ snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);
923
441
  }
924
442
  }
925
443
  }
@@ -981,7 +499,7 @@ export class Ad4mModel {
981
499
  // setRelationValues call during innerUpdate.
982
500
  if (!(field in this._snapshot))
983
501
  continue;
984
- const current = Ad4mModel.normalizeValue(this[field]);
502
+ const current = normalizeValue(this[field]);
985
503
  const original = this._snapshot[field];
986
504
  if (Array.isArray(current) || Array.isArray(original)) {
987
505
  // Order-insensitive comparison (sorted) so reordering alone
@@ -1005,7 +523,7 @@ export class Ad4mModel {
1005
523
  const ctor = this.constructor;
1006
524
  const metadata = ctor.getModelMetadata();
1007
525
  // Query for all links from this specific node (base expression)
1008
- const safeBaseExpression = ctor.formatSurrealValue(this._baseExpression);
526
+ const safeBaseExpression = formatSurrealValue(this._baseExpression);
1009
527
  const linksQuery = `
1010
528
  SELECT id, predicate, out.uri AS target, author, timestamp
1011
529
  FROM link
@@ -1016,7 +534,7 @@ export class Ad4mModel {
1016
534
  if (links && links.length > 0) {
1017
535
  // Core hydration: properties (latest-wins), relations, timestamps/author
1018
536
  const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
1019
- await ctor.hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
537
+ await hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
1020
538
  }
1021
539
  // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1022
540
  const allRelsMeta = getRelationsMetadata(ctor);
@@ -1041,10 +559,10 @@ export class Ad4mModel {
1041
559
  const getterOpts = opts?.properties || opts?.include
1042
560
  ? { requestedProperties: opts?.properties, include: opts?.include }
1043
561
  : undefined;
1044
- await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
562
+ await evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
1045
563
  // Eager-load relations if requested
1046
564
  if (opts?.include) {
1047
- await ctor.hydrateRelations([this], this._perspective, opts.include);
565
+ await hydrateRelations(ctor, [this], this._perspective, opts.include);
1048
566
  }
1049
567
  }
1050
568
  catch (e) {
@@ -1053,7 +571,6 @@ export class Ad4mModel {
1053
571
  this.takeSnapshot();
1054
572
  return this;
1055
573
  }
1056
- // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
1057
574
  static async queryToProlog(perspective, query, modelClassName) {
1058
575
  const { properties, where, order, offset, limit, count } = query;
1059
576
  const className = modelClassName || (await this.getClassName(perspective));
@@ -1078,358 +595,6 @@ export class Ad4mModel {
1078
595
  `;
1079
596
  return fullQuery;
1080
597
  }
1081
- /**
1082
- * Builds a SurrealQL conformance getter for a relation whose `target` model
1083
- * is known but no explicit `getter` string was supplied.
1084
- *
1085
- * The generated getter traverses outgoing links matching the relation's
1086
- * predicate and then filters the target nodes to only those that conform to
1087
- * the target model's shape (required properties / flags).
1088
- *
1089
- * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
1090
- * so the same logic is used at shape-definition time and at query time.
1091
- *
1092
- * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
1093
- * @param targetClass - The target model class (result of calling the `target()` thunk)
1094
- * @returns A SurrealQL expression string, or `undefined` if no conformance
1095
- * conditions could be derived from the target model.
1096
- * @private
1097
- */
1098
- static buildConformanceGetter(relationPredicate, targetClass) {
1099
- const filter = buildConformanceFilter(relationPredicate, targetClass);
1100
- if (!filter) {
1101
- const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
1102
- console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
1103
- return undefined;
1104
- }
1105
- return filter.getter;
1106
- }
1107
- /**
1108
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
1109
- *
1110
- * For relations that declare a `target` but no explicit `getter`, a conformance
1111
- * getter is auto-generated from the target model's metadata (unless `filter: false`).
1112
- * @private
1113
- */
1114
- static async evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
1115
- const safeBaseExpression = this.formatSurrealValue(instance.id);
1116
- // Build projection filter — when requestedProperties is active, only
1117
- // evaluate getters for fields that are requested (or included).
1118
- const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
1119
- const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
1120
- // Evaluate property getters
1121
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1122
- if (projectionSet && !projectionSet.has(propName))
1123
- continue;
1124
- if (propMeta.getter) {
1125
- try {
1126
- // Replace 'Base' placeholder with actual base expression
1127
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
1128
- // Query from node table to have graph traversal context
1129
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1130
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
1131
- instance[propName] = result[0].value;
1132
- }
1133
- }
1134
- catch (error) {
1135
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
1136
- }
1137
- }
1138
- }
1139
- // Evaluate relation getters (explicit or auto-generated from target)
1140
- for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1141
- // Skip relations excluded by property projection (unless in include map)
1142
- if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
1143
- continue;
1144
- const meta = relMeta;
1145
- // Determine the getter to execute:
1146
- // 1. Explicit `getter` always wins
1147
- // 2. `where` clause → compile DSL to SurrealQL getter
1148
- // 3. If `target` is set and `filter !== false`, auto-generate from target metadata
1149
- // BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
1150
- // because buildConformanceGetter traverses outgoing links (->link) which is
1151
- // wrong for reverse relations. Their values are already populated by the
1152
- // reverse link lookup in instancesFromSurrealResult / getData.
1153
- let getter = meta.getter;
1154
- if (!getter && meta.where && meta.direction !== 'reverse') {
1155
- try {
1156
- const TargetClass = meta.target?.();
1157
- const targetMetadata = TargetClass
1158
- ? TargetClass.getModelMetadata?.() ?? null
1159
- : null;
1160
- const conditions = compileWhereClause(meta.where, targetMetadata);
1161
- if (conditions.length > 0) {
1162
- const escapedPred = escapeSurrealString(meta.predicate);
1163
- getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
1164
- }
1165
- }
1166
- catch (e) {
1167
- // Target metadata may not be available yet
1168
- }
1169
- }
1170
- if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
1171
- try {
1172
- const TargetClass = meta.target();
1173
- getter = this.buildConformanceGetter(meta.predicate, TargetClass);
1174
- if (!getter) {
1175
- console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
1176
- }
1177
- }
1178
- catch (e) {
1179
- console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
1180
- }
1181
- }
1182
- if (getter) {
1183
- try {
1184
- // Replace 'Base' placeholder with actual base expression
1185
- const query = getter.replace(/Base/g, safeBaseExpression);
1186
- const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
1187
- // Query from node table to have graph traversal context
1188
- const result = await perspective.querySurrealDB(fullQuery);
1189
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1190
- // Filter out 'None' from relation results
1191
- const value = result[0].value;
1192
- instance[relName] = Array.isArray(value)
1193
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
1194
- : value;
1195
- }
1196
- }
1197
- catch (error) {
1198
- console.warn(`Failed to evaluate getter for ${relName}:`, error);
1199
- }
1200
- }
1201
- }
1202
- }
1203
- /**
1204
- * Hydrates relation fields on instances according to the provided IncludeMap.
1205
- *
1206
- * For each relation listed in `includeMap`, the raw expression-URI strings
1207
- * stored on the instance are replaced with fully-hydrated model instances
1208
- * (fetched via the relation's `target()` class). Nested IncludeMaps are
1209
- * supported for multi-level eager loading.
1210
- *
1211
- * @param instances - The instances whose relations should be hydrated
1212
- * @param perspective - The perspective to fetch related instances from
1213
- * @param includeMap - Describes which relations to hydrate
1214
- * @private
1215
- */
1216
- static async hydrateRelations(instances, perspective, includeMap) {
1217
- if (!includeMap || Object.keys(includeMap).length === 0)
1218
- return;
1219
- const relMeta = getRelationsMetadata(this);
1220
- for (const [relName, includeValue] of Object.entries(includeMap)) {
1221
- const meta = relMeta[relName];
1222
- if (!meta) {
1223
- console.warn(`include: relation "${relName}" not found in metadata, skipping`);
1224
- continue;
1225
- }
1226
- const TargetClass = meta.target();
1227
- // Determine if a RelationSubQuery was supplied (object) vs a plain `true`
1228
- const subQuery = typeof includeValue === 'object' && includeValue !== null
1229
- ? includeValue
1230
- : undefined;
1231
- const nestedInclude = subQuery?.include;
1232
- // ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
1233
- // The link goes target→instance, so we query backwards:
1234
- // predicate = meta.predicate, target = inst.id → source is the related id
1235
- if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
1236
- // Per-instance reverse lookup (can't batch easily across instances)
1237
- for (const inst of instances) {
1238
- const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
1239
- // Defensive filter: perspective.get may return extra results; ensure
1240
- // we only use links that genuinely point to this instance.
1241
- const sourceIds = reverseLinks
1242
- .filter(l => l.data.target === inst.id)
1243
- .map(l => l.data.source);
1244
- if (meta.kind === 'belongsToOne') {
1245
- if (sourceIds.length === 0) {
1246
- inst[relName] = null;
1247
- continue;
1248
- }
1249
- const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
1250
- try {
1251
- const related = new TargetClass(perspective, sourceId);
1252
- await related.get();
1253
- inst[relName] = related;
1254
- }
1255
- catch {
1256
- inst[relName] = null;
1257
- }
1258
- }
1259
- else {
1260
- // belongsToMany — return array of hydrated instances
1261
- let hydrated = [];
1262
- // If there's a where/order sub-query, delegate to findAll for filtering
1263
- if (subQuery && (subQuery.where || subQuery.order || subQuery.properties)) {
1264
- const whereWithIds = {
1265
- id: sourceIds,
1266
- ...(subQuery.where ?? {}),
1267
- };
1268
- hydrated = await TargetClass.findAll(perspective, {
1269
- where: whereWithIds,
1270
- ...(subQuery.order && { order: subQuery.order }),
1271
- ...(subQuery.properties && { properties: subQuery.properties }),
1272
- });
1273
- }
1274
- else {
1275
- await Promise.all(sourceIds.map(async (sid) => {
1276
- try {
1277
- const related = new TargetClass(perspective, sid);
1278
- await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
1279
- hydrated.push(related);
1280
- }
1281
- catch { /* skip */ }
1282
- }));
1283
- }
1284
- // Apply order (client-side, if not already handled by findAll above)
1285
- if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
1286
- const orderEntries = Object.entries(subQuery.order);
1287
- hydrated = hydrated.sort((a, b) => {
1288
- for (const [field, dir] of orderEntries) {
1289
- const av = String(a[field] ?? '');
1290
- const bv = String(b[field] ?? '');
1291
- const diff = av.localeCompare(bv);
1292
- if (diff !== 0)
1293
- return dir === 'DESC' ? -diff : diff;
1294
- }
1295
- return 0;
1296
- });
1297
- }
1298
- // Apply offset and limit
1299
- if (subQuery?.offset != null || subQuery?.limit != null) {
1300
- const start = subQuery.offset ?? 0;
1301
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1302
- hydrated = hydrated.slice(start, end);
1303
- }
1304
- inst[relName] = hydrated;
1305
- // Recurse for nested includes
1306
- if (nestedInclude && hydrated.length > 0) {
1307
- await TargetClass.hydrateRelations(hydrated, perspective, nestedInclude);
1308
- }
1309
- }
1310
- }
1311
- continue; // skip the forward-relation path below
1312
- }
1313
- // ── Forward relations (hasMany / hasOne) ──────────────────────────────
1314
- // Collect all unique URIs across all instances for batch-friendly lookup.
1315
- // IMPORTANT: We cache each instance's raw value NOW (before the async
1316
- // findAll) so that concurrent getData() calls on the same instance can't
1317
- // overwrite the relation field between the uriSet relation and the
1318
- // post-await assignment loop. Without this cache, a concurrent call
1319
- // can replace the raw URI strings with hydrated model objects, causing
1320
- // the `typeof v === 'string'` check to fail and the array to end up empty.
1321
- const uriSet = new Set();
1322
- const rawCache = new Map();
1323
- for (const inst of instances) {
1324
- const raw = inst[relName];
1325
- rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
1326
- if (raw == null)
1327
- continue;
1328
- if (Array.isArray(raw)) {
1329
- for (const v of raw) {
1330
- if (typeof v === 'string')
1331
- uriSet.add(v);
1332
- // Handle already-hydrated instances (from a concurrent call)
1333
- else if (v && typeof v === 'object' && typeof v.id === 'string')
1334
- uriSet.add(v.id);
1335
- }
1336
- }
1337
- else if (typeof raw === 'string') {
1338
- uriSet.add(raw);
1339
- }
1340
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1341
- uriSet.add(raw.id);
1342
- }
1343
- }
1344
- if (uriSet.size === 0)
1345
- continue;
1346
- // Hydrate related instances using findAll to ensure conformance checking.
1347
- // findAll validates model membership via graph traversal (required predicates / flags),
1348
- // so non-conforming linked URIs are silently dropped — matching the documented behaviour.
1349
- const hydrated = new Map();
1350
- const whereWithIds = {
1351
- id: Array.from(uriSet),
1352
- ...(subQuery?.where ?? {}),
1353
- };
1354
- const fetchQuery = {
1355
- where: whereWithIds,
1356
- ...(subQuery?.order && { order: subQuery.order }),
1357
- ...(subQuery?.properties && { properties: subQuery.properties }),
1358
- };
1359
- const results = await TargetClass.findAll(perspective, fetchQuery);
1360
- for (const result of results) {
1361
- hydrated.set(result.id, result);
1362
- }
1363
- // Replace raw URIs with hydrated instances on each parent instance.
1364
- // Use the cached raw values captured BEFORE the async findAll to avoid
1365
- // the race condition where a concurrent getData() already replaced the
1366
- // strings with hydrated objects.
1367
- for (const inst of instances) {
1368
- const raw = rawCache.get(inst);
1369
- if (raw == null)
1370
- continue;
1371
- if (Array.isArray(raw)) {
1372
- // Map URIs → instances; handle both raw strings and already-hydrated objects
1373
- let resolved = raw
1374
- .map((v) => {
1375
- if (typeof v === 'string') {
1376
- return hydrated.has(v) ? hydrated.get(v) : null;
1377
- }
1378
- // Already a hydrated model instance (from a concurrent call)
1379
- if (v && typeof v === 'object' && typeof v.id === 'string') {
1380
- return hydrated.has(v.id) ? hydrated.get(v.id) : v;
1381
- }
1382
- return null;
1383
- })
1384
- .filter((v) => v !== null);
1385
- // Per-instance sort (client-side, after filtering)
1386
- if (subQuery?.order) {
1387
- const orderEntries = Object.entries(subQuery.order);
1388
- resolved = resolved.sort((a, b) => {
1389
- for (const [field, dir] of orderEntries) {
1390
- const av = String(a[field] ?? '');
1391
- const bv = String(b[field] ?? '');
1392
- const diff = av.localeCompare(bv);
1393
- if (diff !== 0)
1394
- return dir === 'DESC' ? -diff : diff;
1395
- }
1396
- return 0;
1397
- });
1398
- }
1399
- // Per-instance limit / offset
1400
- if (subQuery?.offset != null || subQuery?.limit != null) {
1401
- const start = subQuery.offset ?? 0;
1402
- const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1403
- resolved = resolved.slice(start, end);
1404
- }
1405
- // Enforce maxCount guard — single-valued relations keep only the last item
1406
- if (meta.maxCount === 1) {
1407
- if (resolved.length > 1) {
1408
- console.warn(`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`);
1409
- }
1410
- inst[relName] = resolved.length > 0
1411
- ? resolved[resolved.length - 1]
1412
- : null;
1413
- }
1414
- else {
1415
- inst[relName] = resolved;
1416
- }
1417
- }
1418
- else if (typeof raw === 'string' && hydrated.has(raw)) {
1419
- inst[relName] = hydrated.get(raw);
1420
- }
1421
- else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1422
- // Already-hydrated object — look up refreshed version or keep as-is
1423
- inst[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
1424
- }
1425
- }
1426
- // Recurse for nested includes
1427
- if (nestedInclude) {
1428
- const hydratedInstances = Array.from(hydrated.values());
1429
- await TargetClass.hydrateRelations(hydratedInstances, perspective, nestedInclude);
1430
- }
1431
- }
1432
- }
1433
598
  /**
1434
599
  * Generates a SurrealQL query from a Query object.
1435
600
  *
@@ -1468,556 +633,60 @@ export class Ad4mModel {
1468
633
  */
1469
634
  static async queryToSurrealQL(perspective, query) {
1470
635
  const metadata = this.getModelMetadata();
1471
- const { where, order, offset, limit } = query;
1472
- // Build list of graph traversal filters for required predicates
1473
- const graphTraversalFilters = [];
1474
- // Add parent filter if specified (filter to nodes linked from a parent via a specific predicate)
1475
- if (query.parent) {
1476
- const parentPredicate = resolveParentPredicate(query.parent, this);
1477
- graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${this.formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
1478
- }
1479
- // Add filters for required properties
1480
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1481
- if (propMeta.required) {
1482
- // Skip properties with a getter — they are computed dynamically
1483
- // and may not have a stored link with their predicate, so requiring their
1484
- // presence would wrongly exclude valid model instances.
1485
- if (propMeta.getter)
1486
- continue;
1487
- // For flag properties, also filter by the target value
1488
- if (propMeta.flag && propMeta.initial) {
1489
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1490
- }
1491
- else {
1492
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
636
+ const allRelMeta = getRelationsMetadata(this);
637
+ return buildSurrealQLQuery(metadata, allRelMeta, query, this);
638
+ }
639
+ static async instancesFromPrologResult(perspective, query, result) {
640
+ if (!result?.[0]?.AllInstances)
641
+ return { results: [], totalCount: 0 };
642
+ // Map results to instances
643
+ const requestedProperties = query?.properties || [];
644
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
645
+ try {
646
+ const instance = new this(perspective, Base);
647
+ // Remove unrequested attributes from instance
648
+ if (requestedProperties.length) {
649
+ Object.keys(instance).forEach((key) => {
650
+ if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
651
+ delete instance[key];
652
+ });
1493
653
  }
654
+ // Collect values to assign to instance
655
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
656
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
657
+ return instance;
1494
658
  }
1495
- }
1496
- // If no required properties produced filters, try properties with initial
1497
- // values (e.g. @Flag or @Property with an explicit initial).
1498
- if (graphTraversalFilters.length === 0) {
1499
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1500
- if (propMeta.initial) {
1501
- if (propMeta.flag) {
1502
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1503
- }
1504
- else {
1505
- graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1506
- }
1507
- break;
1508
- }
659
+ catch (error) {
660
+ console.error(`Failed to process instance ${Base}:`, error);
661
+ // Return null for failed instances - we'll filter these out below
662
+ return null;
1509
663
  }
664
+ }));
665
+ const instances = allInstances.filter((instance) => instance !== null);
666
+ // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
667
+ if (query.include && instances.length > 0) {
668
+ await hydrateRelations(this, instances, perspective, query.include);
1510
669
  }
1511
- // Still no filters → open-world structural matching.
1512
- // Require the node to have at least one link whose predicate is declared
1513
- // by this model (property OR relation). This prevents the query from
1514
- // matching every node in the perspective.
1515
- if (graphTraversalFilters.length === 0) {
1516
- const structuralPredicates = [];
1517
- for (const [, propMeta] of Object.entries(metadata.properties)) {
1518
- if (propMeta.predicate) {
1519
- structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
1520
- }
1521
- }
1522
- if (metadata.relations) {
1523
- for (const [, relMeta] of Object.entries(metadata.relations)) {
1524
- if (relMeta.predicate) {
1525
- structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
1526
- }
1527
- }
1528
- }
1529
- if (structuralPredicates.length > 0) {
1530
- graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
1531
- }
670
+ // Take snapshots for dirty tracking after ALL hydration is complete
671
+ // (including eager-loaded relations).
672
+ // When `include` is specified, only snapshot those relations.
673
+ // Otherwise snapshot ALL fields (properties + relations) since
674
+ // hydrateFromLinks populates relations with stable raw IDs.
675
+ const snapshotRelations = query.include;
676
+ for (const inst of instances) {
677
+ inst.takeSnapshot(snapshotRelations);
1532
678
  }
1533
- // Build user WHERE clause filters using graph traversal
1534
- const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
1535
- // Build complete WHERE clause using graph traversal filters
1536
- const whereConditions = [];
1537
- // Add all graph traversal filters for required properties
1538
- whereConditions.push(...graphTraversalFilters);
1539
- // Add user where conditions if any
1540
- if (userWhereClause) {
1541
- whereConditions.push(userWhereClause);
1542
- }
1543
- // Always ensure node has at least one link (each perspective has its own isolated DB)
1544
- whereConditions.push(`count(->link) > 0`);
1545
- // Build the query FROM node using direct graph traversal in WHERE
1546
- // This avoids slow subqueries and uses graph indexes for fast traversal
1547
- // FETCH links expands the link record IDs into full record objects
1548
- // (without FETCH, ->link returns only IDs like "link:abc123")
1549
- const fullQuery = `
1550
- SELECT
1551
- id AS source,
1552
- uri AS source_uri,
1553
- ->link AS links
1554
- FROM node
1555
- WHERE ${whereConditions.join(' AND ')}
1556
- FETCH links
1557
- `.trim();
1558
- return fullQuery;
679
+ return { results: instances, totalCount: result[0].TotalCount };
1559
680
  }
1560
681
  /**
1561
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
1562
- *
1563
- * @description
1564
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
1565
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
1566
- *
1567
- * Handles several condition types:
1568
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
1569
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
1570
- * - NOT operators: Use `NOT` prefix
1571
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
1572
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
682
+ * Converts SurrealDB query results to Ad4mModel instances.
1573
683
  *
1574
- * @param metadata - Model metadata containing property predicates
1575
- * @param where - Where conditions from the query
1576
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
684
+ * @param perspective - The perspective context
685
+ * @param query - The query parameters used
686
+ * @param result - Array of result objects from SurrealDB
687
+ * @returns Promise resolving to results with total count
1577
688
  *
1578
- * @private
1579
- */
1580
- static buildGraphTraversalWhereClause(metadata, where) {
1581
- if (!where)
1582
- return '';
1583
- const conditions = [];
1584
- for (const [propertyName, condition] of Object.entries(where)) {
1585
- // Check if this is a special field (id, author, timestamp)
1586
- // Note: author and timestamp filtering is done in JavaScript after query
1587
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1588
- if (isSpecial) {
1589
- // Skip author and timestamp - they'll be filtered in JavaScript
1590
- // Only handle 'id' (which maps to 'uri') here
1591
- if (propertyName === 'author' || propertyName === 'timestamp') {
1592
- continue; // Skip - will be filtered post-query
1593
- }
1594
- const columnName = 'uri'; // id maps to uri in node table
1595
- // Handle base/uri field directly
1596
- if (Array.isArray(condition)) {
1597
- // Array values (IN clause)
1598
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1599
- conditions.push(`${columnName} IN [${formattedValues}]`);
1600
- }
1601
- else if (typeof condition === 'object' && condition !== null) {
1602
- // Operator object
1603
- const ops = condition;
1604
- if (ops.not !== undefined) {
1605
- if (Array.isArray(ops.not)) {
1606
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1607
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1608
- }
1609
- else {
1610
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1611
- }
1612
- }
1613
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1614
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1615
- }
1616
- if (ops.gt !== undefined) {
1617
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1618
- }
1619
- if (ops.gte !== undefined) {
1620
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1621
- }
1622
- if (ops.lt !== undefined) {
1623
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1624
- }
1625
- if (ops.lte !== undefined) {
1626
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1627
- }
1628
- if (ops.contains !== undefined) {
1629
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1630
- }
1631
- }
1632
- else {
1633
- // Simple equality
1634
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1635
- }
1636
- }
1637
- else {
1638
- // Handle regular properties via graph traversal.
1639
- // IMPORTANT: Check relation metadata first — @BelongsToOne / @BelongsToMany
1640
- // also write into propertyRegistry, but the link direction is inverted.
1641
- // If we matched the property path they would get a forward ->link filter
1642
- // which is wrong for belongs-to relations.
1643
- const allRelations = getRelationsMetadata(this);
1644
- const relMeta = allRelations[propertyName];
1645
- const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
1646
- if (relMeta) {
1647
- const predicate = escapeSurrealString(relMeta.predicate);
1648
- if (Array.isArray(condition)) {
1649
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1650
- if (isBelongs) {
1651
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
1652
- }
1653
- else {
1654
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
1655
- }
1656
- }
1657
- else if (typeof condition === 'object' && condition !== null) {
1658
- const ops = condition;
1659
- if (ops.not !== undefined) {
1660
- if (Array.isArray(ops.not)) {
1661
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1662
- if (isBelongs) {
1663
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
1664
- }
1665
- else {
1666
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
1667
- }
1668
- }
1669
- else {
1670
- if (isBelongs) {
1671
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1672
- }
1673
- else {
1674
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1675
- }
1676
- }
1677
- }
1678
- }
1679
- else {
1680
- // Simple equality
1681
- if (isBelongs) {
1682
- conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1683
- }
1684
- else {
1685
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1686
- }
1687
- }
1688
- continue;
1689
- }
1690
- const propMeta = metadata.properties[propertyName];
1691
- if (!propMeta)
1692
- continue; // Skip if property not found in metadata
1693
- const predicate = escapeSurrealString(propMeta.predicate);
1694
- // Use fn::parse_literal() for properties with resolveLanguage
1695
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
1696
- if (Array.isArray(condition)) {
1697
- // Array values (IN clause)
1698
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1699
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1700
- }
1701
- else if (typeof condition === 'object' && condition !== null) {
1702
- // Operator object
1703
- const ops = condition;
1704
- if (ops.not !== undefined) {
1705
- if (Array.isArray(ops.not)) {
1706
- // For NOT IN with array: must NOT have a link with value in the array
1707
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1708
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1709
- }
1710
- else {
1711
- // For NOT with single value: must NOT have this value
1712
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1713
- }
1714
- }
1715
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1716
- // post-query because fn::parse_literal() comparisons in SurrealDB
1717
- // don't work reliably with numeric comparisons.
1718
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1719
- // However, we still need to ensure the property exists
1720
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1721
- ops.lt !== undefined || ops.lte !== undefined ||
1722
- ops.between !== undefined || ops.contains !== undefined;
1723
- if (hasComparisonOps) {
1724
- // Ensure we only get nodes that have this property
1725
- conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
1726
- }
1727
- }
1728
- else {
1729
- // Simple equality
1730
- conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1731
- }
1732
- }
1733
- }
1734
- return conditions.join(' AND ');
1735
- }
1736
- /**
1737
- * Builds the WHERE clause for SurrealQL queries.
1738
- *
1739
- * @description
1740
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
1741
- * For each property filter, generates a subquery that checks for links with the appropriate
1742
- * predicate and target value.
1743
- *
1744
- * Handles several condition types:
1745
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
1746
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
1747
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
1748
- * - gt, gte, lt, lte: comparison operators
1749
- * - not: negation (single value or array)
1750
- * - between: range check
1751
- * - contains: substring/element check (uses SurrealQL CONTAINS)
1752
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
1753
- *
1754
- * All conditions are joined with AND.
1755
- *
1756
- * @param metadata - Model metadata containing property predicates
1757
- * @param where - Where conditions from the query
1758
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
1759
- *
1760
- * @private
1761
- */
1762
- static buildSurrealWhereClause(metadata, where) {
1763
- if (!where)
1764
- return '';
1765
- const conditions = [];
1766
- for (const [propertyName, condition] of Object.entries(where)) {
1767
- // Check if this is a special field (id, author, timestamp)
1768
- // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1769
- // because they need to be computed from the grouped links first
1770
- const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1771
- if (isSpecial) {
1772
- // Skip author and timestamp - they'll be filtered in JavaScript
1773
- // Only handle 'id' (which maps to 'source') here
1774
- if (propertyName === 'author' || propertyName === 'timestamp') {
1775
- continue; // Skip - will be filtered post-query
1776
- }
1777
- const columnName = 'source'; // id maps to source
1778
- // Handle base/source field directly
1779
- if (Array.isArray(condition)) {
1780
- // Array values (IN clause)
1781
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1782
- conditions.push(`${columnName} IN [${formattedValues}]`);
1783
- }
1784
- else if (typeof condition === 'object' && condition !== null) {
1785
- // Operator object
1786
- const ops = condition;
1787
- if (ops.not !== undefined) {
1788
- if (Array.isArray(ops.not)) {
1789
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1790
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1791
- }
1792
- else {
1793
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1794
- }
1795
- }
1796
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1797
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1798
- }
1799
- if (ops.gt !== undefined) {
1800
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1801
- }
1802
- if (ops.gte !== undefined) {
1803
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1804
- }
1805
- if (ops.lt !== undefined) {
1806
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1807
- }
1808
- if (ops.lte !== undefined) {
1809
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1810
- }
1811
- if (ops.contains !== undefined) {
1812
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1813
- }
1814
- }
1815
- else {
1816
- // Simple equality
1817
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1818
- }
1819
- }
1820
- else {
1821
- // Handle regular properties via subqueries
1822
- const propMeta = metadata.properties[propertyName];
1823
- if (!propMeta)
1824
- continue; // Skip if property not found in metadata
1825
- const predicate = escapeSurrealString(propMeta.predicate);
1826
- // Use fn::parse_literal() for properties with resolveLanguage
1827
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1828
- if (Array.isArray(condition)) {
1829
- // Array values (IN clause)
1830
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1831
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1832
- }
1833
- else if (typeof condition === 'object' && condition !== null) {
1834
- // Operator object
1835
- const ops = condition;
1836
- if (ops.not !== undefined) {
1837
- if (Array.isArray(ops.not)) {
1838
- // For NOT IN with array: exclude sources that HAVE a value in the array
1839
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1840
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1841
- }
1842
- else {
1843
- // For NOT with single value: exclude sources that HAVE this value
1844
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
1845
- }
1846
- }
1847
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1848
- // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
1849
- // don't work reliably with numeric comparisons.
1850
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1851
- // However, we still need to ensure the property exists by filtering on the predicate
1852
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1853
- ops.lt !== undefined || ops.lte !== undefined ||
1854
- ops.between !== undefined || ops.contains !== undefined;
1855
- if (hasComparisonOps) {
1856
- // Ensure we only get instances that have this property
1857
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
1858
- }
1859
- }
1860
- else {
1861
- // Simple equality
1862
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
1863
- }
1864
- }
1865
- }
1866
- return conditions.join(' AND ');
1867
- }
1868
- /**
1869
- * Builds the SELECT fields for SurrealQL queries.
1870
- *
1871
- * @description
1872
- * Generates the field list for the SELECT clause, resolving properties and relations
1873
- * via subqueries. Each property is fetched with a subquery that finds the link with the
1874
- * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
1875
- *
1876
- * Field types:
1877
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1878
- * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
1879
- * - Author/Timestamp: Always included to provide metadata about each instance
1880
- *
1881
- * If properties or relations arrays are provided, only those fields are included.
1882
- * Otherwise, all properties/relations from metadata are included.
1883
- *
1884
- * @param metadata - Model metadata containing property and relation predicates
1885
- * @param properties - Optional array of property names to include (default: all)
1886
- * @param relations - Optional array of relation names to include (default: all)
1887
- * @returns Comma-separated SELECT field list
1888
- *
1889
- * @private
1890
- */
1891
- static buildSurrealSelectFields(metadata, properties, relations) {
1892
- const fields = [];
1893
- // Determine properties to fetch
1894
- const propsToFetch = properties || Object.keys(metadata.properties);
1895
- for (const propName of propsToFetch) {
1896
- const propMeta = metadata.properties[propName];
1897
- if (!propMeta)
1898
- continue; // Skip if not found
1899
- // Reference source directly since we're selecting from link table
1900
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1901
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1902
- }
1903
- // Determine relations to fetch
1904
- const relsToFetch = relations || Object.keys(metadata.relations);
1905
- for (const relName of relsToFetch) {
1906
- const relMeta = metadata.relations[relName];
1907
- if (!relMeta)
1908
- continue; // Skip if not found
1909
- // Reference source directly since we're selecting from link table
1910
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1911
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${relName}`);
1912
- }
1913
- // Always add author and timestamp fields
1914
- fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1915
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1916
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1917
- return fields.join(',\n ');
1918
- }
1919
- /**
1920
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
1921
- * Compatible with GROUP BY source queries.
1922
- *
1923
- * @private
1924
- */
1925
- static buildSurrealSelectFieldsWithAggregation(metadata, properties, relations) {
1926
- const fields = [];
1927
- // Determine properties to fetch
1928
- const propsToFetch = properties || Object.keys(metadata.properties);
1929
- for (const propName of propsToFetch) {
1930
- const propMeta = metadata.properties[propName];
1931
- if (!propMeta)
1932
- continue; // Skip if not found
1933
- // Use array::first to get the first target value for this predicate
1934
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1935
- fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1936
- }
1937
- // Determine relations to fetch
1938
- const relsToFetch = relations || Object.keys(metadata.relations);
1939
- for (const relName of relsToFetch) {
1940
- const relMeta = metadata.relations[relName];
1941
- if (!relMeta)
1942
- continue; // Skip if not found
1943
- // Use array filtering to get all target values for this predicate
1944
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
1945
- fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${relName}`);
1946
- }
1947
- // Always add author and timestamp fields
1948
- fields.push(`array::first(author) AS author`);
1949
- fields.push(`array::first(timestamp) AS createdAt`);
1950
- fields.push(`array::last(timestamp) AS updatedAt`);
1951
- return fields.join(',\n ');
1952
- }
1953
- /**
1954
- * Formats a value for use in SurrealQL queries.
1955
- *
1956
- * @description
1957
- * Handles different value types:
1958
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
1959
- * - Numbers/booleans: Converted to string
1960
- * - Arrays: Recursively formatted and wrapped in brackets
1961
- *
1962
- * @param value - The value to format
1963
- * @returns Formatted value string ready for SurrealQL
1964
- *
1965
- * @private
1966
- */
1967
- static formatSurrealValue(value) {
1968
- return _formatSurrealValue(value);
1969
- }
1970
- static async instancesFromPrologResult(perspective, query, result) {
1971
- if (!result?.[0]?.AllInstances)
1972
- return { results: [], totalCount: 0 };
1973
- // Map results to instances
1974
- const requestedProperties = query?.properties || [];
1975
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1976
- try {
1977
- const instance = new this(perspective, Base);
1978
- // Remove unrequested attributes from instance
1979
- if (requestedProperties.length) {
1980
- Object.keys(instance).forEach((key) => {
1981
- if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
1982
- delete instance[key];
1983
- });
1984
- }
1985
- // Collect values to assign to instance
1986
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1987
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1988
- return instance;
1989
- }
1990
- catch (error) {
1991
- console.error(`Failed to process instance ${Base}:`, error);
1992
- // Return null for failed instances - we'll filter these out below
1993
- return null;
1994
- }
1995
- }));
1996
- const instances = allInstances.filter((instance) => instance !== null);
1997
- // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1998
- if (query.include && instances.length > 0) {
1999
- await this.hydrateRelations(instances, perspective, query.include);
2000
- }
2001
- // Take snapshots for dirty tracking after ALL hydration is complete
2002
- // (including eager-loaded relations).
2003
- // When `include` is specified, only snapshot those relations.
2004
- // Otherwise snapshot ALL fields (properties + relations) since
2005
- // hydrateFromLinks populates relations with stable raw IDs.
2006
- const snapshotRelations = query.include;
2007
- for (const inst of instances) {
2008
- inst.takeSnapshot(snapshotRelations);
2009
- }
2010
- return { results: instances, totalCount: result[0].TotalCount };
2011
- }
2012
- /**
2013
- * Converts SurrealDB query results to Ad4mModel instances.
2014
- *
2015
- * @param perspective - The perspective context
2016
- * @param query - The query parameters used
2017
- * @param result - Array of result objects from SurrealDB
2018
- * @returns Promise resolving to results with total count
2019
- *
2020
- * @internal
689
+ * @internal
2021
690
  */
2022
691
  static async instancesFromSurrealResult(perspective, query, result) {
2023
692
  if (!result || result.length === 0)
@@ -2041,7 +710,7 @@ FETCH links
2041
710
  const links = row.links || [];
2042
711
  const instance = new this(perspective, base);
2043
712
  // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
2044
- await this.hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
713
+ await hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
2045
714
  // When specific properties are requested, delete unrequested properties
2046
715
  // so they return undefined instead of their constructor defaults (e.g. 0, [])
2047
716
  if (requestedProperties.length > 0) {
@@ -2097,7 +766,7 @@ FETCH links
2097
766
  ? { requestedProperties, include: query.include }
2098
767
  : undefined;
2099
768
  for (const instance of instances) {
2100
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
769
+ await evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
2101
770
  }
2102
771
  // Filter by where conditions that couldn't be filtered in SQL
2103
772
  // This includes:
@@ -2113,7 +782,7 @@ FETCH links
2113
782
  continue;
2114
783
  // For author and timestamp, always filter in JS
2115
784
  if (propertyName === 'author' || propertyName === 'timestamp') {
2116
- if (!this.matchesCondition(instance[propertyName], condition)) {
785
+ if (!matchesCondition(instance[propertyName], condition)) {
2117
786
  return false;
2118
787
  }
2119
788
  continue;
@@ -2127,7 +796,7 @@ FETCH links
2127
796
  ops.lt !== undefined || ops.lte !== undefined ||
2128
797
  ops.between !== undefined || ops.contains !== undefined;
2129
798
  if (hasComparisonOps) {
2130
- if (!this.matchesCondition(instance[propertyName], condition)) {
799
+ if (!matchesCondition(instance[propertyName], condition)) {
2131
800
  return false;
2132
801
  }
2133
802
  }
@@ -2184,7 +853,7 @@ FETCH links
2184
853
  }
2185
854
  // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
2186
855
  if (query.include && paginatedInstances.length > 0) {
2187
- await this.hydrateRelations(paginatedInstances, perspective, query.include);
856
+ await hydrateRelations(this, paginatedInstances, perspective, query.include);
2188
857
  }
2189
858
  // Take snapshots for dirty tracking after ALL hydration is complete
2190
859
  // (including eager-loaded relations).
@@ -2201,62 +870,6 @@ FETCH links
2201
870
  totalCount
2202
871
  };
2203
872
  }
2204
- /**
2205
- * Checks if a value matches a condition (for post-query filtering).
2206
- * @private
2207
- */
2208
- static matchesCondition(value, condition) {
2209
- // Handle array values (IN clause)
2210
- if (Array.isArray(condition)) {
2211
- return condition.includes(value);
2212
- }
2213
- // Handle operator object
2214
- if (typeof condition === 'object' && condition !== null) {
2215
- const ops = condition;
2216
- // Special case: 'not' operator (exclusive with other operators)
2217
- if (ops.not !== undefined) {
2218
- if (Array.isArray(ops.not)) {
2219
- return !ops.not.includes(value);
2220
- }
2221
- else {
2222
- return value !== ops.not;
2223
- }
2224
- }
2225
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
2226
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
2227
- return value >= ops.between[0] && value <= ops.between[1];
2228
- }
2229
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
2230
- // and return true only if ALL conditions are satisfied
2231
- let allConditionsMet = true;
2232
- if (ops.gt !== undefined) {
2233
- allConditionsMet = allConditionsMet && (value > ops.gt);
2234
- }
2235
- if (ops.gte !== undefined) {
2236
- allConditionsMet = allConditionsMet && (value >= ops.gte);
2237
- }
2238
- if (ops.lt !== undefined) {
2239
- allConditionsMet = allConditionsMet && (value < ops.lt);
2240
- }
2241
- if (ops.lte !== undefined) {
2242
- allConditionsMet = allConditionsMet && (value <= ops.lte);
2243
- }
2244
- if (ops.contains !== undefined) {
2245
- if (typeof value === 'string') {
2246
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
2247
- }
2248
- else if (Array.isArray(value)) {
2249
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
2250
- }
2251
- else {
2252
- allConditionsMet = false;
2253
- }
2254
- }
2255
- return allConditionsMet;
2256
- }
2257
- // Simple equality
2258
- return value === condition;
2259
- }
2260
873
  /**
2261
874
  * Gets all instances of the model in the perspective that match the query params.
2262
875
  *
@@ -2464,7 +1077,6 @@ FETCH links
2464
1077
  }
2465
1078
  }
2466
1079
  async setProperty(key, value, batchId) {
2467
- // Phase 1: Use metadata instead of Prolog queries
2468
1080
  const metadata = this.getPropertyMetadata(key);
2469
1081
  if (!metadata) {
2470
1082
  console.warn(`Property "${key}" has no metadata, skipping`);
@@ -2493,7 +1105,6 @@ FETCH links
2493
1105
  return String(value);
2494
1106
  }
2495
1107
  async setRelationValues(key, value, batchId) {
2496
- // Phase 1: Use metadata instead of Prolog queries
2497
1108
  const metadata = this.getRelationOptions(key);
2498
1109
  if (!metadata) {
2499
1110
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2511,7 +1122,6 @@ FETCH links
2511
1122
  }
2512
1123
  }
2513
1124
  async addRelationValue(key, value, batchId) {
2514
- // Phase 1: Use metadata instead of Prolog queries
2515
1125
  const metadata = this.getRelationOptions(key);
2516
1126
  if (!metadata) {
2517
1127
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2529,7 +1139,6 @@ FETCH links
2529
1139
  }
2530
1140
  }
2531
1141
  async removeRelationValue(key, value, batchId) {
2532
- // Phase 1: Use metadata instead of Prolog queries
2533
1142
  const metadata = this.getRelationOptions(key);
2534
1143
  if (!metadata) {
2535
1144
  console.warn(`Relation "${key}" has no metadata, skipping`);
@@ -2676,7 +1285,6 @@ FETCH links
2676
1285
  }
2677
1286
  async innerUpdate(setProperties = true, batchId) {
2678
1287
  const ctor = this.constructor;
2679
- this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2680
1288
  // Determine which fields actually changed (skip unchanged when snapshot exists)
2681
1289
  const dirty = this._snapshot ? new Set(this.changedFields()) : null;
2682
1290
  // Only iterate schema-declared fields, not internal ORM properties
@@ -2784,7 +1392,6 @@ FETCH links
2784
1392
  else {
2785
1393
  opts = { include: optsOrInclude };
2786
1394
  }
2787
- this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2788
1395
  return await this.getData(opts);
2789
1396
  }
2790
1397
  /**
@@ -2856,6 +1463,9 @@ FETCH links
2856
1463
  console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);
2857
1464
  }
2858
1465
  }
1466
+ // ──────────────────────────────────────────────────────────
1467
+ // Static convenience methods
1468
+ // ──────────────────────────────────────────────────────────
2859
1469
  /**
2860
1470
  * Creates and saves a new model instance in one step.
2861
1471
  *
@@ -3112,929 +1722,7 @@ FETCH links
3112
1722
  * @throws Error when namespace cannot be inferred
3113
1723
  */
3114
1724
  static fromJSONSchema(schema, options) {
3115
- // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
3116
- if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
3117
- throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
3118
- }
3119
- // Determine namespace with cascading precedence
3120
- const namespace = this.determineNamespace(schema, options);
3121
- // Create the dynamic class
3122
- const DynamicModelClass = class extends Ad4mModel {
3123
- };
3124
- // Set up class metadata
3125
- if (!options.name || options.name.trim() === '') {
3126
- throw new Error("options.name is required and cannot be empty");
3127
- }
3128
- DynamicModelClass.className = options.name;
3129
- DynamicModelClass.prototype.className = options.name;
3130
- // Generate properties and relations metadata
3131
- const properties = {};
3132
- const relations = {};
3133
- if (schema.properties) {
3134
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
3135
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
3136
- const isRequired = schema.required?.includes(propertyName) || false;
3137
- const propertyType = normalizeSchemaType(propertySchema.type);
3138
- const isArray = isArrayType(propertySchema);
3139
- if (isArray) {
3140
- // Handle arrays as relations
3141
- // Store the singular form as the relation key since SDNA generation expects singular
3142
- relations[propertyName] = {
3143
- through: predicate,
3144
- local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
3145
- };
3146
- // Define the property on prototype
3147
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3148
- configurable: true,
3149
- writable: true,
3150
- value: []
3151
- });
3152
- // Add relation methods
3153
- const adderName = `add${capitalize(propertyName)}`;
3154
- const removerName = `remove${capitalize(propertyName)}`;
3155
- const setterName = `set${capitalize(propertyName)}`;
3156
- DynamicModelClass.prototype[adderName] = function () {
3157
- // Placeholder function for SDNA generation
3158
- };
3159
- DynamicModelClass.prototype[removerName] = function () {
3160
- // Placeholder function for SDNA generation
3161
- };
3162
- DynamicModelClass.prototype[setterName] = function () {
3163
- // Placeholder function for SDNA generation
3164
- };
3165
- }
3166
- else {
3167
- // Handle regular properties
3168
- let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
3169
- // If no specific resolveLanguage for this property, use the global one
3170
- if (!resolveLanguage && options.resolveLanguage) {
3171
- resolveLanguage = options.resolveLanguage;
3172
- }
3173
- const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
3174
- // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
3175
- let readOnly = this.getPropertyOption(propertyName, propertySchema, options, 'readOnly');
3176
- if (readOnly === undefined) {
3177
- const xWritable = propertySchema["x-ad4m"]?.writable;
3178
- readOnly = xWritable !== undefined ? !xWritable : false;
3179
- }
3180
- const writable = !readOnly;
3181
- let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
3182
- // Handle nested objects by serializing to JSON
3183
- if (isObjectType(propertySchema) && !resolveLanguage) {
3184
- resolveLanguage = 'literal';
3185
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
3186
- }
3187
- // Ensure numeric properties use literal language for correct typing
3188
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
3189
- resolveLanguage = 'literal';
3190
- }
3191
- // Default resolveLanguage to 'literal' for all remaining property types,
3192
- // matching the @Property decorator behaviour. Without this, string values
3193
- // stored as literal:// URLs are returned unparsed.
3194
- if (resolveLanguage === undefined || resolveLanguage === null) {
3195
- resolveLanguage = 'literal';
3196
- }
3197
- // If property is required, ensure it has an initial value
3198
- if (isRequired && !initial) {
3199
- if (isObjectType(propertySchema)) {
3200
- initial = 'literal://json:{}';
3201
- }
3202
- else {
3203
- initial = "ad4m://undefined";
3204
- }
3205
- }
3206
- properties[propertyName] = {
3207
- through: predicate,
3208
- required: isRequired,
3209
- writable: writable,
3210
- ...(resolveLanguage && { resolveLanguage }),
3211
- ...(local !== undefined && { local }),
3212
- ...(initial && { initial })
3213
- };
3214
- // Define the property on prototype
3215
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3216
- configurable: true,
3217
- writable: true,
3218
- value: this.getDefaultValueForType(propertyType)
3219
- });
3220
- // Add setter function if writable
3221
- if (writable) {
3222
- const setterName = propertyNameToSetterName(propertyName);
3223
- DynamicModelClass.prototype[setterName] = function () {
3224
- // This is a placeholder function that the SDNA generation looks for
3225
- // The actual setter logic is handled by the Ad4mModel base class
3226
- };
3227
- }
3228
- }
3229
- }
3230
- }
3231
- // No auto-flag generation — models with all-optional properties use
3232
- // open-world structural matching. Consumers who need type discrimination
3233
- // should add an explicit @Flag to their model definition.
3234
- // Attach metadata to WeakMap registries
3235
- for (const [propName, propMeta] of Object.entries(properties)) {
3236
- setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);
3237
- }
3238
- for (const [relName, relMeta] of Object.entries(relations)) {
3239
- setRelationRegistryEntry(DynamicModelClass, relName, {
3240
- predicate: relMeta.through || "",
3241
- kind: 'hasMany',
3242
- ...(relMeta.getter !== undefined && { getter: relMeta.getter }),
3243
- ...(relMeta.local !== undefined && { local: relMeta.local }),
3244
- });
3245
- }
3246
- // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
3247
- DynamicModelClass.prototype.__jsonSchema = schema;
3248
- DynamicModelClass.prototype.__jsonSchemaOptions = options;
3249
- // Apply the Model decorator to set up the generateSDNA method
3250
- const ModelDecorator = Model({ name: options.name });
3251
- ModelDecorator(DynamicModelClass);
3252
- return DynamicModelClass;
3253
- }
3254
- /**
3255
- * Determines the namespace for predicates using cascading precedence
3256
- */
3257
- static determineNamespace(schema, options) {
3258
- // 1. Explicit namespace in options (highest precedence)
3259
- if (options.namespace) {
3260
- return options.namespace;
3261
- }
3262
- // 2. x-ad4m metadata in schema
3263
- if (schema["x-ad4m"]?.namespace) {
3264
- return schema["x-ad4m"].namespace;
3265
- }
3266
- // 3. Infer from schema title
3267
- if (schema.title) {
3268
- return `${schema.title.toLowerCase()}://`;
3269
- }
3270
- // 4. Try to extract from $id if it's a URL
3271
- if (schema.$id) {
3272
- try {
3273
- const url = new URL(schema.$id);
3274
- const pathParts = url.pathname.split('/').filter(p => p);
3275
- if (pathParts.length > 0) {
3276
- const lastPart = pathParts[pathParts.length - 1];
3277
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
3278
- return `${baseName.toLowerCase()}://`;
3279
- }
3280
- }
3281
- catch {
3282
- // If $id is not a valid URL, continue to error
3283
- }
3284
- }
3285
- // 5. Error if no namespace can be determined
3286
- throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
3287
- - options.namespace
3288
- - schema["x-ad4m"].namespace
3289
- - schema.title
3290
- - valid schema.$id`);
3291
- }
3292
- /**
3293
- * Determines the predicate for a specific property using cascading precedence
3294
- */
3295
- static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
3296
- // 1. Explicit property mapping (highest precedence)
3297
- if (options.propertyMapping?.[propertyName]) {
3298
- return options.propertyMapping[propertyName];
3299
- }
3300
- // 2. x-ad4m metadata in property schema
3301
- if (propertySchema["x-ad4m"]?.through) {
3302
- return propertySchema["x-ad4m"].through;
3303
- }
3304
- // 3. Generate from namespace + property name
3305
- if (options.predicateTemplate) {
3306
- const normalizedNs = normalizeNamespaceString(namespace);
3307
- const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
3308
- const nsNoScheme = rest || '';
3309
- return options.predicateTemplate
3310
- .replace('${namespace}', nsNoScheme)
3311
- .replace('${scheme}', scheme)
3312
- .replace('${ns}', nsNoScheme)
3313
- .replace('${title}', schema.title || '')
3314
- .replace('${property}', propertyName);
3315
- }
3316
- // 4. Custom predicate generator
3317
- if (options.predicateGenerator) {
3318
- return options.predicateGenerator(schema.title || '', propertyName);
3319
- }
3320
- // 5. Default: namespace + property name
3321
- const normalizedNs = normalizeNamespaceString(namespace);
3322
- if (normalizedNs.includes('://')) {
3323
- // For namespaces like "product://", append property directly
3324
- return `${normalizedNs}${propertyName}`;
3325
- }
3326
- else {
3327
- return `${normalizedNs}://${propertyName}`;
3328
- }
3329
- }
3330
- /**
3331
- * Gets property-specific options using cascading precedence
3332
- */
3333
- static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
3334
- // 1. Property-specific options
3335
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
3336
- return options.propertyOptions[propertyName][optionName];
3337
- }
3338
- // 2. x-ad4m metadata in property
3339
- if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
3340
- return propertySchema["x-ad4m"][optionName];
3341
- }
3342
- // 3. Global option
3343
- if (options[optionName] !== undefined) {
3344
- return options[optionName];
3345
- }
3346
- // 4. Default value
3347
- return defaultValue;
3348
- }
3349
- /**
3350
- * Gets default value for a JSON Schema type
3351
- */
3352
- static getDefaultValueForType(type) {
3353
- switch (type) {
3354
- case 'string': return '';
3355
- case 'number': return 0;
3356
- case 'integer': return 0;
3357
- case 'boolean': return false;
3358
- case 'array': return [];
3359
- case 'object': return {};
3360
- default: return '';
3361
- }
1725
+ return buildModelFromJSONSchema(this, schema, options);
3362
1726
  }
3363
1727
  }
3364
1728
  Ad4mModel.classNamesByClass = new WeakMap();
3365
- /** Query builder for Ad4mModel queries.
3366
- * Allows building queries with a fluent interface and either running them once
3367
- * or subscribing to updates.
3368
- *
3369
- * @example
3370
- * ```typescript
3371
- * const builder = Recipe.query(perspective)
3372
- * .where({ category: "Dessert" })
3373
- * .order({ rating: "DESC" })
3374
- * .limit(10);
3375
- *
3376
- * // Run once
3377
- * const recipes = await builder.run();
3378
- *
3379
- * // Or subscribe to updates
3380
- * await builder.subscribe(recipes => {
3381
- * console.log("Updated recipes:", recipes);
3382
- * });
3383
- * ```
3384
- */
3385
- export class ModelQueryBuilder {
3386
- constructor(perspective, ctor, query) {
3387
- this.queryParams = {};
3388
- this.modelClassName = null;
3389
- this.useSurrealDBFlag = true;
3390
- this.perspective = perspective;
3391
- this.ctor = ctor;
3392
- if (query)
3393
- this.queryParams = query;
3394
- }
3395
- /**
3396
- * Disposes of the current subscription if one exists.
3397
- *
3398
- * This method:
3399
- * 1. Stops the keepalive signals to the subscription
3400
- * 2. Unsubscribes from GraphQL subscription updates
3401
- * 3. Notifies the backend to clean up subscription resources
3402
- * 4. Clears the subscription reference
3403
- *
3404
- * You should call this method when you're done with a subscription
3405
- * to prevent memory leaks and ensure proper cleanup.
3406
- */
3407
- dispose() {
3408
- if (this.currentSubscription) {
3409
- this.currentSubscription.dispose();
3410
- this.currentSubscription = undefined;
3411
- }
3412
- }
3413
- /**
3414
- * Adds where conditions to the query.
3415
- *
3416
- * @param conditions - The conditions to filter by
3417
- * @returns The query builder for chaining
3418
- *
3419
- * @example
3420
- * ```typescript
3421
- * .where({
3422
- * category: "Dessert",
3423
- * rating: { gt: 4 },
3424
- * tags: ["vegan", "quick"],
3425
- * published: true
3426
- * })
3427
- * ```
3428
- */
3429
- where(conditions) {
3430
- this.queryParams.where = conditions;
3431
- return this;
3432
- }
3433
- /**
3434
- * Sets the order for the query results.
3435
- *
3436
- * @param orderBy - The ordering criteria
3437
- * @returns The query builder for chaining
3438
- *
3439
- * @example
3440
- * ```typescript
3441
- * .order({ createdAt: "DESC" })
3442
- * ```
3443
- */
3444
- order(orderBy) {
3445
- this.queryParams.order = orderBy;
3446
- return this;
3447
- }
3448
- /**
3449
- * Sets the maximum number of results to return.
3450
- *
3451
- * @param limit - Maximum number of results
3452
- * @returns The query builder for chaining
3453
- *
3454
- * @example
3455
- * ```typescript
3456
- * .limit(10)
3457
- * ```
3458
- */
3459
- limit(limit) {
3460
- this.queryParams.limit = limit;
3461
- return this;
3462
- }
3463
- /**
3464
- * Sets the number of results to skip.
3465
- *
3466
- * @param offset - Number of results to skip
3467
- * @returns The query builder for chaining
3468
- *
3469
- * @example
3470
- * ```typescript
3471
- * .offset(20) // Skip first 20 results
3472
- * ```
3473
- */
3474
- offset(offset) {
3475
- this.queryParams.offset = offset;
3476
- return this;
3477
- }
3478
- /**
3479
- * Scopes the query to instances linked from a parent.
3480
- *
3481
- * The predicate is resolved in order of precedence:
3482
- * 1. **Instance only** — the parent's constructor is used as the model
3483
- * class; its relation metadata is scanned for a relation whose
3484
- * `target()` matches the queried model class.
3485
- * 2. **Instance + options with `field`** — direct field-name lookup on
3486
- * the parent model's relation metadata (disambiguates when a parent
3487
- * has multiple relations targeting the same child class).
3488
- * 3. **String id + model class** — same metadata scan (or field lookup if
3489
- * options include `field`).
3490
- * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
3491
- *
3492
- * Passing a plain string id with no second argument throws because the
3493
- * predicate cannot be resolved without a model class.
3494
- *
3495
- * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
3496
- * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
3497
- * @param options - Optional settings: `field` for direct relation-name lookup
3498
- * @returns The query builder for chaining
3499
- *
3500
- * @example
3501
- * ```typescript
3502
- * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
3503
- * Recipe.query(perspective).parent(cookbook).get();
3504
- *
3505
- * // Instance + field — disambiguate when parent has multiple relations to same child
3506
- * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
3507
- *
3508
- * // String id + model class
3509
- * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
3510
- *
3511
- * // String id + model class + field
3512
- * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
3513
- *
3514
- * // String id + raw predicate (escape hatch)
3515
- * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
3516
- * ```
3517
- */
3518
- parent(idOrInstance, modelOrPredicate, options) {
3519
- const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;
3520
- // Handle options-object as second arg: parent(instance, { field: "recipes" })
3521
- if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {
3522
- if (typeof idOrInstance === 'string') {
3523
- throw new Error('parent() called with a string id and options object requires a model class as second argument');
3524
- }
3525
- const model = idOrInstance.constructor;
3526
- this.queryParams.parent = { id, model, field: modelOrPredicate.field };
3527
- return this;
3528
- }
3529
- const field = options?.field;
3530
- if (typeof modelOrPredicate === 'string') {
3531
- // Raw predicate string → raw form of ParentScope
3532
- this.queryParams.parent = { id, predicate: modelOrPredicate };
3533
- }
3534
- else if (typeof modelOrPredicate === 'function') {
3535
- // Model class → model form of ParentScope
3536
- this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
3537
- }
3538
- else if (typeof idOrInstance !== 'string') {
3539
- // Ad4mModel instance — derive model class from constructor
3540
- this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
3541
- }
3542
- else {
3543
- throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
3544
- }
3545
- return this;
3546
- }
3547
- /**
3548
- * Specifies which properties to include in the results.
3549
- *
3550
- * @param properties - Array of property names to include
3551
- * @returns The query builder for chaining
3552
- *
3553
- * @example
3554
- * ```typescript
3555
- * .properties(["name", "description", "rating"])
3556
- * ```
3557
- */
3558
- properties(properties) {
3559
- this.queryParams.properties = properties;
3560
- return this;
3561
- }
3562
- /**
3563
- * Specifies which relations to eager-load (hydrate into model instances).
3564
- *
3565
- * Without `include`, relation fields contain raw expression URIs (strings).
3566
- * With `include`, the URIs are resolved into fully-hydrated model instances
3567
- * using the `target` class declared in the relation decorator.
3568
- *
3569
- * Supports nested includes for multi-level eager loading.
3570
- *
3571
- * @param map - An IncludeMap describing which relations to hydrate
3572
- * @returns The query builder for chaining
3573
- *
3574
- * @example
3575
- * ```typescript
3576
- * // Hydrate comments one level deep
3577
- * const recipes = await Recipe.query(perspective)
3578
- * .include({ comments: true })
3579
- * .run();
3580
- * // recipe.comments is now Comment[] (model instances), not string[]
3581
- *
3582
- * // Nested: hydrate comments AND each comment's author
3583
- * const recipes = await Recipe.query(perspective)
3584
- * .include({ comments: { author: true } })
3585
- * .run();
3586
- * ```
3587
- */
3588
- include(map) {
3589
- this.queryParams.include = map;
3590
- return this;
3591
- }
3592
- overrideModelClassName(className) {
3593
- this.modelClassName = className;
3594
- return this;
3595
- }
3596
- /**
3597
- * Enables or disables SurrealDB query path.
3598
- *
3599
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
3600
- * @returns The query builder for chaining
3601
- *
3602
- * @example
3603
- * ```typescript
3604
- * // Use SurrealDB (default)
3605
- * const recipes = await Recipe.query(perspective)
3606
- * .where({ category: "Dessert" })
3607
- * .useSurrealDB(true)
3608
- * .get();
3609
- *
3610
- * // Use Prolog (legacy)
3611
- * const recipesProlog = await Recipe.query(perspective)
3612
- * .where({ category: "Dessert" })
3613
- * .useSurrealDB(false)
3614
- * .get();
3615
- * ```
3616
- *
3617
- * @remarks
3618
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
3619
- * if useSurrealDB(true) is set (default).
3620
- */
3621
- useSurrealDB(enabled = true) {
3622
- this.useSurrealDBFlag = enabled;
3623
- return this;
3624
- }
3625
- /**
3626
- * Executes the query once and returns the results.
3627
- *
3628
- * @returns Array of matching entities
3629
- *
3630
- * @example
3631
- * ```typescript
3632
- * const recipes = await Recipe.query(perspective)
3633
- * .where({ category: "Dessert" })
3634
- * .get();
3635
- * ```
3636
- */
3637
- async get() {
3638
- let results;
3639
- if (this.useSurrealDBFlag) {
3640
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3641
- const result = await this.perspective.querySurrealDB(surrealQuery);
3642
- ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
3643
- }
3644
- else {
3645
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3646
- const result = await this.perspective.infer(query);
3647
- ({ results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result));
3648
- }
3649
- return results;
3650
- }
3651
- /**
3652
- * Returns the first matching instance, or `null` if none match.
3653
- *
3654
- * Internally sets `limit: 1` and delegates to `get()`.
3655
- *
3656
- * @returns The first matching instance, or `null`
3657
- *
3658
- * @example
3659
- * ```typescript
3660
- * const recipe = await Recipe.query(perspective)
3661
- * .where({ name: "Pasta" })
3662
- * .first();
3663
- * ```
3664
- */
3665
- async first() {
3666
- this.queryParams.limit = 1;
3667
- const results = await this.get();
3668
- return results[0] ?? null;
3669
- }
3670
- /**
3671
- * Subscribes to the query and receives updates when results change.
3672
- *
3673
- * This method:
3674
- * 1. Creates and initializes a SurrealDB live query subscription (default)
3675
- * 2. Sets up the callback to process future updates
3676
- * 3. Returns the initial results immediately
3677
- *
3678
- * Remember to call dispose() when you're done with the subscription
3679
- * to clean up resources.
3680
- *
3681
- * @param callback - Function to call with updated results
3682
- * @returns Initial results array
3683
- *
3684
- * @example
3685
- * ```typescript
3686
- * const builder = Recipe.query(perspective)
3687
- * .where({ status: "cooking" });
3688
- *
3689
- * const initialRecipes = await builder.subscribe(recipes => {
3690
- * console.log("Updated recipes:", recipes);
3691
- * });
3692
- *
3693
- * // When done with subscription:
3694
- * builder.dispose();
3695
- * ```
3696
- *
3697
- * @remarks
3698
- * By default, this uses SurrealDB live queries for real-time updates.
3699
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3700
- */
3701
- async subscribe(callback) {
3702
- // Clean up any existing subscription
3703
- this.dispose();
3704
- const ctor = this.ctor;
3705
- if (this.useSurrealDBFlag) {
3706
- const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
3707
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3708
- const processResults = async (result) => {
3709
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3710
- callback(results);
3711
- };
3712
- this.currentSubscription.onResult(processResults);
3713
- // Process initial result
3714
- const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3715
- // Also invoke callback with initial results so subscribers see them
3716
- callback(results);
3717
- return results;
3718
- }
3719
- else {
3720
- const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3721
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3722
- const processResults = async (result) => {
3723
- const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3724
- callback(results);
3725
- };
3726
- this.currentSubscription.onResult(processResults);
3727
- const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
3728
- // Also invoke callback with initial results so subscribers see them
3729
- callback(results);
3730
- return results;
3731
- }
3732
- }
3733
- /**
3734
- * Gets the total count of matching entities.
3735
- *
3736
- * @returns Total count
3737
- *
3738
- * @example
3739
- * ```typescript
3740
- * const totalDesserts = await Recipe.query(perspective)
3741
- * .where({ category: "Dessert" })
3742
- * .count();
3743
- * ```
3744
- */
3745
- async count() {
3746
- if (this.useSurrealDBFlag) {
3747
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3748
- const result = await this.perspective.querySurrealDB(surrealQuery);
3749
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
3750
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
3751
- // This ensures count() returns the same number as get().length
3752
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3753
- return totalCount;
3754
- }
3755
- else {
3756
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3757
- const result = await this.perspective.infer(query);
3758
- return result?.[0]?.TotalCount || 0;
3759
- }
3760
- }
3761
- /**
3762
- * Subscribes to count updates for matching entities.
3763
- *
3764
- * This method:
3765
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
3766
- * 2. Sets up the callback to process future count updates
3767
- * 3. Returns the initial count immediately
3768
- *
3769
- * Remember to call dispose() when you're done with the subscription
3770
- * to clean up resources.
3771
- *
3772
- * @param callback - Function to call with updated count
3773
- * @returns Initial count
3774
- *
3775
- * @example
3776
- * ```typescript
3777
- * const builder = Recipe.query(perspective)
3778
- * .where({ status: "active" });
3779
- *
3780
- * const initialCount = await builder.countSubscribe(count => {
3781
- * console.log("Active items:", count);
3782
- * });
3783
- *
3784
- * // When done with subscription:
3785
- * builder.dispose();
3786
- * ```
3787
- *
3788
- * @remarks
3789
- * By default, this uses SurrealDB live queries for real-time updates.
3790
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3791
- */
3792
- async countSubscribe(callback) {
3793
- // Clean up any existing subscription
3794
- this.dispose();
3795
- if (this.useSurrealDBFlag) {
3796
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3797
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3798
- const processResults = async (result) => {
3799
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3800
- callback(totalCount);
3801
- };
3802
- this.currentSubscription.onResult(processResults);
3803
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3804
- callback(totalCount);
3805
- return totalCount;
3806
- }
3807
- else {
3808
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3809
- this.currentSubscription = await this.perspective.subscribeInfer(query);
3810
- const processResults = async (result) => {
3811
- const newCount = result?.[0]?.TotalCount || 0;
3812
- callback(newCount);
3813
- };
3814
- this.currentSubscription.onResult(processResults);
3815
- const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
3816
- callback(initialCount);
3817
- return initialCount;
3818
- }
3819
- }
3820
- /**
3821
- * Gets a page of results with pagination metadata.
3822
- *
3823
- * @param pageSize - Number of items per page
3824
- * @param pageNumber - Which page to retrieve (1-based)
3825
- * @returns Paginated results with metadata
3826
- *
3827
- * @example
3828
- * ```typescript
3829
- * const page = await Recipe.query(perspective)
3830
- * .where({ category: "Main" })
3831
- * .paginate(10, 1);
3832
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
3833
- * ```
3834
- */
3835
- async paginate(pageSize, pageNumber) {
3836
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3837
- if (this.useSurrealDBFlag) {
3838
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3839
- const result = await this.perspective.querySurrealDB(surrealQuery);
3840
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3841
- return { results, totalCount, pageSize, pageNumber };
3842
- }
3843
- else {
3844
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3845
- const result = await this.perspective.infer(prologQuery);
3846
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
3847
- return { results, totalCount, pageSize, pageNumber };
3848
- }
3849
- }
3850
- /**
3851
- * Subscribes to paginated results updates.
3852
- *
3853
- * This method:
3854
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
3855
- * 2. Sets up the callback to process future page updates
3856
- * 3. Returns the initial page immediately
3857
- *
3858
- * Remember to call dispose() when you're done with the subscription
3859
- * to clean up resources.
3860
- *
3861
- * @param pageSize - Number of items per page
3862
- * @param pageNumber - Which page to retrieve (1-based)
3863
- * @param callback - Function to call with updated pagination results
3864
- * @returns Initial pagination results
3865
- *
3866
- * @example
3867
- * ```typescript
3868
- * const builder = Recipe.query(perspective)
3869
- * .where({ category: "Main" });
3870
- *
3871
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
3872
- * console.log("Updated page:", page.results);
3873
- * });
3874
- *
3875
- * // When done with subscription:
3876
- * builder.dispose();
3877
- * ```
3878
- *
3879
- * @remarks
3880
- * By default, this uses SurrealDB live queries for real-time updates.
3881
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
3882
- */
3883
- async paginateSubscribe(pageSize, pageNumber, callback) {
3884
- // Clean up any existing subscription
3885
- this.dispose();
3886
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3887
- if (this.useSurrealDBFlag) {
3888
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3889
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3890
- const processResults = async (result) => {
3891
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3892
- callback({ results, totalCount, pageSize, pageNumber });
3893
- };
3894
- this.currentSubscription.onResult(processResults);
3895
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
3896
- const initialPage = { results, totalCount, pageSize, pageNumber };
3897
- callback(initialPage);
3898
- return initialPage;
3899
- }
3900
- else {
3901
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3902
- this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
3903
- const processResults = async (r) => {
3904
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
3905
- callback({ results, totalCount, pageSize, pageNumber });
3906
- };
3907
- this.currentSubscription.onResult(processResults);
3908
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
3909
- const initialPrologPage = { results, totalCount, pageSize, pageNumber };
3910
- callback(initialPrologPage);
3911
- return initialPrologPage;
3912
- }
3913
- }
3914
- }
3915
- // ── Standalone Prolog fact generator ──────────────────────────────────────────
3916
- /**
3917
- * Convert a camelCase or PascalCase identifier to snake_case.
3918
- * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
3919
- */
3920
- function toSnakeCase(str) {
3921
- return str
3922
- .replace(/([A-Z])/g, "_$1")
3923
- .toLowerCase()
3924
- .replace(/^_/, "");
3925
- }
3926
- function buildInstanceClause(predicateName, metadata) {
3927
- const props = metadata.properties;
3928
- // Collect flags first — these are the strongest recognizers
3929
- const flags = Object.values(props).filter((p) => p.flag && p.predicate && p.initial);
3930
- if (flags.length > 0) {
3931
- const conditions = flags
3932
- .map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
3933
- .join(",\n ");
3934
- return `${predicateName}(X) :-\n ${conditions}.`;
3935
- }
3936
- // Fallback: required non-flag properties
3937
- const required = Object.values(props).filter((p) => p.required && p.predicate && !p.flag);
3938
- if (required.length > 0) {
3939
- const conditions = required
3940
- .map((p) => `triple(X, '${p.predicate}', _)`)
3941
- .join(",\n ");
3942
- return `${predicateName}(X) :-\n ${conditions}.`;
3943
- }
3944
- // Open-world structural fallback: match nodes that have at least one of the
3945
- // model's declared property predicates. Uses disjunction (;) so any single
3946
- // predicate is enough.
3947
- const allPredicates = Object.values(props)
3948
- .filter((p) => p.predicate)
3949
- .map((p) => p.predicate);
3950
- if (metadata.relations) {
3951
- for (const rel of Object.values(metadata.relations)) {
3952
- if (rel.predicate)
3953
- allPredicates.push(rel.predicate);
3954
- }
3955
- }
3956
- if (allPredicates.length > 0) {
3957
- const disjunction = allPredicates
3958
- .map((pred) => `triple(X, '${pred}', _)`)
3959
- .join(" ;\n ");
3960
- return `${predicateName}(X) :-\n (${disjunction}).`;
3961
- }
3962
- return null;
3963
- }
3964
- function buildPropertyClause(modelPredicateName, prop) {
3965
- if (prop.flag)
3966
- return null;
3967
- if (!prop.predicate)
3968
- return null;
3969
- const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
3970
- return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
3971
- }
3972
- function buildRelationClause(modelPredicateName, relation) {
3973
- if (!relation.predicate)
3974
- return null;
3975
- const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
3976
- if (relation.direction === "reverse") {
3977
- return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
3978
- }
3979
- return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
3980
- }
3981
- /**
3982
- * Generate Prolog predicate facts from a model class's decorator metadata.
3983
- *
3984
- * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
3985
- * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
3986
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
3987
- *
3988
- * The generated predicates are:
3989
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
3990
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
3991
- * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
3992
- *
3993
- * @example
3994
- * ```typescript
3995
- * import { generatePrologFacts } from '@coasys/ad4m';
3996
- *
3997
- * const facts = generatePrologFacts(Poll);
3998
- * const result = await perspective.infer(\`
3999
- * \${facts}
4000
- * recent_popular_poll(X) :-
4001
- * poll(X),
4002
- * poll_vote_count(X, N), N > 10.
4003
- * \`);
4004
- * ```
4005
- *
4006
- * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
4007
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
4008
- */
4009
- export function generatePrologFacts(ModelClass) {
4010
- const metadata = ModelClass.getModelMetadata();
4011
- const predicateName = toSnakeCase(metadata.className);
4012
- const lines = [];
4013
- lines.push(`% ${metadata.className} — generated Prolog facts`);
4014
- // Instance recognizer
4015
- const instanceClause = buildInstanceClause(predicateName, metadata);
4016
- if (instanceClause) {
4017
- lines.push("");
4018
- lines.push(`% Instance recognizer`);
4019
- lines.push(instanceClause);
4020
- }
4021
- // Property getters
4022
- const propClauses = Object.values(metadata.properties)
4023
- .map((p) => buildPropertyClause(predicateName, p))
4024
- .filter((c) => c !== null);
4025
- if (propClauses.length > 0) {
4026
- lines.push("");
4027
- lines.push(`% Field getters`);
4028
- lines.push(...propClauses);
4029
- }
4030
- // Relation getters
4031
- const relClauses = Object.values(metadata.relations)
4032
- .map((c) => buildRelationClause(predicateName, c))
4033
- .filter((c) => c !== null);
4034
- if (relClauses.length > 0) {
4035
- lines.push("");
4036
- lines.push(`% Relation getters`);
4037
- lines.push(...relClauses);
4038
- }
4039
- return lines.join("\n");
4040
- }