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

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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6893 -5884
  3. package/lib/index.js +6889 -5872
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3760 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4386 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -1,40 +1,327 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
- import { makeRandomId, getRelationsMetadata } from "./decorators";
5
- import { resolveParentPredicate } from "./parentUtils";
6
- export { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
7
- import * as mutation from "./mutation";
8
- import { capitalize } from "./util";
9
- // ── JSON Schema factory ────────────────────────────────────────────────────
10
- import { createModelFromJSONSchema } from "./schema/fromJSONSchema";
11
- // ── Fluent query builder (re-exported for consumers) ──────────────────────
12
- import { ModelQueryBuilder } from "./query/ModelQueryBuilder";
13
- export { ModelQueryBuilder };
14
- // ── SurrealDB query helpers (used internally, also re-exported) ────────────
15
- export { buildSurrealQuery, buildSurrealCountQuery, formatSurrealValue, matchesCondition, buildGraphTraversalWhereClause, } from "./query/surrealCompiler";
16
- // ── Hydration utilities (re-exported for advanced consumers) ──────────────
17
- export { hydrateInstanceFromLinks, evaluateCustomGetters, normalizeTimestamp, } from "./query/hydration";
18
- // ── Static query operations (each static method below delegates here) ─────────
19
- import * as ops from "./query/operations";
20
- import { fetchInstanceData } from "./query/fetchInstance";
21
- // ── Metadata helpers ────────────────────────────────────────────────────────
22
- import { getModelMetadata as _getModelMetadata } from "./schema/metadata";
23
- // ── Transaction API ──────────────────────────────────────────────────────────
24
- import { runTransaction } from "./transaction";
25
- // ── Subscription API ───────────────────────────────────────────────────────────────
26
- import { createSubscription } from "./subscription";
4
+ import { makeRandomId, Model, getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
5
+ import { propertyNameToSetterName } from "./util";
6
+ import { escapeSurrealString } from "../utils";
7
+ function capitalize(word) {
8
+ return word.charAt(0).toUpperCase() + word.slice(1);
9
+ }
27
10
  /**
28
- * Base class for all AD4M data models.
11
+ * Resolves the predicate for a parent query.
29
12
  *
30
- * Instances are subgraphs in a {@link PerspectiveProxy}; properties and relations
31
- * map to typed links. Decorators (`@Property`, `@HasMany`, etc.) declare the schema;
32
- * query helpers (`findAll`, `query`, `subscribe`) run SurrealQL against the
33
- * perspective's local graph engine.
13
+ * Uses TS discriminated union narrowing:
14
+ * - Raw form (`{ id, predicate }`) → predicate used as-is
15
+ * - Model form (`{ model, id, field? }`) → lookup from relation metadata
16
+ * - With `field`: direct key lookup
17
+ * - Without `field`: scan for a relation whose `target()` matches `childCtor`
18
+ */
19
+ function resolveParentPredicate(parent, childCtor) {
20
+ // Raw form — explicit predicate
21
+ if ('predicate' in parent)
22
+ return parent.predicate;
23
+ // Model form — resolve from relation metadata
24
+ const { model } = parent;
25
+ const relMeta = getRelationsMetadata(model);
26
+ // Direct lookup by field name when provided
27
+ if (parent.field) {
28
+ const entry = relMeta[parent.field];
29
+ if (!entry) {
30
+ throw new Error(`parent(): field "${parent.field}" is not a registered relation on ${model.name}`);
31
+ }
32
+ return entry.predicate;
33
+ }
34
+ // Fallback: scan for a relation whose target matches the child class
35
+ for (const [, entry] of Object.entries(relMeta)) {
36
+ if (entry.target && entry.target() === childCtor) {
37
+ return entry.predicate;
38
+ }
39
+ }
40
+ throw new Error(`parent(): could not resolve predicate — no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);
41
+ }
42
+ function buildParentQuery(parent, resolvedPredicate) {
43
+ if (!parent || !resolvedPredicate)
44
+ return '';
45
+ return `triple("${parent.id}", "${resolvedPredicate}", Base)`;
46
+ }
47
+ // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
48
+ function buildAuthorAndTimestampQuery() {
49
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
50
+ return `
51
+ findall(
52
+ [T, A],
53
+ link(Base, _, _, T, A),
54
+ AllLinks
55
+ ),
56
+ sort(AllLinks, SortedLinks),
57
+ SortedLinks = [[Timestamp, Author]|_]
58
+ `;
59
+ }
60
+ function buildPropertiesQuery(properties) {
61
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
62
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
63
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
64
+ // If no properties are provided, all are included
65
+ return `
66
+ findall([PropertyName, PropertyValue, Resolve], (
67
+ % Constrain to specified properties if provided
68
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
69
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
70
+ ), Properties)
71
+ `;
72
+ }
73
+ function buildWhereQuery(where = {}) {
74
+ // Constrains the query to instances that match the provided where conditions
75
+ // 'id' maps to the Prolog 'Base' variable (the base expression of the instance).
76
+ function formatValue(value) {
77
+ // Wrap strings in quotes
78
+ return typeof value === "string" ? `"${value}"` : value;
79
+ }
80
+ return Object.entries(where)
81
+ .map(([key, value]) => {
82
+ const isSpecial = ["id", "author", "timestamp"].includes(key);
83
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
84
+ // For 'id' the Prolog variable is always 'Base'
85
+ const field = key === "id" ? "Base" : capitalize(key);
86
+ // Handle direct array values (for IN conditions)
87
+ if (Array.isArray(value)) {
88
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
89
+ if (isSpecial)
90
+ return `member(${field}, [${formattedValues}])`;
91
+ else
92
+ return `${getter}, member(Value${key}, [${formattedValues}])`;
93
+ }
94
+ // Handle operation object
95
+ if (typeof value === "object" && value !== null) {
96
+ const { not, between, lt, lte, gt, gte } = value;
97
+ // Handle NOT operation
98
+ if (not !== undefined) {
99
+ if (Array.isArray(not)) {
100
+ // NOT IN array
101
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
102
+ if (isSpecial)
103
+ return `\\+ member(${field}, [${formattedValues}])`;
104
+ else
105
+ return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
106
+ }
107
+ else {
108
+ // NOT EQUAL
109
+ if (isSpecial)
110
+ return `${field} \\= ${formatValue(not)}`;
111
+ else
112
+ return `${getter}, Value${key} \\= ${formatValue(not)}`;
113
+ }
114
+ }
115
+ // Handle BETWEEN
116
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
117
+ if (isSpecial)
118
+ return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
119
+ else
120
+ return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
121
+ }
122
+ // Handle lt, lte, gt, & gte operations
123
+ const operators = [
124
+ { value: lt, symbol: "<" },
125
+ { value: lte, symbol: "=<" },
126
+ { value: gt, symbol: ">" },
127
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
128
+ ];
129
+ for (const { value, symbol } of operators) {
130
+ if (value !== undefined)
131
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
132
+ }
133
+ }
134
+ // Default to direct equality
135
+ if (isSpecial)
136
+ return `${field} = ${formatValue(value)}`;
137
+ else
138
+ return `${getter}, Value${key} = ${formatValue(value)}`;
139
+ })
140
+ .join(", ");
141
+ }
142
+ function buildCountQuery(count) {
143
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
144
+ }
145
+ function buildOrderQuery(order) {
146
+ if (!order)
147
+ return "SortedInstances = UnsortedInstances";
148
+ const entries = Object.entries(order);
149
+ if (entries.length === 1) {
150
+ const [propertyName, direction] = entries[0];
151
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
152
+ }
153
+ // Multi-field sort: sort from least-significant to most-significant key
154
+ // so that the final (primary) sort preserves secondary-key ordering for equal values.
155
+ // The merge_sort implementation is stable (equal elements keep original order).
156
+ const clauses = [];
157
+ for (let i = entries.length - 1; i >= 0; i--) {
158
+ const [propertyName, direction] = entries[i];
159
+ const inputVar = i === entries.length - 1 ? "UnsortedInstances" : `MultiSortIntermediate${i + 1}`;
160
+ const outputVar = i === 0 ? "SortedInstances" : `MultiSortIntermediate${i}`;
161
+ clauses.push(`sort_instances(${inputVar}, "${propertyName}", "${direction}", ${outputVar})`);
162
+ }
163
+ return clauses.join(",\n ");
164
+ }
165
+ function buildOffsetQuery(offset) {
166
+ if (!offset || offset < 0)
167
+ return "InstancesWithOffset = SortedInstances";
168
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
169
+ }
170
+ function buildLimitQuery(limit) {
171
+ if (!limit || limit < 0)
172
+ return "AllInstances = InstancesWithOffset";
173
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
174
+ }
175
+ function normalizeNamespaceString(namespace) {
176
+ if (!namespace)
177
+ return '';
178
+ if (namespace.includes('://')) {
179
+ const [scheme, rest] = namespace.split('://');
180
+ const path = (rest || '').replace(/\/+$/, '');
181
+ return `${scheme}://${path}`;
182
+ }
183
+ else {
184
+ return namespace.replace(/\/+$/, '');
185
+ }
186
+ }
187
+ function normalizeSchemaType(type) {
188
+ if (!type)
189
+ return undefined;
190
+ if (typeof type === "string")
191
+ return type;
192
+ if (Array.isArray(type) && type.length > 0) {
193
+ const nonNull = type.find((t) => t !== "null");
194
+ return nonNull || type[0];
195
+ }
196
+ return undefined;
197
+ }
198
+ function isSchemaType(schema, expectedType) {
199
+ return normalizeSchemaType(schema.type) === expectedType;
200
+ }
201
+ function isArrayType(schema) {
202
+ return isSchemaType(schema, "array");
203
+ }
204
+ function isObjectType(schema) {
205
+ return isSchemaType(schema, "object");
206
+ }
207
+ function isNumericType(schema) {
208
+ const normalized = normalizeSchemaType(schema.type);
209
+ return normalized === "number" || normalized === "integer";
210
+ }
211
+ /**
212
+ * Base class for defining data models in AD4M.
213
+ *
214
+ * @description
215
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
216
+ * Each model instance is represented as a subgraph in the perspective, with properties and relations
217
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
218
+ * instances based on their properties and relationships.
219
+ *
220
+ * Key concepts:
221
+ * - Each model instance has a unique base expression that serves as its identifier
222
+ * - Properties are stored as links with predicates defined by the `through` option
223
+ * - Relations represent one-to-many relationships as sets of links
224
+ * - Queries are translated to Prolog for efficient graph pattern matching
225
+ * - Changes are tracked through the perspective's subscription system
226
+ *
227
+ * @example
228
+ * ```typescript
229
+ * // Define a recipe model
230
+ * @Model({ name: "Recipe" })
231
+ * class Recipe extends Ad4mModel {
232
+ * // Required property with literal value
233
+ * @Property({
234
+ * through: "recipe://name",
235
+ * resolveLanguage: "literal"
236
+ * })
237
+ * name: string = "";
238
+ *
239
+ * // Optional property with custom initial value
240
+ * @Optional({
241
+ * through: "recipe://status",
242
+ * initial: "recipe://draft"
243
+ * })
244
+ * status: string = "";
245
+ *
246
+ * // Read-only computed property
247
+ * @ReadOnly({
248
+ * through: "recipe://rating",
249
+ * getter: `
250
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
251
+ * sum_list(Ratings, Sum),
252
+ * length(Ratings, Count),
253
+ * Value is Sum / Count
254
+ * `
255
+ * })
256
+ * averageRating: number = 0;
257
+ *
258
+ * // Relation of ingredients
259
+ * @HasMany({ through: "recipe://ingredient" })
260
+ * ingredients: string[] = [];
34
261
  *
35
- * See [README.md](./README.md) for a full worked example and decorator reference.
262
+ * // Relation of comments linked to another model
263
+ * @HasMany(() => Comment, { through: "recipe://comment" })
264
+ * comments: Comment[] = [];
265
+ * }
266
+ *
267
+ * // Create and save a new recipe
268
+ * const recipe = new Recipe(perspective);
269
+ * recipe.name = "Chocolate Cake";
270
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
271
+ * await recipe.save();
272
+ *
273
+ * // Query recipes in different ways
274
+ * // Get all recipes
275
+ * const allRecipes = await Recipe.findAll(perspective);
276
+ *
277
+ * // Find recipes with specific criteria
278
+ * const desserts = await Recipe.findAll(perspective, {
279
+ * where: {
280
+ * status: "recipe://published",
281
+ * averageRating: { gt: 4 }
282
+ * },
283
+ * order: { name: "ASC" },
284
+ * limit: 10
285
+ * });
286
+ *
287
+ * // Use the fluent query builder
288
+ * const popularRecipes = await Recipe.query(perspective)
289
+ * .where({ averageRating: { gt: 4.5 } })
290
+ * .order({ averageRating: "DESC" })
291
+ * .limit(5)
292
+ * .get();
293
+ *
294
+ * // Subscribe to real-time updates
295
+ * await Recipe.query(perspective)
296
+ * .where({ status: "recipe://cooking" })
297
+ * .subscribe(recipes => {
298
+ * console.log("Currently being cooked:", recipes);
299
+ * });
300
+ *
301
+ * // Paginate results
302
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
303
+ * .where({ status: "recipe://published" })
304
+ * .paginate(10, 1);
305
+ * ```
36
306
  */
37
307
  export class Ad4mModel {
308
+ /**
309
+ * Generates the SDNA (Subject DNA) Prolog rules for this model class.
310
+ * Injected at class-definition time by the `@Model` decorator.
311
+ * Returns a default value on un-decorated base classes.
312
+ */
313
+ static generateSDNA() {
314
+ return { sdna: '', name: '' };
315
+ }
316
+ /**
317
+ * Generates the SHACL shape graph for this model class.
318
+ * Injected at class-definition time by the `@Model` decorator.
319
+ * Returns `{ shape: null, name: '' }` on un-decorated base classes —
320
+ * the decorator's `parentSHACL?.shape?.nodeShapeUri` check handles this.
321
+ */
322
+ static generateSHACL() {
323
+ return { shape: null, name: '' };
324
+ }
38
325
  static async getClassName(perspective) {
39
326
  // Check if this is the Ad4mModel class itself or a subclass
40
327
  const isBaseClass = this === Ad4mModel;
@@ -48,343 +335,3588 @@ export class Ad4mModel {
48
335
  classCache = {};
49
336
  this.classNamesByClass.set(this, classCache);
50
337
  }
51
- // Get or create the cached name for this perspective
52
- const perspectiveID = perspective.uuid;
53
- if (!classCache[perspectiveID]) {
54
- classCache[perspectiveID] =
55
- await perspective.stringOrTemplateObjectToSubjectClassName(this);
338
+ // Get or create the cached name for this perspective
339
+ const perspectiveID = perspective.uuid;
340
+ if (!classCache[perspectiveID]) {
341
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
342
+ }
343
+ return classCache[perspectiveID];
344
+ }
345
+ /**
346
+ * Backwards compatibility alias for createdAt.
347
+ * @deprecated Use createdAt instead. This will be removed in a future version.
348
+ */
349
+ get timestamp() {
350
+ return this.createdAt;
351
+ }
352
+ /**
353
+ * Extracts metadata from decorators for query building.
354
+ *
355
+ * @description
356
+ * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)
357
+ * and returns it in a structured format that's easier to work with for query builders
358
+ * and other systems that need to introspect model structure.
359
+ *
360
+ * The metadata includes:
361
+ * - Class name from @Model
362
+ * - Property metadata (predicates, types, constraints, etc.)
363
+ * - Relation metadata (predicates, filters, etc.)
364
+ *
365
+ * For models created via `fromJSONSchema()`, this method will derive metadata from
366
+ * the WeakMap registries that were populated during the dynamic class creation.
367
+ * If these structures are empty but a JSON schema was attached to the class,
368
+ * it can fall back to deriving metadata from that schema.
369
+ *
370
+ * @returns Structured metadata object containing className, properties, and relations
371
+ * @throws Error if the class doesn't have @Model decorator
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * @Model({ name: "Recipe" })
376
+ * class Recipe extends Ad4mModel {
377
+ * @Property({ through: "recipe://name", resolveLanguage: "literal" })
378
+ * name: string = "";
379
+ *
380
+ * @HasMany({ through: "recipe://ingredient" })
381
+ * ingredients: string[] = [];
382
+ * }
383
+ *
384
+ * const metadata = Recipe.getModelMetadata();
385
+ * console.log(metadata.className); // "Recipe"
386
+ * console.log(metadata.properties.name.predicate); // "recipe://name"
387
+ * console.log(metadata.relations.ingredients.predicate); // "recipe://ingredient"
388
+ * ```
389
+ */
390
+ static getModelMetadata() {
391
+ // Access the prototype with any type to access decorator-added properties
392
+ const prototype = this.prototype;
393
+ // Validate that the class has @Model decorator
394
+ // The decorator sets prototype.className, so we check for its existence
395
+ if (!prototype.className || prototype.className === 'Ad4mModel') {
396
+ throw new Error("Model class must be decorated with @Model");
397
+ }
398
+ // Extract className
399
+ const className = prototype.className;
400
+ // Extract properties from WeakMap registry
401
+ const propertiesMetadata = {};
402
+ const prototypeProperties = getPropertiesMetadata(this);
403
+ for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
404
+ const options = opts;
405
+ propertiesMetadata[propertyName] = {
406
+ name: propertyName,
407
+ predicate: options.through || "",
408
+ required: options.required || false,
409
+ readOnly: !(options.writable ?? false),
410
+ ...(options.initial !== undefined && { initial: options.initial }),
411
+ ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
412
+ ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
413
+ ...(options.getter !== undefined && { getter: options.getter }),
414
+ ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
415
+ ...(options.local !== undefined && { local: options.local }),
416
+ ...(options.transform !== undefined && { transform: options.transform }),
417
+ ...(options.flag !== undefined && { flag: options.flag })
418
+ };
419
+ }
420
+ // Extract relations (relations) from WeakMap registry
421
+ const relationsMetadata = {};
422
+ const allRelationsMeta = getRelationsMetadata(this);
423
+ const prototypeRelations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
424
+ for (const [relationName, opts] of Object.entries(prototypeRelations)) {
425
+ const options = opts;
426
+ relationsMetadata[relationName] = {
427
+ name: relationName,
428
+ predicate: options.predicate || "",
429
+ ...(options.local !== undefined && { local: options.local }),
430
+ ...(options.getter !== undefined && { getter: options.getter }),
431
+ direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
432
+ };
433
+ }
434
+ // Fallback: If both structures are empty but a JSON schema is attached, derive from it
435
+ // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
436
+ const hasProperties = Object.keys(propertiesMetadata).length > 0;
437
+ const hasRelations = Object.keys(relationsMetadata).length > 0;
438
+ const hasMetadata = hasProperties || hasRelations;
439
+ if (!hasMetadata && prototype.__jsonSchema) {
440
+ // Derive metadata from the attached JSON schema
441
+ const schema = prototype.__jsonSchema;
442
+ const options = prototype.__jsonSchemaOptions || {};
443
+ if (schema.properties) {
444
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
445
+ const isArray = isArrayType(propertySchema);
446
+ const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
447
+ if (isArray) {
448
+ relationsMetadata[propertyName] = {
449
+ name: propertyName,
450
+ predicate: predicate,
451
+ ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
452
+ };
453
+ }
454
+ else {
455
+ const isRequired = schema.required?.includes(propertyName) || false;
456
+ propertiesMetadata[propertyName] = {
457
+ name: propertyName,
458
+ predicate: predicate,
459
+ required: isRequired,
460
+ readOnly: propertySchema["x-ad4m"]?.writable === false,
461
+ ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
462
+ ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
463
+ ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
464
+ };
465
+ }
466
+ }
467
+ }
468
+ }
469
+ return {
470
+ className,
471
+ properties: propertiesMetadata,
472
+ relations: relationsMetadata,
473
+ };
474
+ }
475
+ /**
476
+ * Constructs a new model instance.
477
+ *
478
+ * @param perspective - The perspective where this model will be stored
479
+ * @param baseExpression - Optional expression URI for this instance.
480
+ * If omitted, a random Literal URL is generated.
481
+ * @param source - Optional source expression this instance is linked to
482
+ *
483
+ * @example
484
+ * ```typescript
485
+ * // Create a new recipe with auto-generated base expression
486
+ * const recipe = new Recipe(perspective);
487
+ *
488
+ * // Create with specific base expression
489
+ * const recipe = new Recipe(perspective, "literal://...");
490
+ * ```
491
+ */
492
+ constructor(perspective, baseExpression) {
493
+ this._snapshot = null;
494
+ this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();
495
+ this._perspective = perspective;
496
+ }
497
+ /**
498
+ * The unique identifier (expression URI) of this model instance.
499
+ */
500
+ get id() {
501
+ return this._baseExpression;
502
+ }
503
+ /**
504
+ * @deprecated Use `.id` instead. Will be removed in a future version.
505
+ */
506
+ get baseExpression() {
507
+ return this._baseExpression;
508
+ }
509
+ /**
510
+ * Protected getter for the perspective.
511
+ * Allows subclasses to access the perspective while keeping it private from external code.
512
+ */
513
+ get perspective() {
514
+ return this._perspective;
515
+ }
516
+ /**
517
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
518
+ * @private
519
+ */
520
+ getPropertyMetadata(key) {
521
+ const ctor = this.constructor;
522
+ const props = getPropertiesMetadata(ctor);
523
+ return props[key];
524
+ }
525
+ /**
526
+ * Get relation options from decorator
527
+ * @private
528
+ */
529
+ getRelationOptions(key) {
530
+ const ctor = this.constructor;
531
+ const rels = getRelationsMetadata(ctor);
532
+ return rels[key];
533
+ }
534
+ /**
535
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
536
+ * Replaces Prolog query: property_setter(C, key, Setter)
537
+ * @private
538
+ */
539
+ generatePropertySetterAction(key, metadata) {
540
+ // Flags are always immutable — throw a clear error
541
+ if (metadata.flag) {
542
+ throw new Error(`Property "${key}" is a @Flag and cannot be written. ` +
543
+ `Flags are immutable type markers set at creation time.`);
544
+ }
545
+ // Check if property is read-only
546
+ if (metadata.readOnly) {
547
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
548
+ }
549
+ if (metadata.prologSetter) {
550
+ // Custom Prolog setter - throw error for now (Phase 2)
551
+ throw new Error(`Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
552
+ `Use standard @Property decorator or enable Prolog for custom setters.`);
553
+ }
554
+ if (!metadata.through) {
555
+ throw new Error(`Property "${key}" has no 'through' predicate defined`);
556
+ }
557
+ return [{
558
+ action: "setSingleTarget",
559
+ source: "this",
560
+ predicate: metadata.through,
561
+ target: "value",
562
+ ...(metadata.local && { local: true })
563
+ }];
564
+ }
565
+ /**
566
+ * Generate relation action from metadata (Phase 1: Prolog-free refactor)
567
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
568
+ * @private
569
+ */
570
+ generateRelationAction(key, actionType) {
571
+ const metadata = this.getRelationOptions(key);
572
+ if (!metadata) {
573
+ throw new Error(`Relation "${key}" has no metadata defined`);
574
+ }
575
+ if (!metadata.predicate) {
576
+ throw new Error(`Relation "${key}" has no predicate defined`);
577
+ }
578
+ const actionMap = {
579
+ adder: "addLink",
580
+ remover: "removeLink",
581
+ setter: "collectionSetter"
582
+ };
583
+ return [{
584
+ action: actionMap[actionType],
585
+ source: "this",
586
+ predicate: metadata.predicate,
587
+ target: "value",
588
+ ...(metadata.local && { local: true })
589
+ }];
590
+ }
591
+ // ──────────────────────────────────────────────────────────
592
+ // Unified hydration helpers
593
+ // ──────────────────────────────────────────────────────────
594
+ /**
595
+ * Resolves a raw link target value into a hydrated property value.
596
+ *
597
+ * Handles, in order:
598
+ * 1. Non-literal expression resolution (`perspective.getExpression`)
599
+ * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
600
+ * 3. Primitive type coercion (string → number / boolean)
601
+ * 4. Transform function application
602
+ *
603
+ * @param target - The raw target string from the link
604
+ * @param propMeta - Property metadata from the decorator registry
605
+ * @param perspective - The perspective for expression resolution
606
+ * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
607
+ * @returns The resolved value
608
+ * @private
609
+ */
610
+ static async hydratePropertyValue(target, propMeta, perspective, expectedType) {
611
+ let value = target;
612
+ if (target !== undefined && target !== null && target !== '') {
613
+ // Non-literal expression resolution
614
+ if (propMeta.resolveLanguage != null &&
615
+ propMeta.resolveLanguage !== 'literal' &&
616
+ typeof target === 'string' &&
617
+ !target.startsWith('literal://')) {
618
+ try {
619
+ const expression = await perspective.getExpression(target);
620
+ if (expression) {
621
+ try {
622
+ value = JSON.parse(expression.data);
623
+ }
624
+ catch {
625
+ value = expression.data;
626
+ }
627
+ }
628
+ }
629
+ catch (e) {
630
+ console.warn(`hydratePropertyValue: failed to resolve expression for "${propMeta.name}":`, e);
631
+ }
632
+ }
633
+ // Literal URI parsing
634
+ else if (propMeta.resolveLanguage === 'literal' &&
635
+ typeof target === 'string' &&
636
+ target.startsWith('literal://')) {
637
+ try {
638
+ const parsed = Literal.fromUrl(target).get();
639
+ value = parsed.data !== undefined ? parsed.data : parsed;
640
+ }
641
+ catch {
642
+ // Keep raw value
643
+ }
644
+ }
645
+ // Primitive type coercion
646
+ else if (typeof target === 'string' && expectedType) {
647
+ if (expectedType === 'number')
648
+ value = Number(target);
649
+ else if (expectedType === 'boolean')
650
+ value = target === 'true' || target === '1';
651
+ }
652
+ }
653
+ // Transform function
654
+ if (propMeta.transform && typeof propMeta.transform === 'function') {
655
+ value = propMeta.transform(value);
656
+ }
657
+ return value;
658
+ }
659
+ /**
660
+ * Hydrates an instance from an array of raw links.
661
+ *
662
+ * Processes properties (latest-wins semantics), relations
663
+ * (chronological accumulation), and timestamps/author in a single
664
+ * pass over the links array.
665
+ *
666
+ * @param instance - The blank model instance to populate
667
+ * @param links - Array of link objects (predicate, target, author?, timestamp?)
668
+ * @param metadata - Model metadata from `getModelMetadata()`
669
+ * @param perspective - The perspective for expression resolution
670
+ * @param requestedProperties - Optional sparse fieldset; when provided, only these
671
+ * property names are hydrated (relations are unaffected).
672
+ * Omit or pass `undefined` to hydrate all properties.
673
+ * @private
674
+ */
675
+ static async hydrateFromLinks(instance, links, metadata, perspective, requestedProperties) {
676
+ if (!links || links.length === 0)
677
+ return;
678
+ let minTimestamp = null;
679
+ let maxTimestamp = null;
680
+ let originalAuthor = null;
681
+ let latestAuthor = null;
682
+ // Build predicate→propName and predicate→relName lookup maps for O(1) matching
683
+ // When requestedProperties is provided, only include those properties in the map
684
+ const propFilter = requestedProperties && requestedProperties.length > 0
685
+ ? new Set(requestedProperties)
686
+ : null;
687
+ const predToProperty = new Map();
688
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
689
+ if (propMeta.getter)
690
+ continue; // Handled via custom getter evaluation
691
+ if (propFilter && !propFilter.has(propName))
692
+ continue; // Skip unrequested properties
693
+ predToProperty.set(propMeta.predicate, [propName, propMeta]);
694
+ }
695
+ const predToRelation = new Map();
696
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
697
+ if (relMeta.getter)
698
+ continue;
699
+ predToRelation.set(relMeta.predicate, [relName, relMeta]);
700
+ }
701
+ // Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
702
+ const propertyLatest = new Map();
703
+ // Per-relation accumulator: ordered targets with metadata for sorting
704
+ const relationAccum = new Map();
705
+ // Single pass over all links
706
+ for (let i = 0; i < links.length; i++) {
707
+ const link = links[i];
708
+ const { predicate, target, author, timestamp } = link;
709
+ if (target === 'None' || target === undefined || target === null)
710
+ continue;
711
+ // Track timestamps/authors
712
+ if (timestamp != null) {
713
+ if (minTimestamp == null || timestamp < minTimestamp) {
714
+ minTimestamp = timestamp;
715
+ originalAuthor = author ?? null;
716
+ }
717
+ if (maxTimestamp == null || timestamp > maxTimestamp) {
718
+ maxTimestamp = timestamp;
719
+ latestAuthor = author ?? null;
720
+ }
721
+ }
722
+ // Property match — accumulate for latest-wins
723
+ const propEntry = predToProperty.get(predicate);
724
+ if (propEntry) {
725
+ const existing = propertyLatest.get(propEntry[0]);
726
+ // Latest-wins: always overwrite (links are ordered ASC so last = latest)
727
+ propertyLatest.set(propEntry[0], { target, timestamp });
728
+ continue;
729
+ }
730
+ // Relation match — accumulate all
731
+ const relEntry = predToRelation.get(predicate);
732
+ if (relEntry) {
733
+ const [relName] = relEntry;
734
+ let arr = relationAccum.get(relName);
735
+ if (!arr) {
736
+ arr = [];
737
+ relationAccum.set(relName, arr);
738
+ }
739
+ arr.push({ target, timestamp: timestamp ?? '', index: i });
740
+ }
741
+ }
742
+ // Resolve properties
743
+ for (const [propName, { target }] of propertyLatest) {
744
+ const [, propMeta] = predToProperty.get(metadata.properties[propName].predicate);
745
+ const expectedType = typeof instance[propName];
746
+ instance[propName] = await this.hydratePropertyValue(target, propMeta, perspective, expectedType !== 'undefined' ? expectedType : undefined);
747
+ }
748
+ // Resolve relations: sort by timestamp (stable via index tiebreaker), filter empties
749
+ for (const [relName, items] of relationAccum) {
750
+ items.sort((a, b) => {
751
+ const cmp = String(a.timestamp).localeCompare(String(b.timestamp));
752
+ return cmp !== 0 ? cmp : a.index - b.index;
753
+ });
754
+ instance[relName] = items
755
+ .map(i => i.target)
756
+ .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
757
+ }
758
+ // Assign author / timestamps
759
+ if (originalAuthor)
760
+ instance.author = originalAuthor;
761
+ if (minTimestamp != null) {
762
+ instance.createdAt = typeof minTimestamp === 'string' && minTimestamp.includes('T')
763
+ ? new Date(minTimestamp).getTime()
764
+ : typeof minTimestamp === 'string'
765
+ ? (isNaN(parseInt(minTimestamp, 10)) ? minTimestamp : parseInt(minTimestamp, 10))
766
+ : minTimestamp;
767
+ }
768
+ if (maxTimestamp != null) {
769
+ instance.updatedAt = typeof maxTimestamp === 'string' && maxTimestamp.includes('T')
770
+ ? new Date(maxTimestamp).getTime()
771
+ : typeof maxTimestamp === 'string'
772
+ ? (isNaN(parseInt(maxTimestamp, 10)) ? maxTimestamp : parseInt(maxTimestamp, 10))
773
+ : maxTimestamp;
774
+ }
775
+ }
776
+ static async assignValuesToInstance(perspective, instance, values) {
777
+ // Map properties to object
778
+ const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
779
+ let finalValue = value;
780
+ // Handle UTF-8 byte sequences from Prolog URL decoding
781
+ if (!resolve && typeof value === 'string') {
782
+ // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
783
+ // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
784
+ const codePoints = Array.from(value, ch => ch.codePointAt(0));
785
+ const looksByteString = codePoints.every(cp => cp <= 0xFF);
786
+ const hasHighByte = codePoints.some(cp => cp >= 0x80);
787
+ if (looksByteString && hasHighByte) {
788
+ try {
789
+ const bytes = Uint8Array.from(codePoints);
790
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
791
+ if (decoded !== value)
792
+ finalValue = decoded;
793
+ }
794
+ catch (error) {
795
+ // If UTF-8 conversion fails, keep the original value
796
+ console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
797
+ }
798
+ }
799
+ }
800
+ // Resolve the value if necessary
801
+ if (resolve) {
802
+ let resolvedExpression = await perspective.getExpression(value);
803
+ if (resolvedExpression) {
804
+ try {
805
+ // Attempt to parse the data as JSON
806
+ finalValue = JSON.parse(resolvedExpression.data);
807
+ }
808
+ catch (error) {
809
+ // If parsing fails, keep the original data
810
+ finalValue = resolvedExpression.data;
811
+ }
812
+ }
813
+ }
814
+ // Apply transform function if it exists
815
+ const propsMeta = getPropertiesMetadata(instance.constructor);
816
+ const transform = propsMeta[name]?.transform;
817
+ if (transform && typeof transform === "function") {
818
+ finalValue = transform(finalValue);
819
+ }
820
+ return [name, finalValue];
821
+ })));
822
+ // Filter out properties that are read-only (getters without setters)
823
+ const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
824
+ const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
825
+ if (!descriptor) {
826
+ // No descriptor means it's a regular property on the instance, allow it
827
+ return true;
828
+ }
829
+ // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
830
+ const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
831
+ if (isAccessor) {
832
+ // Accessor descriptor: only allow if it has a setter
833
+ return descriptor.set !== undefined;
834
+ }
835
+ else {
836
+ // Data descriptor: only allow if writable is not explicitly false
837
+ return descriptor.writable !== false;
838
+ }
839
+ }));
840
+ // Assign properties to instance
841
+ Object.assign(instance, writableProps);
842
+ }
843
+ // ──────────────────────────────────────────────────────────
844
+ // Snapshot / dirty tracking
845
+ // ──────────────────────────────────────────────────────────
846
+ /**
847
+ * Captures a shallow snapshot of the instance's current property and
848
+ * relation values. Called automatically after hydration (`get()`,
849
+ * query results). The snapshot is used by `isDirty()`,
850
+ * `changedFields()`, and by `update()` to skip unchanged fields.
851
+ * @private
852
+ */
853
+ /**
854
+ * Normalize a value for snapshot storage.
855
+ * Arrays of model instances are reduced to their `.id` strings so that
856
+ * dirty-tracking compares stable identifiers instead of object references.
857
+ */
858
+ static normalizeValue(value) {
859
+ if (Array.isArray(value)) {
860
+ return value.map((v) => v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v);
861
+ }
862
+ return value;
863
+ }
864
+ /**
865
+ * @param includedRelations Controls which relation fields are recorded
866
+ * in the snapshot for dirty-tracking:
867
+ * • `undefined` (default) — snapshot ALL relations (used by `.get()`,
868
+ * `.create()`, `.save()` etc. where full hydration has occurred).
869
+ * • `IncludeMap` object (e.g. `{ views: true }`) — only snapshot the
870
+ * relations named in the map. Fields not listed are omitted from
871
+ * the snapshot so that `changedFields()` ignores them.
872
+ * • `null` / empty object — skip ALL relations (used by bare
873
+ * subscriptions that don't eagerly load relations).
874
+ */
875
+ takeSnapshot(includedRelations) {
876
+ const ctor = this.constructor;
877
+ const metadata = ctor.getModelMetadata();
878
+ const snap = {};
879
+ // Always snapshot properties
880
+ for (const propName of Object.keys(metadata.properties)) {
881
+ const val = this[propName];
882
+ snap[propName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
883
+ }
884
+ // Snapshot relations only when appropriate:
885
+ // undefined → all relations (backward compat)
886
+ // IncludeMap → only the keys present in the map
887
+ // null / {} → none
888
+ if (includedRelations === undefined) {
889
+ // Full snapshot — e.g. after getData() / create()
890
+ for (const relName of Object.keys(metadata.relations)) {
891
+ const val = this[relName];
892
+ snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
893
+ }
894
+ }
895
+ else if (includedRelations && Object.keys(includedRelations).length > 0) {
896
+ // Partial snapshot — only the explicitly included relations
897
+ for (const relName of Object.keys(includedRelations)) {
898
+ if (relName in metadata.relations) {
899
+ const val = this[relName];
900
+ snap[relName] = Ad4mModel.normalizeValue(Array.isArray(val) ? [...val] : val);
901
+ }
902
+ }
903
+ }
904
+ // else: null or empty object → skip all relations
905
+ this._snapshot = snap;
906
+ }
907
+ /**
908
+ * Returns `true` if any tracked property or relation has changed
909
+ * since the last hydration (or since `takeSnapshot()` was last called).
910
+ *
911
+ * Always returns `true` if no snapshot exists (e.g. a freshly
912
+ * constructed instance that hasn't been fetched yet).
913
+ *
914
+ * @example
915
+ * ```typescript
916
+ * const recipe = await Recipe.create(perspective, { name: "Pasta" });
917
+ * recipe.isDirty(); // false — just hydrated
918
+ * recipe.name = "Risotto";
919
+ * recipe.isDirty(); // true
920
+ * ```
921
+ */
922
+ isDirty() {
923
+ if (!this._snapshot)
924
+ return true;
925
+ return this.changedFields().length > 0;
926
+ }
927
+ /**
928
+ * Returns the names of properties/relations that differ from the
929
+ * snapshot taken at the last hydration.
930
+ *
931
+ * Returns **all** field names if no snapshot exists.
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * recipe.name = "New Name";
936
+ * recipe.changedFields(); // ["name"]
937
+ * ```
938
+ */
939
+ changedFields() {
940
+ const ctor = this.constructor;
941
+ const metadata = ctor.getModelMetadata();
942
+ if (!this._snapshot) {
943
+ return [
944
+ ...Object.keys(metadata.properties),
945
+ ...Object.keys(metadata.relations),
946
+ ];
947
+ }
948
+ const changed = [];
949
+ const allFields = [
950
+ ...Object.keys(metadata.properties),
951
+ ...Object.keys(metadata.relations),
952
+ ];
953
+ for (const field of allFields) {
954
+ // Skip fields that were not recorded in the snapshot (e.g. relation
955
+ // fields omitted because the originating query had no `include`).
956
+ // Without this guard, a relation populated by hydrateFromLinks with
957
+ // raw string IDs would appear "dirty" against a missing snapshot
958
+ // entry and trigger an unnecessary (and potentially destructive)
959
+ // setRelationValues call during innerUpdate.
960
+ if (!(field in this._snapshot))
961
+ continue;
962
+ const current = Ad4mModel.normalizeValue(this[field]);
963
+ const original = this._snapshot[field];
964
+ if (Array.isArray(current) || Array.isArray(original)) {
965
+ // Order-insensitive comparison (sorted) so reordering alone
966
+ // doesn't mark a relation as dirty.
967
+ const a = Array.isArray(current) ? [...current].sort() : [];
968
+ const b = Array.isArray(original) ? [...original].sort() : [];
969
+ if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
970
+ changed.push(field);
971
+ }
972
+ }
973
+ else if (current !== original) {
974
+ changed.push(field);
975
+ }
976
+ }
977
+ return changed;
978
+ }
979
+ async getData(opts) {
980
+ // Builds an object with the author, timestamp, all properties, & all relations on the Ad4mModel and saves it to the instance
981
+ // Use SurrealDB for data queries
982
+ try {
983
+ const ctor = this.constructor;
984
+ const metadata = ctor.getModelMetadata();
985
+ // Query for all links from this specific node (base expression)
986
+ const safeBaseExpression = ctor.formatSurrealValue(this._baseExpression);
987
+ const linksQuery = `
988
+ SELECT id, predicate, out.uri AS target, author, timestamp
989
+ FROM link
990
+ WHERE in.uri = ${safeBaseExpression}
991
+ ORDER BY timestamp ASC
992
+ `;
993
+ const links = await this._perspective.querySurrealDB(linksQuery);
994
+ if (links && links.length > 0) {
995
+ // Core hydration: properties (latest-wins), relations, timestamps/author
996
+ const requestedProperties = opts?.properties && opts.properties.length > 0 ? opts.properties : undefined;
997
+ await ctor.hydrateFromLinks(this, links, metadata, this._perspective, requestedProperties);
998
+ }
999
+ // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1000
+ const allRelsMeta = getRelationsMetadata(ctor);
1001
+ const requestedProps = opts?.properties && opts.properties.length > 0 ? new Set(opts.properties) : null;
1002
+ for (const [relName, relMeta] of Object.entries(allRelsMeta)) {
1003
+ if (relMeta.kind !== 'belongsToOne' && relMeta.kind !== 'belongsToMany')
1004
+ continue;
1005
+ if (requestedProps && !requestedProps.has(relName))
1006
+ continue;
1007
+ const reverseLinks = await this._perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: this._baseExpression }));
1008
+ const sourceIds = reverseLinks
1009
+ .filter((l) => l.data.target === this._baseExpression)
1010
+ .map((l) => l.data.source);
1011
+ if (relMeta.kind === 'belongsToOne') {
1012
+ this[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
1013
+ }
1014
+ else {
1015
+ this[relName] = sourceIds;
1016
+ }
1017
+ }
1018
+ // Evaluate SurrealQL getters
1019
+ await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata);
1020
+ // Eager-load relations if requested
1021
+ if (opts?.include) {
1022
+ await ctor.hydrateRelations([this], this._perspective, opts.include);
1023
+ }
1024
+ }
1025
+ catch (e) {
1026
+ console.error(`SurrealDB getData also failed for ${this._baseExpression}:`, e);
1027
+ }
1028
+ this.takeSnapshot();
1029
+ return this;
1030
+ }
1031
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
1032
+ static async queryToProlog(perspective, query, modelClassName) {
1033
+ const { properties, where, order, offset, limit, count } = query;
1034
+ const className = modelClassName || (await this.getClassName(perspective));
1035
+ // Resolve parent predicate from model metadata if needed
1036
+ const resolvedParentPredicate = query.parent
1037
+ ? resolveParentPredicate(query.parent, this)
1038
+ : undefined;
1039
+ const instanceQueries = [
1040
+ buildAuthorAndTimestampQuery(),
1041
+ buildParentQuery(query.parent, resolvedParentPredicate),
1042
+ buildPropertiesQuery(properties),
1043
+ buildWhereQuery(where),
1044
+ ];
1045
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
1046
+ const fullQuery = `
1047
+ findall([Base, Properties, Collections, Timestamp, Author], (
1048
+ subject_class("${className}", SubjectClass),
1049
+ instance(SubjectClass, Base),
1050
+ ${instanceQueries.filter((q) => q).join(", ")}
1051
+ ), UnsortedInstances),
1052
+ ${resultSetQueries.filter((q) => q).join(", ")}
1053
+ `;
1054
+ return fullQuery;
1055
+ }
1056
+ /**
1057
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
1058
+ * @private
1059
+ */
1060
+ static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
1061
+ const safeBaseExpression = this.formatSurrealValue(instance.id);
1062
+ // Evaluate property getters
1063
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1064
+ if (propMeta.getter) {
1065
+ try {
1066
+ // Replace 'Base' placeholder with actual base expression
1067
+ const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
1068
+ // Query from node table to have graph traversal context
1069
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1070
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
1071
+ instance[propName] = result[0].value;
1072
+ }
1073
+ }
1074
+ catch (error) {
1075
+ console.warn(`Failed to evaluate getter for ${propName}:`, error);
1076
+ }
1077
+ }
1078
+ }
1079
+ // Evaluate relation getters
1080
+ for (const [relName, relMeta] of Object.entries(metadata.relations)) {
1081
+ if (relMeta.getter) {
1082
+ try {
1083
+ // Replace 'Base' placeholder with actual base expression
1084
+ const query = relMeta.getter.replace(/Base/g, safeBaseExpression);
1085
+ // Query from node table to have graph traversal context
1086
+ const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
1087
+ if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
1088
+ // Filter out 'None' from relation results
1089
+ const value = result[0].value;
1090
+ instance[relName] = Array.isArray(value)
1091
+ ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
1092
+ : value;
1093
+ }
1094
+ }
1095
+ catch (error) {
1096
+ console.warn(`Failed to evaluate getter for ${relName}:`, error);
1097
+ }
1098
+ }
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Hydrates relation fields on instances according to the provided IncludeMap.
1103
+ *
1104
+ * For each relation listed in `includeMap`, the raw expression-URI strings
1105
+ * stored on the instance are replaced with fully-hydrated model instances
1106
+ * (fetched via the relation's `target()` class). Nested IncludeMaps are
1107
+ * supported for multi-level eager loading.
1108
+ *
1109
+ * @param instances - The instances whose relations should be hydrated
1110
+ * @param perspective - The perspective to fetch related instances from
1111
+ * @param includeMap - Describes which relations to hydrate
1112
+ * @private
1113
+ */
1114
+ static async hydrateRelations(instances, perspective, includeMap) {
1115
+ if (!includeMap || Object.keys(includeMap).length === 0)
1116
+ return;
1117
+ const relMeta = getRelationsMetadata(this);
1118
+ for (const [relName, includeValue] of Object.entries(includeMap)) {
1119
+ const meta = relMeta[relName];
1120
+ if (!meta) {
1121
+ console.warn(`include: relation "${relName}" not found in metadata, skipping`);
1122
+ continue;
1123
+ }
1124
+ const TargetClass = meta.target();
1125
+ // Determine if a RelationSubQuery was supplied (object) vs a plain `true`
1126
+ const subQuery = typeof includeValue === 'object' && includeValue !== null
1127
+ ? includeValue
1128
+ : undefined;
1129
+ const nestedInclude = subQuery?.include;
1130
+ // ── Reverse relations (belongsToOne / belongsToMany) ──────────────────
1131
+ // The link goes target→instance, so we query backwards:
1132
+ // predicate = meta.predicate, target = inst.id → source is the related id
1133
+ if (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') {
1134
+ // Per-instance reverse lookup (can't batch easily across instances)
1135
+ for (const inst of instances) {
1136
+ const reverseLinks = await perspective.get(new LinkQuery({ predicate: meta.predicate, target: inst.id }));
1137
+ // Defensive filter: perspective.get may return extra results; ensure
1138
+ // we only use links that genuinely point to this instance.
1139
+ const sourceIds = reverseLinks
1140
+ .filter(l => l.data.target === inst.id)
1141
+ .map(l => l.data.source);
1142
+ if (meta.kind === 'belongsToOne') {
1143
+ if (sourceIds.length === 0) {
1144
+ inst[relName] = null;
1145
+ continue;
1146
+ }
1147
+ const sourceId = sourceIds[sourceIds.length - 1]; // latest-wins
1148
+ try {
1149
+ const related = new TargetClass(perspective, sourceId);
1150
+ await related.get();
1151
+ inst[relName] = related;
1152
+ }
1153
+ catch {
1154
+ inst[relName] = null;
1155
+ }
1156
+ }
1157
+ else {
1158
+ // belongsToMany — return array of hydrated instances
1159
+ let hydrated = [];
1160
+ // If there's a where/order sub-query, delegate to findAll for filtering
1161
+ if (subQuery && (subQuery.where || subQuery.order || subQuery.properties)) {
1162
+ const whereWithIds = {
1163
+ id: sourceIds,
1164
+ ...(subQuery.where ?? {}),
1165
+ };
1166
+ hydrated = await TargetClass.findAll(perspective, {
1167
+ where: whereWithIds,
1168
+ ...(subQuery.order && { order: subQuery.order }),
1169
+ ...(subQuery.properties && { properties: subQuery.properties }),
1170
+ });
1171
+ }
1172
+ else {
1173
+ await Promise.all(sourceIds.map(async (sid) => {
1174
+ try {
1175
+ const related = new TargetClass(perspective, sid);
1176
+ await related.get(subQuery?.properties ? { properties: subQuery.properties } : undefined);
1177
+ hydrated.push(related);
1178
+ }
1179
+ catch { /* skip */ }
1180
+ }));
1181
+ }
1182
+ // Apply order (client-side, if not already handled by findAll above)
1183
+ if (subQuery?.order && !(subQuery.where || subQuery.properties)) {
1184
+ const orderEntries = Object.entries(subQuery.order);
1185
+ hydrated = hydrated.sort((a, b) => {
1186
+ for (const [field, dir] of orderEntries) {
1187
+ const av = String(a[field] ?? '');
1188
+ const bv = String(b[field] ?? '');
1189
+ const diff = av.localeCompare(bv);
1190
+ if (diff !== 0)
1191
+ return dir === 'DESC' ? -diff : diff;
1192
+ }
1193
+ return 0;
1194
+ });
1195
+ }
1196
+ // Apply offset and limit
1197
+ if (subQuery?.offset != null || subQuery?.limit != null) {
1198
+ const start = subQuery.offset ?? 0;
1199
+ const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1200
+ hydrated = hydrated.slice(start, end);
1201
+ }
1202
+ inst[relName] = hydrated;
1203
+ // Recurse for nested includes
1204
+ if (nestedInclude && hydrated.length > 0) {
1205
+ await TargetClass.hydrateRelations(hydrated, perspective, nestedInclude);
1206
+ }
1207
+ }
1208
+ }
1209
+ continue; // skip the forward-relation path below
1210
+ }
1211
+ // ── Forward relations (hasMany / hasOne) ──────────────────────────────
1212
+ // Collect all unique URIs across all instances for batch-friendly lookup.
1213
+ // IMPORTANT: We cache each instance's raw value NOW (before the async
1214
+ // findAll) so that concurrent getData() calls on the same instance can't
1215
+ // overwrite the relation field between the uriSet relation and the
1216
+ // post-await assignment loop. Without this cache, a concurrent call
1217
+ // can replace the raw URI strings with hydrated model objects, causing
1218
+ // the `typeof v === 'string'` check to fail and the array to end up empty.
1219
+ const uriSet = new Set();
1220
+ const rawCache = new Map();
1221
+ for (const inst of instances) {
1222
+ const raw = inst[relName];
1223
+ rawCache.set(inst, Array.isArray(raw) ? [...raw] : raw);
1224
+ if (raw == null)
1225
+ continue;
1226
+ if (Array.isArray(raw)) {
1227
+ for (const v of raw) {
1228
+ if (typeof v === 'string')
1229
+ uriSet.add(v);
1230
+ // Handle already-hydrated instances (from a concurrent call)
1231
+ else if (v && typeof v === 'object' && typeof v.id === 'string')
1232
+ uriSet.add(v.id);
1233
+ }
1234
+ }
1235
+ else if (typeof raw === 'string') {
1236
+ uriSet.add(raw);
1237
+ }
1238
+ else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1239
+ uriSet.add(raw.id);
1240
+ }
1241
+ }
1242
+ if (uriSet.size === 0)
1243
+ continue;
1244
+ // Hydrate related instances using findAll to ensure conformance checking.
1245
+ // findAll validates model membership via graph traversal (required predicates / flags),
1246
+ // so non-conforming linked URIs are silently dropped — matching the documented behaviour.
1247
+ const hydrated = new Map();
1248
+ const whereWithIds = {
1249
+ id: Array.from(uriSet),
1250
+ ...(subQuery?.where ?? {}),
1251
+ };
1252
+ const fetchQuery = {
1253
+ where: whereWithIds,
1254
+ ...(subQuery?.order && { order: subQuery.order }),
1255
+ ...(subQuery?.properties && { properties: subQuery.properties }),
1256
+ };
1257
+ const results = await TargetClass.findAll(perspective, fetchQuery);
1258
+ for (const result of results) {
1259
+ hydrated.set(result.id, result);
1260
+ }
1261
+ // Replace raw URIs with hydrated instances on each parent instance.
1262
+ // Use the cached raw values captured BEFORE the async findAll to avoid
1263
+ // the race condition where a concurrent getData() already replaced the
1264
+ // strings with hydrated objects.
1265
+ for (const inst of instances) {
1266
+ const raw = rawCache.get(inst);
1267
+ if (raw == null)
1268
+ continue;
1269
+ if (Array.isArray(raw)) {
1270
+ // Map URIs → instances; handle both raw strings and already-hydrated objects
1271
+ let resolved = raw
1272
+ .map((v) => {
1273
+ if (typeof v === 'string') {
1274
+ return hydrated.has(v) ? hydrated.get(v) : null;
1275
+ }
1276
+ // Already a hydrated model instance (from a concurrent call)
1277
+ if (v && typeof v === 'object' && typeof v.id === 'string') {
1278
+ return hydrated.has(v.id) ? hydrated.get(v.id) : v;
1279
+ }
1280
+ return null;
1281
+ })
1282
+ .filter((v) => v !== null);
1283
+ // Per-instance sort (client-side, after filtering)
1284
+ if (subQuery?.order) {
1285
+ const orderEntries = Object.entries(subQuery.order);
1286
+ resolved = resolved.sort((a, b) => {
1287
+ for (const [field, dir] of orderEntries) {
1288
+ const av = String(a[field] ?? '');
1289
+ const bv = String(b[field] ?? '');
1290
+ const diff = av.localeCompare(bv);
1291
+ if (diff !== 0)
1292
+ return dir === 'DESC' ? -diff : diff;
1293
+ }
1294
+ return 0;
1295
+ });
1296
+ }
1297
+ // Per-instance limit / offset
1298
+ if (subQuery?.offset != null || subQuery?.limit != null) {
1299
+ const start = subQuery.offset ?? 0;
1300
+ const end = subQuery.limit != null ? start + subQuery.limit : undefined;
1301
+ resolved = resolved.slice(start, end);
1302
+ }
1303
+ // Enforce maxCount guard — single-valued relations keep only the last item
1304
+ if (meta.maxCount === 1) {
1305
+ if (resolved.length > 1) {
1306
+ console.warn(`include: relation "${relName}" has maxCount 1 but ${resolved.length} values found; keeping the last`);
1307
+ }
1308
+ inst[relName] = resolved.length > 0
1309
+ ? resolved[resolved.length - 1]
1310
+ : null;
1311
+ }
1312
+ else {
1313
+ inst[relName] = resolved;
1314
+ }
1315
+ }
1316
+ else if (typeof raw === 'string' && hydrated.has(raw)) {
1317
+ inst[relName] = hydrated.get(raw);
1318
+ }
1319
+ else if (raw && typeof raw === 'object' && typeof raw.id === 'string') {
1320
+ // Already-hydrated object — look up refreshed version or keep as-is
1321
+ inst[relName] = hydrated.has(raw.id) ? hydrated.get(raw.id) : raw;
1322
+ }
1323
+ }
1324
+ // Recurse for nested includes
1325
+ if (nestedInclude) {
1326
+ const hydratedInstances = Array.from(hydrated.values());
1327
+ await TargetClass.hydrateRelations(hydratedInstances, perspective, nestedInclude);
1328
+ }
1329
+ }
1330
+ }
1331
+ /**
1332
+ * Generates a SurrealQL query from a Query object.
1333
+ *
1334
+ * @description
1335
+ * This method translates high-level query parameters into a SurrealQL query string
1336
+ * that can be executed against the SurrealDB backend. Unlike Prolog queries which
1337
+ * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
1338
+ * stored in SurrealDB.
1339
+ *
1340
+ * The generated query uses a CTE (Common Table Expression) pattern:
1341
+ * 1. First, identify candidate base expressions by filtering links based on where conditions
1342
+ * 2. Then, for each candidate base, resolve properties and relations via subqueries
1343
+ * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
1344
+ *
1345
+ * Key architectural notes:
1346
+ * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
1347
+ * - No SDNA knowledge at the database level
1348
+ * - Properties are resolved via subqueries that look for links with specific predicates
1349
+ * - Relations are similar but return multiple values instead of one
1350
+ * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
1351
+ *
1352
+ * @param perspective - The perspective to query (used for metadata extraction)
1353
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
1354
+ * @returns Complete SurrealQL query string ready for execution
1355
+ *
1356
+ * @example
1357
+ * ```typescript
1358
+ * const query = Recipe.queryToSurrealQL(perspective, {
1359
+ * where: { name: "Pasta", rating: { gt: 4 } },
1360
+ * order: { timestamp: "DESC" },
1361
+ * limit: 10
1362
+ * });
1363
+ * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
1364
+ * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
1365
+ * ```
1366
+ */
1367
+ static async queryToSurrealQL(perspective, query) {
1368
+ const metadata = this.getModelMetadata();
1369
+ const { where, order, offset, limit } = query;
1370
+ // Build list of graph traversal filters for required predicates
1371
+ const graphTraversalFilters = [];
1372
+ // Add parent filter if specified (filter to nodes linked from a parent via a specific predicate)
1373
+ if (query.parent) {
1374
+ const parentPredicate = resolveParentPredicate(query.parent, this);
1375
+ graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${this.formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
1376
+ }
1377
+ // Add filters for required properties
1378
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1379
+ if (propMeta.required) {
1380
+ // Skip properties with a getter — they are computed dynamically
1381
+ // and may not have a stored link with their predicate, so requiring their
1382
+ // presence would wrongly exclude valid model instances.
1383
+ if (propMeta.getter)
1384
+ continue;
1385
+ // For flag properties, also filter by the target value
1386
+ if (propMeta.flag && propMeta.initial) {
1387
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1388
+ }
1389
+ else {
1390
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1391
+ }
1392
+ }
1393
+ }
1394
+ // If no required properties produced filters, try properties with initial
1395
+ // values (e.g. @Flag or @Property with an explicit initial).
1396
+ if (graphTraversalFilters.length === 0) {
1397
+ for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1398
+ if (propMeta.initial) {
1399
+ if (propMeta.flag) {
1400
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
1401
+ }
1402
+ else {
1403
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
1404
+ }
1405
+ break;
1406
+ }
1407
+ }
1408
+ }
1409
+ // Still no filters → open-world structural matching.
1410
+ // Require the node to have at least one link whose predicate is declared
1411
+ // by this model (property OR relation). This prevents the query from
1412
+ // matching every node in the perspective.
1413
+ if (graphTraversalFilters.length === 0) {
1414
+ const structuralPredicates = [];
1415
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
1416
+ if (propMeta.predicate) {
1417
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
1418
+ }
1419
+ }
1420
+ if (metadata.relations) {
1421
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
1422
+ if (relMeta.predicate) {
1423
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
1424
+ }
1425
+ }
1426
+ }
1427
+ if (structuralPredicates.length > 0) {
1428
+ graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
1429
+ }
1430
+ }
1431
+ // Build user WHERE clause filters using graph traversal
1432
+ const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
1433
+ // Build complete WHERE clause using graph traversal filters
1434
+ const whereConditions = [];
1435
+ // Add all graph traversal filters for required properties
1436
+ whereConditions.push(...graphTraversalFilters);
1437
+ // Add user where conditions if any
1438
+ if (userWhereClause) {
1439
+ whereConditions.push(userWhereClause);
1440
+ }
1441
+ // Always ensure node has at least one link (each perspective has its own isolated DB)
1442
+ whereConditions.push(`count(->link) > 0`);
1443
+ // Build the query FROM node using direct graph traversal in WHERE
1444
+ // This avoids slow subqueries and uses graph indexes for fast traversal
1445
+ // FETCH links expands the link record IDs into full record objects
1446
+ // (without FETCH, ->link returns only IDs like "link:abc123")
1447
+ const fullQuery = `
1448
+ SELECT
1449
+ id AS source,
1450
+ uri AS source_uri,
1451
+ ->link AS links
1452
+ FROM node
1453
+ WHERE ${whereConditions.join(' AND ')}
1454
+ FETCH links
1455
+ `.trim();
1456
+ return fullQuery;
1457
+ }
1458
+ /**
1459
+ * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
1460
+ *
1461
+ * @description
1462
+ * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
1463
+ * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
1464
+ *
1465
+ * Handles several condition types:
1466
+ * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
1467
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
1468
+ * - NOT operators: Use `NOT` prefix
1469
+ * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
1470
+ * - Special fields: base uses `uri` directly, author/timestamp handled post-query
1471
+ *
1472
+ * @param metadata - Model metadata containing property predicates
1473
+ * @param where - Where conditions from the query
1474
+ * @returns Graph traversal WHERE clause filters, or empty string if no conditions
1475
+ *
1476
+ * @private
1477
+ */
1478
+ static buildGraphTraversalWhereClause(metadata, where) {
1479
+ if (!where)
1480
+ return '';
1481
+ const conditions = [];
1482
+ for (const [propertyName, condition] of Object.entries(where)) {
1483
+ // Check if this is a special field (id, author, timestamp)
1484
+ // Note: author and timestamp filtering is done in JavaScript after query
1485
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1486
+ if (isSpecial) {
1487
+ // Skip author and timestamp - they'll be filtered in JavaScript
1488
+ // Only handle 'id' (which maps to 'uri') here
1489
+ if (propertyName === 'author' || propertyName === 'timestamp') {
1490
+ continue; // Skip - will be filtered post-query
1491
+ }
1492
+ const columnName = 'uri'; // id maps to uri in node table
1493
+ // Handle base/uri field directly
1494
+ if (Array.isArray(condition)) {
1495
+ // Array values (IN clause)
1496
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1497
+ conditions.push(`${columnName} IN [${formattedValues}]`);
1498
+ }
1499
+ else if (typeof condition === 'object' && condition !== null) {
1500
+ // Operator object
1501
+ const ops = condition;
1502
+ if (ops.not !== undefined) {
1503
+ if (Array.isArray(ops.not)) {
1504
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1505
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1506
+ }
1507
+ else {
1508
+ conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1509
+ }
1510
+ }
1511
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1512
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1513
+ }
1514
+ if (ops.gt !== undefined) {
1515
+ conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1516
+ }
1517
+ if (ops.gte !== undefined) {
1518
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1519
+ }
1520
+ if (ops.lt !== undefined) {
1521
+ conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1522
+ }
1523
+ if (ops.lte !== undefined) {
1524
+ conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1525
+ }
1526
+ if (ops.contains !== undefined) {
1527
+ conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1528
+ }
1529
+ }
1530
+ else {
1531
+ // Simple equality
1532
+ conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1533
+ }
1534
+ }
1535
+ else {
1536
+ // Handle regular properties via graph traversal.
1537
+ // IMPORTANT: Check relation metadata first — @BelongsToOne / @BelongsToMany
1538
+ // also write into propertyRegistry, but the link direction is inverted.
1539
+ // If we matched the property path they would get a forward ->link filter
1540
+ // which is wrong for belongs-to relations.
1541
+ const allRelations = getRelationsMetadata(this);
1542
+ const relMeta = allRelations[propertyName];
1543
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
1544
+ if (relMeta) {
1545
+ const predicate = escapeSurrealString(relMeta.predicate);
1546
+ if (Array.isArray(condition)) {
1547
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1548
+ if (isBelongs) {
1549
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
1550
+ }
1551
+ else {
1552
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
1553
+ }
1554
+ }
1555
+ else if (typeof condition === 'object' && condition !== null) {
1556
+ const ops = condition;
1557
+ if (ops.not !== undefined) {
1558
+ if (Array.isArray(ops.not)) {
1559
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1560
+ if (isBelongs) {
1561
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
1562
+ }
1563
+ else {
1564
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
1565
+ }
1566
+ }
1567
+ else {
1568
+ if (isBelongs) {
1569
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1570
+ }
1571
+ else {
1572
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(ops.not)}]) = 0`);
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+ else {
1578
+ // Simple equality
1579
+ if (isBelongs) {
1580
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1581
+ }
1582
+ else {
1583
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${this.formatSurrealValue(condition)}]) > 0`);
1584
+ }
1585
+ }
1586
+ continue;
1587
+ }
1588
+ const propMeta = metadata.properties[propertyName];
1589
+ if (!propMeta)
1590
+ continue; // Skip if property not found in metadata
1591
+ const predicate = escapeSurrealString(propMeta.predicate);
1592
+ // Use fn::parse_literal() for properties with resolveLanguage
1593
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
1594
+ if (Array.isArray(condition)) {
1595
+ // Array values (IN clause)
1596
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1597
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1598
+ }
1599
+ else if (typeof condition === 'object' && condition !== null) {
1600
+ // Operator object
1601
+ const ops = condition;
1602
+ if (ops.not !== undefined) {
1603
+ if (Array.isArray(ops.not)) {
1604
+ // For NOT IN with array: must NOT have a link with value in the array
1605
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1606
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1607
+ }
1608
+ else {
1609
+ // For NOT with single value: must NOT have this value
1610
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1611
+ }
1612
+ }
1613
+ // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1614
+ // post-query because fn::parse_literal() comparisons in SurrealDB
1615
+ // don't work reliably with numeric comparisons.
1616
+ // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1617
+ // However, we still need to ensure the property exists
1618
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1619
+ ops.lt !== undefined || ops.lte !== undefined ||
1620
+ ops.between !== undefined || ops.contains !== undefined;
1621
+ if (hasComparisonOps) {
1622
+ // Ensure we only get nodes that have this property
1623
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
1624
+ }
1625
+ }
1626
+ else {
1627
+ // Simple equality
1628
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1629
+ }
1630
+ }
1631
+ }
1632
+ return conditions.join(' AND ');
1633
+ }
1634
+ /**
1635
+ * Builds the WHERE clause for SurrealQL queries.
1636
+ *
1637
+ * @description
1638
+ * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
1639
+ * For each property filter, generates a subquery that checks for links with the appropriate
1640
+ * predicate and target value.
1641
+ *
1642
+ * Handles several condition types:
1643
+ * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
1644
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
1645
+ * - Operators: `{ rating: { gt: 4 } }` → target > '4'
1646
+ * - gt, gte, lt, lte: comparison operators
1647
+ * - not: negation (single value or array)
1648
+ * - between: range check
1649
+ * - contains: substring/element check (uses SurrealQL CONTAINS)
1650
+ * - Special fields: base, author, timestamp are accessed directly, not via subqueries
1651
+ *
1652
+ * All conditions are joined with AND.
1653
+ *
1654
+ * @param metadata - Model metadata containing property predicates
1655
+ * @param where - Where conditions from the query
1656
+ * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
1657
+ *
1658
+ * @private
1659
+ */
1660
+ static buildSurrealWhereClause(metadata, where) {
1661
+ if (!where)
1662
+ return '';
1663
+ const conditions = [];
1664
+ for (const [propertyName, condition] of Object.entries(where)) {
1665
+ // Check if this is a special field (id, author, timestamp)
1666
+ // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1667
+ // because they need to be computed from the grouped links first
1668
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
1669
+ if (isSpecial) {
1670
+ // Skip author and timestamp - they'll be filtered in JavaScript
1671
+ // Only handle 'id' (which maps to 'source') here
1672
+ if (propertyName === 'author' || propertyName === 'timestamp') {
1673
+ continue; // Skip - will be filtered post-query
1674
+ }
1675
+ const columnName = 'source'; // id maps to source
1676
+ // Handle base/source field directly
1677
+ if (Array.isArray(condition)) {
1678
+ // Array values (IN clause)
1679
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1680
+ conditions.push(`${columnName} IN [${formattedValues}]`);
1681
+ }
1682
+ else if (typeof condition === 'object' && condition !== null) {
1683
+ // Operator object
1684
+ const ops = condition;
1685
+ if (ops.not !== undefined) {
1686
+ if (Array.isArray(ops.not)) {
1687
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1688
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1689
+ }
1690
+ else {
1691
+ conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1692
+ }
1693
+ }
1694
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1695
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1696
+ }
1697
+ if (ops.gt !== undefined) {
1698
+ conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1699
+ }
1700
+ if (ops.gte !== undefined) {
1701
+ conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1702
+ }
1703
+ if (ops.lt !== undefined) {
1704
+ conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1705
+ }
1706
+ if (ops.lte !== undefined) {
1707
+ conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1708
+ }
1709
+ if (ops.contains !== undefined) {
1710
+ conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1711
+ }
1712
+ }
1713
+ else {
1714
+ // Simple equality
1715
+ conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1716
+ }
1717
+ }
1718
+ else {
1719
+ // Handle regular properties via subqueries
1720
+ const propMeta = metadata.properties[propertyName];
1721
+ if (!propMeta)
1722
+ continue; // Skip if property not found in metadata
1723
+ const predicate = escapeSurrealString(propMeta.predicate);
1724
+ // Use fn::parse_literal() for properties with resolveLanguage
1725
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1726
+ if (Array.isArray(condition)) {
1727
+ // Array values (IN clause)
1728
+ const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1729
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1730
+ }
1731
+ else if (typeof condition === 'object' && condition !== null) {
1732
+ // Operator object
1733
+ const ops = condition;
1734
+ if (ops.not !== undefined) {
1735
+ if (Array.isArray(ops.not)) {
1736
+ // For NOT IN with array: exclude sources that HAVE a value in the array
1737
+ const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1738
+ conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1739
+ }
1740
+ else {
1741
+ // For NOT with single value: exclude sources that HAVE this value
1742
+ conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
1743
+ }
1744
+ }
1745
+ // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1746
+ // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
1747
+ // don't work reliably with numeric comparisons.
1748
+ // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1749
+ // However, we still need to ensure the property exists by filtering on the predicate
1750
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1751
+ ops.lt !== undefined || ops.lte !== undefined ||
1752
+ ops.between !== undefined || ops.contains !== undefined;
1753
+ if (hasComparisonOps) {
1754
+ // Ensure we only get instances that have this property
1755
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
1756
+ }
1757
+ }
1758
+ else {
1759
+ // Simple equality
1760
+ conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
1761
+ }
1762
+ }
1763
+ }
1764
+ return conditions.join(' AND ');
1765
+ }
1766
+ /**
1767
+ * Builds the SELECT fields for SurrealQL queries.
1768
+ *
1769
+ * @description
1770
+ * Generates the field list for the SELECT clause, resolving properties and relations
1771
+ * via subqueries. Each property is fetched with a subquery that finds the link with the
1772
+ * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
1773
+ *
1774
+ * Field types:
1775
+ * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1776
+ * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
1777
+ * - Author/Timestamp: Always included to provide metadata about each instance
1778
+ *
1779
+ * If properties or relations arrays are provided, only those fields are included.
1780
+ * Otherwise, all properties/relations from metadata are included.
1781
+ *
1782
+ * @param metadata - Model metadata containing property and relation predicates
1783
+ * @param properties - Optional array of property names to include (default: all)
1784
+ * @param relations - Optional array of relation names to include (default: all)
1785
+ * @returns Comma-separated SELECT field list
1786
+ *
1787
+ * @private
1788
+ */
1789
+ static buildSurrealSelectFields(metadata, properties, relations) {
1790
+ const fields = [];
1791
+ // Determine properties to fetch
1792
+ const propsToFetch = properties || Object.keys(metadata.properties);
1793
+ for (const propName of propsToFetch) {
1794
+ const propMeta = metadata.properties[propName];
1795
+ if (!propMeta)
1796
+ continue; // Skip if not found
1797
+ // Reference source directly since we're selecting from link table
1798
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
1799
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1800
+ }
1801
+ // Determine relations to fetch
1802
+ const relsToFetch = relations || Object.keys(metadata.relations);
1803
+ for (const relName of relsToFetch) {
1804
+ const relMeta = metadata.relations[relName];
1805
+ if (!relMeta)
1806
+ continue; // Skip if not found
1807
+ // Reference source directly since we're selecting from link table
1808
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
1809
+ fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${relName}`);
1810
+ }
1811
+ // Always add author and timestamp fields
1812
+ fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1813
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1814
+ fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1815
+ return fields.join(',\n ');
1816
+ }
1817
+ /**
1818
+ * Builds the SELECT fields for SurrealQL queries using aggregation functions.
1819
+ * Compatible with GROUP BY source queries.
1820
+ *
1821
+ * @private
1822
+ */
1823
+ static buildSurrealSelectFieldsWithAggregation(metadata, properties, relations) {
1824
+ const fields = [];
1825
+ // Determine properties to fetch
1826
+ const propsToFetch = properties || Object.keys(metadata.properties);
1827
+ for (const propName of propsToFetch) {
1828
+ const propMeta = metadata.properties[propName];
1829
+ if (!propMeta)
1830
+ continue; // Skip if not found
1831
+ // Use array::first to get the first target value for this predicate
1832
+ const escapedPredicate = escapeSurrealString(propMeta.predicate);
1833
+ fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1834
+ }
1835
+ // Determine relations to fetch
1836
+ const relsToFetch = relations || Object.keys(metadata.relations);
1837
+ for (const relName of relsToFetch) {
1838
+ const relMeta = metadata.relations[relName];
1839
+ if (!relMeta)
1840
+ continue; // Skip if not found
1841
+ // Use array filtering to get all target values for this predicate
1842
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
1843
+ fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${relName}`);
1844
+ }
1845
+ // Always add author and timestamp fields
1846
+ fields.push(`array::first(author) AS author`);
1847
+ fields.push(`array::first(timestamp) AS createdAt`);
1848
+ fields.push(`array::last(timestamp) AS updatedAt`);
1849
+ return fields.join(',\n ');
1850
+ }
1851
+ /**
1852
+ * Formats a value for use in SurrealQL queries.
1853
+ *
1854
+ * @description
1855
+ * Handles different value types:
1856
+ * - Strings: Wrapped in single quotes with backslash-escaped special characters
1857
+ * - Numbers/booleans: Converted to string
1858
+ * - Arrays: Recursively formatted and wrapped in brackets
1859
+ *
1860
+ * @param value - The value to format
1861
+ * @returns Formatted value string ready for SurrealQL
1862
+ *
1863
+ * @private
1864
+ */
1865
+ static formatSurrealValue(value) {
1866
+ if (typeof value === 'string') {
1867
+ // Escape backslashes first, then single quotes and other special characters
1868
+ const escaped = value
1869
+ .replace(/\\/g, '\\\\') // Backslash -> \\
1870
+ .replace(/'/g, "\\'") // Single quote -> \'
1871
+ .replace(/"/g, '\\"') // Double quote -> \"
1872
+ .replace(/\n/g, '\\n') // Newline -> \n
1873
+ .replace(/\r/g, '\\r') // Carriage return -> \r
1874
+ .replace(/\t/g, '\\t'); // Tab -> \t
1875
+ return `'${escaped}'`;
1876
+ }
1877
+ else if (typeof value === 'number' || typeof value === 'boolean') {
1878
+ return String(value);
1879
+ }
1880
+ else if (Array.isArray(value)) {
1881
+ return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
1882
+ }
1883
+ else {
1884
+ return String(value);
1885
+ }
1886
+ }
1887
+ static async instancesFromPrologResult(perspective, query, result) {
1888
+ if (!result?.[0]?.AllInstances)
1889
+ return { results: [], totalCount: 0 };
1890
+ // Map results to instances
1891
+ const requestedProperties = query?.properties || [];
1892
+ const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1893
+ try {
1894
+ const instance = new this(perspective, Base);
1895
+ // Remove unrequested attributes from instance
1896
+ if (requestedProperties.length) {
1897
+ Object.keys(instance).forEach((key) => {
1898
+ if (!requestedProperties.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'id' && key !== 'baseExpression')
1899
+ delete instance[key];
1900
+ });
1901
+ }
1902
+ // Collect values to assign to instance
1903
+ const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1904
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1905
+ return instance;
1906
+ }
1907
+ catch (error) {
1908
+ console.error(`Failed to process instance ${Base}:`, error);
1909
+ // Return null for failed instances - we'll filter these out below
1910
+ return null;
1911
+ }
1912
+ }));
1913
+ const instances = allInstances.filter((instance) => instance !== null);
1914
+ // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
1915
+ if (query.include && instances.length > 0) {
1916
+ await this.hydrateRelations(instances, perspective, query.include);
1917
+ }
1918
+ // Take snapshots for dirty tracking after ALL hydration is complete
1919
+ // (including eager-loaded relations).
1920
+ // When `include` is specified, only snapshot those relations.
1921
+ // Otherwise snapshot ALL fields (properties + relations) since
1922
+ // hydrateFromLinks populates relations with stable raw IDs.
1923
+ const snapshotRelations = query.include;
1924
+ for (const inst of instances) {
1925
+ inst.takeSnapshot(snapshotRelations);
1926
+ }
1927
+ return { results: instances, totalCount: result[0].TotalCount };
1928
+ }
1929
+ /**
1930
+ * Converts SurrealDB query results to Ad4mModel instances.
1931
+ *
1932
+ * @param perspective - The perspective context
1933
+ * @param query - The query parameters used
1934
+ * @param result - Array of result objects from SurrealDB
1935
+ * @returns Promise resolving to results with total count
1936
+ *
1937
+ * @internal
1938
+ */
1939
+ static async instancesFromSurrealResult(perspective, query, result) {
1940
+ if (!result || result.length === 0)
1941
+ return { results: [], totalCount: 0 };
1942
+ const metadata = this.getModelMetadata();
1943
+ const requestedProperties = query?.properties || [];
1944
+ // The query used GROUP BY with graph traversal, so each row has:
1945
+ // - source: the node ID (e.g., "node:abc123")
1946
+ // - source_uri: the actual URI (the base expression)
1947
+ // - links: array of link objects with {predicate, target, author, timestamp}
1948
+ const instances = [];
1949
+ for (const row of result) {
1950
+ let base;
1951
+ try {
1952
+ // Use source_uri as the base (the actual URI), not the node ID
1953
+ base = row.source_uri;
1954
+ // Skip rows without a source_uri field
1955
+ if (!base) {
1956
+ continue;
1957
+ }
1958
+ const links = row.links || [];
1959
+ const instance = new this(perspective, base);
1960
+ // Core hydration via unified helper (pass requestedProperties for sparse fieldset)
1961
+ await this.hydrateFromLinks(instance, links, metadata, perspective, requestedProperties.length > 0 ? requestedProperties : undefined);
1962
+ // When specific properties are requested, delete unrequested properties
1963
+ // so they return undefined instead of their constructor defaults (e.g. 0, [])
1964
+ if (requestedProperties.length > 0) {
1965
+ const requested = new Set(requestedProperties);
1966
+ for (const propName of Object.keys(metadata.properties)) {
1967
+ if (!requested.has(propName)) {
1968
+ delete instance[propName];
1969
+ }
1970
+ }
1971
+ for (const relName of Object.keys(metadata.relations)) {
1972
+ if (!requested.has(relName) && !(query.include && relName in query.include)) {
1973
+ delete instance[relName];
1974
+ }
1975
+ }
1976
+ // Also strip metadata fields unless explicitly requested
1977
+ for (const metaField of ['author', 'createdAt', 'updatedAt']) {
1978
+ if (!requested.has(metaField)) {
1979
+ delete instance[metaField];
1980
+ }
1981
+ }
1982
+ }
1983
+ instances.push(instance);
1984
+ }
1985
+ catch (error) {
1986
+ console.error(`Failed to process SurrealDB instance ${base}:`, error);
1987
+ }
1988
+ }
1989
+ // Populate reverse relation fields (belongsToOne / belongsToMany) as string IDs.
1990
+ // These relations point FROM other nodes TO this instance, so they cannot be resolved
1991
+ // from the node's own outgoing links fetched above. We do a reverse-link lookup here
1992
+ // so that these fields are populated as IDs even without an explicit include.
1993
+ const allRelsMeta = getRelationsMetadata(this);
1994
+ const reverseRelEntries = Object.entries(allRelsMeta).filter(([relName, meta]) => (meta.kind === 'belongsToOne' || meta.kind === 'belongsToMany') &&
1995
+ (requestedProperties.length === 0 || requestedProperties.includes(relName)));
1996
+ if (reverseRelEntries.length > 0 && instances.length > 0) {
1997
+ await Promise.all(instances.map(async (inst) => {
1998
+ for (const [relName, relMeta] of reverseRelEntries) {
1999
+ const reverseLinks = await perspective.get(new LinkQuery({ predicate: relMeta.predicate, target: inst.id }));
2000
+ const sourceIds = reverseLinks
2001
+ .filter((l) => l.data.target === inst.id)
2002
+ .map((l) => l.data.source);
2003
+ if (relMeta.kind === 'belongsToOne') {
2004
+ inst[relName] = sourceIds.length > 0 ? sourceIds[sourceIds.length - 1] : null;
2005
+ }
2006
+ else {
2007
+ inst[relName] = sourceIds;
2008
+ }
2009
+ }
2010
+ }));
2011
+ }
2012
+ // Evaluate custom getters for all instances (single pass)
2013
+ for (const instance of instances) {
2014
+ await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
2015
+ }
2016
+ // Filter by where conditions that couldn't be filtered in SQL
2017
+ // This includes:
2018
+ // - author/timestamp (computed from grouped links)
2019
+ // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
2020
+ // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
2021
+ let filteredInstances = instances;
2022
+ if (query.where) {
2023
+ filteredInstances = instances.filter(instance => {
2024
+ for (const [propertyName, condition] of Object.entries(query.where)) {
2025
+ // Skip 'base' as it's filtered in SQL
2026
+ if (propertyName === 'base')
2027
+ continue;
2028
+ // For author and timestamp, always filter in JS
2029
+ if (propertyName === 'author' || propertyName === 'timestamp') {
2030
+ if (!this.matchesCondition(instance[propertyName], condition)) {
2031
+ return false;
2032
+ }
2033
+ continue;
2034
+ }
2035
+ // For regular properties, only filter comparison operators in JS
2036
+ // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
2037
+ if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
2038
+ const ops = condition;
2039
+ // Check if any comparison operators are present
2040
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
2041
+ ops.lt !== undefined || ops.lte !== undefined ||
2042
+ ops.between !== undefined || ops.contains !== undefined;
2043
+ if (hasComparisonOps) {
2044
+ if (!this.matchesCondition(instance[propertyName], condition)) {
2045
+ return false;
2046
+ }
2047
+ }
2048
+ }
2049
+ }
2050
+ return true;
2051
+ });
2052
+ }
2053
+ // Apply ordering in JavaScript
2054
+ // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
2055
+ // This ensures consistent pagination behavior
2056
+ const effectiveOrder = query.order ||
2057
+ (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
2058
+ if (effectiveOrder) {
2059
+ const orderEntries = Object.entries(effectiveOrder);
2060
+ filteredInstances.sort((a, b) => {
2061
+ for (const [orderPropName, orderDirection] of orderEntries) {
2062
+ let aVal = a[orderPropName];
2063
+ let bVal = b[orderPropName];
2064
+ // Handle undefined values - push them to the end
2065
+ if (aVal === undefined && bVal === undefined)
2066
+ continue;
2067
+ if (aVal === undefined)
2068
+ return orderDirection === 'ASC' ? 1 : -1;
2069
+ if (bVal === undefined)
2070
+ return orderDirection === 'ASC' ? -1 : 1;
2071
+ // Compare values
2072
+ let comparison = 0;
2073
+ if (typeof aVal === 'number' && typeof bVal === 'number') {
2074
+ comparison = aVal - bVal;
2075
+ }
2076
+ else if (typeof aVal === 'string' && typeof bVal === 'string') {
2077
+ comparison = aVal.localeCompare(bVal);
2078
+ }
2079
+ else {
2080
+ comparison = String(aVal).localeCompare(String(bVal));
2081
+ }
2082
+ if (comparison !== 0) {
2083
+ return orderDirection === 'DESC' ? -comparison : comparison;
2084
+ }
2085
+ // comparison === 0: continue to next sort field
2086
+ }
2087
+ return 0;
2088
+ });
2089
+ }
2090
+ // Calculate totalCount BEFORE applying limit/offset
2091
+ const totalCount = filteredInstances.length;
2092
+ // Apply offset and limit in JavaScript
2093
+ let paginatedInstances = filteredInstances;
2094
+ if (query.offset !== undefined || query.limit !== undefined) {
2095
+ const start = query.offset || 0;
2096
+ const end = query.limit ? start + query.limit : undefined;
2097
+ paginatedInstances = filteredInstances.slice(start, end);
2098
+ }
2099
+ // Eager-load relations if requested (BEFORE snapshot so dirty tracking is accurate)
2100
+ if (query.include && paginatedInstances.length > 0) {
2101
+ await this.hydrateRelations(paginatedInstances, perspective, query.include);
2102
+ }
2103
+ // Take snapshots for dirty tracking after ALL hydration is complete
2104
+ // (including eager-loaded relations).
2105
+ // When `include` is specified, only snapshot those relations.
2106
+ // Otherwise snapshot ALL fields (properties + relations) since
2107
+ // hydrateFromLinks populates relations with stable raw IDs —
2108
+ // this ensures push-to-array + save() correctly detects dirty relations.
2109
+ const snapshotRelations = query.include;
2110
+ for (const inst of paginatedInstances) {
2111
+ inst.takeSnapshot(snapshotRelations);
2112
+ }
2113
+ return {
2114
+ results: paginatedInstances,
2115
+ totalCount
2116
+ };
2117
+ }
2118
+ /**
2119
+ * Checks if a value matches a condition (for post-query filtering).
2120
+ * @private
2121
+ */
2122
+ static matchesCondition(value, condition) {
2123
+ // Handle array values (IN clause)
2124
+ if (Array.isArray(condition)) {
2125
+ return condition.includes(value);
2126
+ }
2127
+ // Handle operator object
2128
+ if (typeof condition === 'object' && condition !== null) {
2129
+ const ops = condition;
2130
+ // Special case: 'not' operator (exclusive with other operators)
2131
+ if (ops.not !== undefined) {
2132
+ if (Array.isArray(ops.not)) {
2133
+ return !ops.not.includes(value);
2134
+ }
2135
+ else {
2136
+ return value !== ops.not;
2137
+ }
2138
+ }
2139
+ // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
2140
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
2141
+ return value >= ops.between[0] && value <= ops.between[1];
2142
+ }
2143
+ // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
2144
+ // and return true only if ALL conditions are satisfied
2145
+ let allConditionsMet = true;
2146
+ if (ops.gt !== undefined) {
2147
+ allConditionsMet = allConditionsMet && (value > ops.gt);
2148
+ }
2149
+ if (ops.gte !== undefined) {
2150
+ allConditionsMet = allConditionsMet && (value >= ops.gte);
2151
+ }
2152
+ if (ops.lt !== undefined) {
2153
+ allConditionsMet = allConditionsMet && (value < ops.lt);
2154
+ }
2155
+ if (ops.lte !== undefined) {
2156
+ allConditionsMet = allConditionsMet && (value <= ops.lte);
2157
+ }
2158
+ if (ops.contains !== undefined) {
2159
+ if (typeof value === 'string') {
2160
+ allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
2161
+ }
2162
+ else if (Array.isArray(value)) {
2163
+ allConditionsMet = allConditionsMet && value.includes(ops.contains);
2164
+ }
2165
+ else {
2166
+ allConditionsMet = false;
2167
+ }
2168
+ }
2169
+ return allConditionsMet;
2170
+ }
2171
+ // Simple equality
2172
+ return value === condition;
2173
+ }
2174
+ /**
2175
+ * Gets all instances of the model in the perspective that match the query params.
2176
+ *
2177
+ * @param perspective - The perspective to search in
2178
+ * @param query - Optional query parameters to filter results
2179
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2180
+ * @returns Array of matching models
2181
+ *
2182
+ * @example
2183
+ * ```typescript
2184
+ * // Get all recipes (uses SurrealDB by default)
2185
+ * const allRecipes = await Recipe.findAll(perspective);
2186
+ *
2187
+ * // Get recipes with specific criteria (uses SurrealDB)
2188
+ * const recipes = await Recipe.findAll(perspective, {
2189
+ * where: {
2190
+ * name: "Pasta",
2191
+ * rating: { gt: 4 }
2192
+ * },
2193
+ * order: { createdAt: "DESC" },
2194
+ * limit: 10
2195
+ * });
2196
+ *
2197
+ * // Explicitly use Prolog (legacy, for backward compatibility)
2198
+ * const recipesProlog = await Recipe.findAll(perspective, {}, false);
2199
+ * ```
2200
+ */
2201
+ static async findAll(perspective, query = {}, useSurrealDB = true) {
2202
+ if (query.properties && query.properties.length === 0) {
2203
+ throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
2204
+ }
2205
+ if (useSurrealDB) {
2206
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
2207
+ const result = await perspective.querySurrealDB(surrealQuery);
2208
+ const { results } = await this.instancesFromSurrealResult(perspective, query, result);
2209
+ return results;
2210
+ }
2211
+ else {
2212
+ const prologQuery = await this.queryToProlog(perspective, query);
2213
+ const result = await perspective.infer(prologQuery);
2214
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
2215
+ return results;
2216
+ }
2217
+ }
2218
+ /**
2219
+ * Finds the first instance matching the query, or `null` if none exists.
2220
+ *
2221
+ * Equivalent to `findAll` with `limit: 1` — only one instance is hydrated.
2222
+ *
2223
+ * @param perspective - The perspective to search in
2224
+ * @param query - Optional query parameters to filter results
2225
+ * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
2226
+ * @returns The first matching instance, or `null`
2227
+ *
2228
+ * @example
2229
+ * ```typescript
2230
+ * const recipe = await Recipe.findOne(perspective, {
2231
+ * where: { name: "Pasta" }
2232
+ * });
2233
+ * if (recipe) {
2234
+ * console.log(recipe.name);
2235
+ * }
2236
+ * ```
2237
+ */
2238
+ static async findOne(perspective, query = {}, useSurrealDB = true) {
2239
+ const limitedQuery = { ...query, limit: 1 };
2240
+ const results = await this.findAll(perspective, limitedQuery, useSurrealDB);
2241
+ return results[0] ?? null;
2242
+ }
2243
+ /**
2244
+ * Gets all instances with count of total matches without offset & limit applied.
2245
+ *
2246
+ * @param perspective - The perspective to search in
2247
+ * @param query - Optional query parameters to filter results
2248
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2249
+ * @returns Object containing results array and total count
2250
+ *
2251
+ * @example
2252
+ * ```typescript
2253
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
2254
+ * where: { category: "Dessert" },
2255
+ * limit: 10
2256
+ * });
2257
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
2258
+ *
2259
+ * // Use Prolog explicitly (legacy)
2260
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
2261
+ * ```
2262
+ */
2263
+ static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
2264
+ if (useSurrealDB) {
2265
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
2266
+ const result = await perspective.querySurrealDB(surrealQuery);
2267
+ return await this.instancesFromSurrealResult(perspective, query, result);
2268
+ }
2269
+ else {
2270
+ const prologQuery = await this.queryToProlog(perspective, query);
2271
+ const result = await perspective.infer(prologQuery);
2272
+ return await this.instancesFromPrologResult(perspective, query, result);
2273
+ }
2274
+ }
2275
+ /**
2276
+ * Helper function for pagination with explicit page size and number.
2277
+ *
2278
+ * @param perspective - The perspective to search in
2279
+ * @param pageSize - Number of items per page
2280
+ * @param pageNumber - Which page to retrieve (1-based)
2281
+ * @param query - Optional additional query parameters
2282
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2283
+ * @returns Paginated results with metadata
2284
+ *
2285
+ * @example
2286
+ * ```typescript
2287
+ * const page = await Recipe.paginate(perspective, 10, 1, {
2288
+ * where: { category: "Main Course" }
2289
+ * });
2290
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
2291
+ *
2292
+ * // Use Prolog explicitly (legacy)
2293
+ * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
2294
+ * ```
2295
+ */
2296
+ static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
2297
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
2298
+ if (useSurrealDB) {
2299
+ const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
2300
+ const result = await perspective.querySurrealDB(surrealQuery);
2301
+ const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
2302
+ return { results, totalCount, pageSize, pageNumber };
2303
+ }
2304
+ else {
2305
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
2306
+ const result = await perspective.infer(prologQuery);
2307
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
2308
+ return { results, totalCount, pageSize, pageNumber };
2309
+ }
2310
+ }
2311
+ static async countQueryToProlog(perspective, query = {}, modelClassName) {
2312
+ const { where } = query;
2313
+ const className = modelClassName || (await this.getClassName(perspective));
2314
+ const resolvedParentPredicate = query.parent
2315
+ ? resolveParentPredicate(query.parent, this)
2316
+ : undefined;
2317
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildParentQuery(query.parent, resolvedParentPredicate), buildWhereQuery(where)];
2318
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
2319
+ const fullQuery = `
2320
+ findall([Base, Properties, Collections, Timestamp, Author], (
2321
+ subject_class("${className}", SubjectClass),
2322
+ instance(SubjectClass, Base),
2323
+ ${instanceQueries.filter((q) => q).join(", ")}
2324
+ ), UnsortedInstances),
2325
+ ${resultSetQueries.filter((q) => q).join(", ")}
2326
+ `;
2327
+ return fullQuery;
2328
+ }
2329
+ /**
2330
+ * Generates a SurrealQL COUNT query for the model.
2331
+ *
2332
+ * @param perspective - The perspective context
2333
+ * @param query - Query parameters to filter the count
2334
+ * @returns SurrealQL COUNT query string
2335
+ *
2336
+ * @private
2337
+ */
2338
+ static async countQueryToSurrealQL(perspective, query) {
2339
+ // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
2340
+ // We'll count the number of rows returned (one row per source)
2341
+ const countQuery = { ...query };
2342
+ delete countQuery.limit;
2343
+ delete countQuery.offset;
2344
+ return await this.queryToSurrealQL(perspective, countQuery);
2345
+ }
2346
+ /**
2347
+ * Gets a count of all matching instances.
2348
+ *
2349
+ * @param perspective - The perspective to search in
2350
+ * @param query - Optional query parameters to filter results
2351
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2352
+ * @returns Total count of matching entities
2353
+ *
2354
+ * @example
2355
+ * ```typescript
2356
+ * const totalRecipes = await Recipe.count(perspective);
2357
+ * const activeRecipes = await Recipe.count(perspective, {
2358
+ * where: { status: "active" }
2359
+ * });
2360
+ *
2361
+ * // Use Prolog explicitly (legacy)
2362
+ * const countProlog = await Recipe.count(perspective, {}, false);
2363
+ * ```
2364
+ */
2365
+ static async count(perspective, query = {}, useSurrealDB = true) {
2366
+ if (useSurrealDB) {
2367
+ const surrealQuery = await this.queryToSurrealQL(perspective, query);
2368
+ const result = await perspective.querySurrealDB(surrealQuery);
2369
+ // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
2370
+ // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
2371
+ // This ensures count() returns the same number as findAll().length
2372
+ const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
2373
+ return totalCount;
2374
+ }
2375
+ else {
2376
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
2377
+ return result?.[0]?.TotalCount || 0;
2378
+ }
2379
+ }
2380
+ async setProperty(key, value, batchId) {
2381
+ // Phase 1: Use metadata instead of Prolog queries
2382
+ const metadata = this.getPropertyMetadata(key);
2383
+ if (!metadata) {
2384
+ console.warn(`Property "${key}" has no metadata, skipping`);
2385
+ return;
2386
+ }
2387
+ // Generate actions from metadata (replaces Prolog query)
2388
+ const actions = this.generatePropertySetterAction(key, metadata);
2389
+ // Get resolve language from metadata (replaces Prolog query)
2390
+ let resolveLanguage = metadata.resolveLanguage;
2391
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
2392
+ if (value === undefined || value === null || value === "") {
2393
+ return;
2394
+ }
2395
+ if (resolveLanguage) {
2396
+ value = await this._perspective.createExpression(value, resolveLanguage);
2397
+ }
2398
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }], batchId);
2399
+ }
2400
+ /** Resolve a relation argument to a plain string ID. Accepts either a raw
2401
+ * string ID or an Ad4mModel instance (in which case `.id` is used). */
2402
+ resolveRelationId(value) {
2403
+ if (typeof value === 'string')
2404
+ return value;
2405
+ if (value && typeof value === 'object' && typeof value.id === 'string')
2406
+ return value.id;
2407
+ return String(value);
2408
+ }
2409
+ async setRelationValues(key, value, batchId) {
2410
+ // Phase 1: Use metadata instead of Prolog queries
2411
+ const metadata = this.getRelationOptions(key);
2412
+ if (!metadata) {
2413
+ console.warn(`Relation "${key}" has no metadata, skipping`);
2414
+ return;
2415
+ }
2416
+ // Generate actions from metadata (replaces Prolog query)
2417
+ const actions = this.generateRelationAction(key, 'setter');
2418
+ if (value != null) {
2419
+ if (Array.isArray(value)) {
2420
+ await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: this.resolveRelationId(v) })), batchId);
2421
+ }
2422
+ else {
2423
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
2424
+ }
2425
+ }
2426
+ }
2427
+ async addRelationValue(key, value, batchId) {
2428
+ // Phase 1: Use metadata instead of Prolog queries
2429
+ const metadata = this.getRelationOptions(key);
2430
+ if (!metadata) {
2431
+ console.warn(`Relation "${key}" has no metadata, skipping`);
2432
+ return;
2433
+ }
2434
+ // Generate actions from metadata (replaces Prolog query)
2435
+ const actions = this.generateRelationAction(key, 'adder');
2436
+ if (value != null) {
2437
+ if (Array.isArray(value)) {
2438
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
2439
+ }
2440
+ else {
2441
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
2442
+ }
2443
+ }
2444
+ }
2445
+ async removeRelationValue(key, value, batchId) {
2446
+ // Phase 1: Use metadata instead of Prolog queries
2447
+ const metadata = this.getRelationOptions(key);
2448
+ if (!metadata) {
2449
+ console.warn(`Relation "${key}" has no metadata, skipping`);
2450
+ return;
2451
+ }
2452
+ // Generate actions from metadata (replaces Prolog query)
2453
+ const actions = this.generateRelationAction(key, 'remover');
2454
+ if (value != null) {
2455
+ if (Array.isArray(value)) {
2456
+ await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(v) }], batchId)));
2457
+ }
2458
+ else {
2459
+ await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value: this.resolveRelationId(value) }], batchId);
2460
+ }
2461
+ }
2462
+ }
2463
+ /**
2464
+ * Saves the model instance to the perspective.
2465
+ *
2466
+ * **New instances** (no snapshot yet): creates the subject via
2467
+ * `createSubject` with initial scalar values, then sets relations
2468
+ * via `innerUpdate`.
2469
+ *
2470
+ * **Existing instances** (snapshot present, i.e. fetched via `get()`
2471
+ * or a query): updates only dirty fields via `innerUpdate`, then
2472
+ * refreshes from the perspective.
2473
+ *
2474
+ * @param batchId - Optional batch ID for batch operations
2475
+ * @throws Will throw if instance creation, linking, or updating fails
2476
+ *
2477
+ * @example
2478
+ * ```typescript
2479
+ * // Create
2480
+ * const recipe = new Recipe(perspective);
2481
+ * recipe.name = "Spaghetti";
2482
+ * await recipe.save();
2483
+ *
2484
+ * // Update
2485
+ * recipe.rating = 10;
2486
+ * await recipe.save();
2487
+ * ```
2488
+ */
2489
+ async save(batchId) {
2490
+ // Existing instance → update path (has been fetched / hydrated before)
2491
+ if (this._snapshot) {
2492
+ await this.innerUpdate(true, batchId);
2493
+ if (batchId) {
2494
+ // Batch hasn't been committed yet — getData() would fetch stale data
2495
+ // and overwrite in-memory values. Just refresh the snapshot so further
2496
+ // saves within the same batch diff correctly.
2497
+ this.takeSnapshot();
2498
+ }
2499
+ else {
2500
+ await this.getData();
2501
+ }
2502
+ return;
2503
+ }
2504
+ // New instance → create path
2505
+ let batchCreatedHere = false;
2506
+ if (!batchId) {
2507
+ batchId = await this.perspective.createBatch();
2508
+ batchCreatedHere = true;
2509
+ }
2510
+ // Check if the model has any constructor actions (required properties,
2511
+ // flags, or properties with initial values). Models whose properties are
2512
+ // all optional, have no @Flag, and have no initial values produce an empty
2513
+ // SHACL constructor, so calling createSubject would fail on the Rust side
2514
+ // ("No SHACL constructor found"). In that case we skip createSubject
2515
+ // entirely and let innerUpdate write the links directly.
2516
+ const metadata = this.constructor.getModelMetadata();
2517
+ const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2518
+ // Track properties that have resolveLanguage (non-literal) so they can be
2519
+ // set via setProperty after createSubject (which doesn't resolve languages).
2520
+ const deferredResolveLanguageProps = [];
2521
+ if (hasConstructor) {
2522
+ // First filter out the properties that are not relations (arrays)
2523
+ const initialValues = {};
2524
+ for (const [key, value] of Object.entries(this)) {
2525
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2526
+ // Check if this property requires language resolution (e.g. file storage).
2527
+ // If so, resolve the expression *before* passing to createSubject so
2528
+ // the constructor receives a valid URI instead of raw data.
2529
+ const propMeta = metadata.properties[key];
2530
+ if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
2531
+ // Defer these properties — they need createExpression which may
2532
+ // fail inside a batch context on some languages. We'll set them
2533
+ // via setProperty after createSubject.
2534
+ deferredResolveLanguageProps.push(key);
2535
+ continue;
2536
+ }
2537
+ initialValues[key] = value;
2538
+ }
2539
+ }
2540
+ // Get the class name instead of passing the instance to avoid Prolog query generation
2541
+ const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
2542
+ // Create the subject with the initial values
2543
+ await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);
2544
+ }
2545
+ // Set properties and relations via innerUpdate.
2546
+ // When createSubject was skipped (no constructor actions), we must enable
2547
+ // property writing so that scalar values are persisted as links.
2548
+ await this.innerUpdate(!hasConstructor, batchId);
2549
+ // Now handle any deferred resolveLanguage properties that were excluded
2550
+ // from initialValues. setProperty will call createExpression to upload
2551
+ // the data to the appropriate language and store the resulting URI.
2552
+ for (const key of deferredResolveLanguageProps) {
2553
+ const value = this[key];
2554
+ if (value !== undefined && value !== null) {
2555
+ await this.setProperty(key, value, batchId);
2556
+ }
2557
+ }
2558
+ // If we got a batchId passed in, we let the caller decide when to commit.
2559
+ // We can't call getData() since the instance won't exist in the perspective
2560
+ // until the batch is committed.
2561
+ if (batchCreatedHere) {
2562
+ await this.perspective.commitBatch(batchId);
2563
+ await this.getData();
2564
+ }
2565
+ else {
2566
+ // Take a snapshot so that a subsequent save() within the same batch
2567
+ // routes through the UPDATE path instead of CREATE, avoiding duplicate
2568
+ // links (e.g. two competing "title" values).
2569
+ this.takeSnapshot();
2570
+ }
2571
+ }
2572
+ cleanCopy() {
2573
+ const ctor = this.constructor;
2574
+ const metadata = ctor.getModelMetadata();
2575
+ const cleanCopy = {};
2576
+ // Only include schema-declared fields (properties + relations),
2577
+ // preserving internal ORM machinery (_id, _perspective, generated
2578
+ // addX/removeX/setX methods, _snapshot, etc.)
2579
+ const schemaFields = new Set([
2580
+ ...Object.keys(metadata.properties),
2581
+ ...Object.keys(metadata.relations),
2582
+ ]);
2583
+ for (const key of schemaFields) {
2584
+ const value = this[key];
2585
+ if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
2586
+ cleanCopy[key] = value;
2587
+ }
2588
+ }
2589
+ return cleanCopy;
2590
+ }
2591
+ async innerUpdate(setProperties = true, batchId) {
2592
+ const ctor = this.constructor;
2593
+ this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2594
+ // Determine which fields actually changed (skip unchanged when snapshot exists)
2595
+ const dirty = this._snapshot ? new Set(this.changedFields()) : null;
2596
+ // Only iterate schema-declared fields, not internal ORM properties
2597
+ const metadata = ctor.getModelMetadata();
2598
+ const schemaFields = new Set([
2599
+ ...Object.keys(metadata.properties),
2600
+ ...Object.keys(metadata.relations),
2601
+ ]);
2602
+ const entries = Object.entries(this);
2603
+ for (const [key, value] of entries) {
2604
+ // Only process schema-declared fields
2605
+ if (!schemaFields.has(key))
2606
+ continue;
2607
+ // Skip unchanged fields when a snapshot is available
2608
+ if (dirty && !dirty.has(key))
2609
+ continue;
2610
+ if (value !== undefined && value !== null) {
2611
+ if (value?.action) {
2612
+ switch (value.action) {
2613
+ case "setter":
2614
+ await this.setRelationValues(key, value.value, batchId);
2615
+ break;
2616
+ case "adder":
2617
+ await this.addRelationValue(key, value.value, batchId);
2618
+ break;
2619
+ case "remover":
2620
+ await this.removeRelationValue(key, value.value, batchId);
2621
+ break;
2622
+ default:
2623
+ await this.setRelationValues(key, value.value, batchId);
2624
+ break;
2625
+ }
2626
+ }
2627
+ else if (Array.isArray(value)) {
2628
+ // Handle all arrays as relations, including empty ones (which clears the relation)
2629
+ await this.setRelationValues(key, value, batchId);
2630
+ }
2631
+ else if (value !== undefined && value !== null && value !== "") {
2632
+ if (setProperties) {
2633
+ // Check if this is a relation property (has relation metadata)
2634
+ const relationMeta = this.getRelationOptions(key);
2635
+ if (relationMeta) {
2636
+ // Skip - it's a relation, not a regular property
2637
+ continue;
2638
+ }
2639
+ // Skip flag properties — they are immutable after creation
2640
+ const propMeta = this.getPropertyMetadata(key);
2641
+ if (propMeta?.flag) {
2642
+ continue;
2643
+ }
2644
+ await this.setProperty(key, value, batchId);
2645
+ }
2646
+ }
2647
+ }
2648
+ }
2649
+ }
2650
+ /**
2651
+ * Gets the model instance with all properties and relations populated.
2652
+ *
2653
+ * @param optsOrInclude - Optional hydration options. Accepts two forms:
2654
+ * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`
2655
+ * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)
2656
+ * @returns The populated model instance
2657
+ * @throws Will throw if data retrieval fails
2658
+ *
2659
+ * @example
2660
+ * ```typescript
2661
+ * const recipe = new Recipe(perspective, existingId);
2662
+ * await recipe.get();
2663
+ * console.log(recipe.name, recipe.ingredients);
2664
+ *
2665
+ * // Shorthand — pass IncludeMap directly:
2666
+ * await recipe.get({ ingredients: true });
2667
+ *
2668
+ * // Full options — includes sparse fieldset:
2669
+ * await recipe.get({ include: { ingredients: true }, properties: ['name'] });
2670
+ * ```
2671
+ */
2672
+ async get(optsOrInclude) {
2673
+ // Normalise: if the caller passed a plain IncludeMap shorthand (no `include`
2674
+ // or `properties` key at the top level) wrap it in GetOptions automatically.
2675
+ let opts;
2676
+ if (!optsOrInclude) {
2677
+ opts = undefined;
2678
+ }
2679
+ else if ('include' in optsOrInclude || 'properties' in optsOrInclude) {
2680
+ opts = optsOrInclude;
2681
+ }
2682
+ else {
2683
+ opts = { include: optsOrInclude };
2684
+ }
2685
+ this._subjectClassName = await this._perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
2686
+ return await this.getData(opts);
2687
+ }
2688
+ /**
2689
+ * Deletes the model instance from the perspective.
2690
+ *
2691
+ * @param batchId - Optional batch ID for batch operations
2692
+ * @throws Will throw if removal fails
2693
+ *
2694
+ * @example
2695
+ * ```typescript
2696
+ * const recipe = await Recipe.findAll(perspective)[0];
2697
+ * await recipe.delete();
2698
+ *
2699
+ * // Or with batch operations:
2700
+ * const batchId = await perspective.createBatch();
2701
+ * await recipe.delete(batchId);
2702
+ * await perspective.commitBatch(batchId);
2703
+ * ```
2704
+ */
2705
+ async delete(batchId) {
2706
+ // Check if the model has a destructor (required properties, flags, or
2707
+ // properties with initial values). Models whose properties are all
2708
+ // optional, have no @Flag, and have no initial values produce an empty
2709
+ // SHACL destructor, so calling removeSubject would fail. In that case
2710
+ // we skip the destructor and just remove all outgoing links directly.
2711
+ const metadata = this.constructor.getModelMetadata();
2712
+ const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
2713
+ if (hasDestructor) {
2714
+ // Remove the subject itself (destructor actions)
2715
+ await this._perspective.removeSubject(this, this._baseExpression, batchId);
2716
+ }
2717
+ else {
2718
+ // No destructor — manually remove all outgoing links from this node
2719
+ try {
2720
+ const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
2721
+ if (outgoingLinks.length > 0) {
2722
+ await this._perspective.removeLinks(outgoingLinks, batchId);
2723
+ }
2724
+ }
2725
+ catch (e) {
2726
+ console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
2727
+ }
2728
+ }
2729
+ // Clean up incoming links — remove any links that point **to** this instance
2730
+ try {
2731
+ const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
2732
+ if (incomingLinks.length > 0) {
2733
+ await this._perspective.removeLinks(incomingLinks, batchId);
2734
+ }
2735
+ }
2736
+ catch (e) {
2737
+ // Non-fatal: the subject was already deleted; incoming link cleanup is best-effort
2738
+ console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);
2739
+ }
2740
+ }
2741
+ /**
2742
+ * Creates and saves a new model instance in one step.
2743
+ *
2744
+ * @param perspective - The perspective to create the instance in
2745
+ * @param data - Property values to assign before saving
2746
+ * @param options - Optional settings:
2747
+ * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
2748
+ * be used to create an incoming link from the parent to the new instance.
2749
+ * - `batchId` — an existing batch id; when provided the link write and
2750
+ * `save()` are added to the batch instead of committed immediately.
2751
+ * @returns The saved model instance
2752
+ *
2753
+ * @example
2754
+ * ```typescript
2755
+ * // Simple create
2756
+ * const recipe = await Recipe.create(perspective, {
2757
+ * name: "Spaghetti",
2758
+ * rating: 5,
2759
+ * });
2760
+ *
2761
+ * // Create under a parent (link auto-created)
2762
+ * const comment = await Comment.create(perspective, { text: "Great!" }, {
2763
+ * parent: { model: Post, id: postId },
2764
+ * });
2765
+ *
2766
+ * // Create inside a transaction
2767
+ * await Ad4mModel.transaction(perspective, async (tx) => {
2768
+ * await Recipe.create(perspective, { name: "Pasta" }, { batchId: tx.batchId });
2769
+ * });
2770
+ * ```
2771
+ */
2772
+ static async create(perspective, data = {}, options) {
2773
+ const instance = new this(perspective);
2774
+ Object.assign(instance, data);
2775
+ // When a parent scope is provided without a caller-supplied batch, open a
2776
+ // new batch ourselves so that the instance creation and the parent→child
2777
+ // link are committed atomically. If either step throws, commitBatch is
2778
+ // never reached and the batch is implicitly abandoned (rollback).
2779
+ if (options?.parent && !options?.batchId) {
2780
+ const batchId = await perspective.createBatch();
2781
+ await instance.save(batchId);
2782
+ const predicate = resolveParentPredicate(options.parent, this);
2783
+ const link = new Link({
2784
+ source: options.parent.id,
2785
+ predicate,
2786
+ target: instance.id,
2787
+ });
2788
+ await perspective.add(link, 'shared', batchId);
2789
+ await perspective.commitBatch(batchId);
2790
+ // Hydrate the instance now that the batch has been committed (mirrors the
2791
+ // behaviour of save() when it manages its own batch).
2792
+ await instance.get();
2793
+ return instance;
2794
+ }
2795
+ await instance.save(options?.batchId);
2796
+ // Create parent → child link if a parent scope was provided
2797
+ if (options?.parent) {
2798
+ const predicate = resolveParentPredicate(options.parent, this);
2799
+ const link = new Link({
2800
+ source: options.parent.id,
2801
+ predicate,
2802
+ target: instance.id,
2803
+ });
2804
+ await perspective.add(link, 'shared', options?.batchId);
56
2805
  }
57
- return classCache[perspectiveID];
2806
+ return instance;
58
2807
  }
59
2808
  /**
60
- * Backwards compatibility alias for createdAt.
61
- * @deprecated Use createdAt instead. This will be removed in a future version.
2809
+ * Updates an existing model instance identified by `id`.
2810
+ *
2811
+ * Fetches the instance, applies the provided changes, calls `save()`,
2812
+ * and returns the refreshed instance.
2813
+ *
2814
+ * @param perspective - The perspective containing the instance
2815
+ * @param id - The expression URI of the instance to update
2816
+ * @param data - Property values to merge before saving
2817
+ * @returns The updated model instance
2818
+ *
2819
+ * @example
2820
+ * ```typescript
2821
+ * const recipe = await Recipe.update(perspective, recipeId, {
2822
+ * rating: 10,
2823
+ * });
2824
+ * ```
62
2825
  */
63
- get timestamp() {
64
- return this.createdAt;
2826
+ static async update(perspective, id, data) {
2827
+ const instance = new this(perspective, id);
2828
+ await instance.get();
2829
+ Object.assign(instance, data);
2830
+ await instance.save();
2831
+ return instance;
65
2832
  }
66
- /** Returns the class name, property predicates, and relation predicates from decorators. */
67
- static getModelMetadata() {
68
- return _getModelMetadata(this);
2833
+ /**
2834
+ * Deletes an existing model instance identified by `id`.
2835
+ *
2836
+ * Also cleans up any incoming links that point to this instance.
2837
+ *
2838
+ * @param perspective - The perspective containing the instance
2839
+ * @param id - The expression URI of the instance to delete
2840
+ *
2841
+ * @example
2842
+ * ```typescript
2843
+ * await Recipe.delete(perspective, recipeId);
2844
+ * ```
2845
+ *
2846
+ * @deprecated Use the name `delete` — `remove` is preserved as an alias.
2847
+ */
2848
+ static async remove(perspective, id) {
2849
+ return this.delete(perspective, id);
2850
+ }
2851
+ /**
2852
+ * Deletes an existing model instance identified by `id`.
2853
+ *
2854
+ * Also cleans up any incoming links that point to this instance.
2855
+ *
2856
+ * @param perspective - The perspective containing the instance
2857
+ * @param id - The expression URI of the instance to delete
2858
+ *
2859
+ * @example
2860
+ * ```typescript
2861
+ * await Recipe.delete(perspective, recipeId);
2862
+ * ```
2863
+ */
2864
+ static async delete(perspective, id) {
2865
+ const instance = new this(perspective, id);
2866
+ await instance.delete();
69
2867
  }
70
2868
  /**
71
- * Installs the SHACL/SDNA subject class in `perspective` (idempotent).
2869
+ * Registers this model's SHACL schema on the given perspective.
2870
+ *
2871
+ * This ensures the perspective knows about the model's shape
2872
+ * (properties, relations, constraints) so instances can be
2873
+ * created, queried, and validated.
2874
+ *
2875
+ * @param perspective - The perspective to register the model on
72
2876
  *
73
- * @example `await Promise.all([Post, Comment, Tag].map(M => M.register(perspective)));`
2877
+ * @example
2878
+ * ```typescript
2879
+ * await Recipe.register(perspective);
2880
+ * // Now you can create / query Recipe instances on this perspective
2881
+ * ```
74
2882
  */
75
2883
  static async register(perspective) {
76
2884
  await perspective.ensureSDNASubjectClass(this);
77
2885
  }
78
2886
  /**
79
- * One-shot factory: constructs, assigns `data`, saves, and returns the new instance.
2887
+ * Executes a set of model operations inside a single batch (transaction).
2888
+ *
2889
+ * All `save`, `update`, and `delete` calls made via the provided `batchId`
2890
+ * are buffered and flushed atomically when the callback completes.
2891
+ * If the callback throws, the batch is **not** committed, preventing
2892
+ * partial writes.
2893
+ *
2894
+ * @param perspective - The perspective to operate on
2895
+ * @param fn - Async callback that receives a `TransactionContext` object.
2896
+ * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,
2897
+ * `delete(tx.batchId)`, etc.
2898
+ * @returns The value returned by `fn`
80
2899
  *
81
2900
  * @example
82
2901
  * ```typescript
83
- * const post = await Post.create(perspective, { title: 'Hello', body: 'World' });
2902
+ * await Ad4mModel.transaction(perspective, async (tx) => {
2903
+ * const recipe = new Recipe(perspective);
2904
+ * recipe.name = "Spaghetti";
2905
+ * await recipe.save(tx.batchId);
2906
+ *
2907
+ * const old = await Recipe.query(perspective).where({ name: "Stale" }).run();
2908
+ * for (const r of old) await r.delete(tx.batchId);
2909
+ * });
2910
+ * // All changes committed atomically here
84
2911
  * ```
85
2912
  */
86
- static async create(perspective, data, options) {
87
- const instance = new this(perspective);
88
- Object.assign(instance, data);
89
- await instance.save(options?.batchId);
90
- if (options?.parent) {
91
- const { model, id, field } = options.parent;
92
- const predicate = resolveParentPredicate(model.getModelMetadata(), this, field);
93
- await perspective.addLinks([new Link({ source: id, predicate, target: instance.id })], "shared", options?.batchId);
94
- }
95
- return instance;
2913
+ static async transaction(perspective, fn) {
2914
+ const batchId = await perspective.createBatch();
2915
+ const result = await fn({ batchId });
2916
+ await perspective.commitBatch(batchId);
2917
+ return result;
96
2918
  }
97
2919
  /**
98
- * Fetches the instance, merges `data` into it, then saves.
2920
+ * Creates a query builder for fluent query construction.
99
2921
  *
100
- * This is a convenience alternative to the three-step pattern:
2922
+ * @param perspective - The perspective to query
2923
+ * @param query - Optional initial query parameters
2924
+ * @returns A new query builder instance
2925
+ *
2926
+ * @example
101
2927
  * ```typescript
102
- * // Before
103
- * const instance = new Vote(perspective, id);
104
- * instance.score = newScore;
105
- * await instance.save();
2928
+ * const recipes = await Recipe.query(perspective)
2929
+ * .where({ category: "Dessert" })
2930
+ * .order({ rating: "DESC" })
2931
+ * .limit(5)
2932
+ * .run();
106
2933
  *
107
- * // After
108
- * await Vote.update(perspective, id, { score: newScore });
2934
+ * // With real-time updates
2935
+ * await Recipe.query(perspective)
2936
+ * .where({ status: "cooking" })
2937
+ * .subscribe(recipes => {
2938
+ * console.log("Currently cooking:", recipes);
2939
+ * });
109
2940
  * ```
110
- *
111
- * @param data - Partial set of properties to merge into the stored instance.
112
- * @param batchId - Optional batch identifier for grouping writes.
113
- * @returns The updated instance with all fields populated.
114
2941
  */
115
- static async update(perspective, id, data, batchId) {
116
- const instance = new this(perspective, id);
117
- await instance.get();
118
- Object.assign(instance, data);
119
- await instance.save(batchId);
120
- return instance;
2942
+ static query(perspective, query) {
2943
+ return new ModelQueryBuilder(perspective, this, query);
121
2944
  }
122
2945
  /**
123
- * Deletes the instance with the given `id` from the perspective.
2946
+ * Creates an Ad4mModel class from a JSON Schema definition.
2947
+ *
2948
+ * @description
2949
+ * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
2950
+ * enabling integration with systems that use JSON Schema for type definitions.
124
2951
  *
125
- * This is a convenience alternative to:
2952
+ * The method follows a cascading approach for determining predicates:
2953
+ * 1. Explicit configuration in options parameter (highest precedence)
2954
+ * 2. x-ad4m metadata in the JSON Schema
2955
+ * 3. Inference from schema title and property names
2956
+ * 4. Error if no namespace can be determined
2957
+ *
2958
+ * @example
126
2959
  * ```typescript
127
- * // Before
128
- * const instance = new Poll(perspective, id);
129
- * await instance.delete();
2960
+ * // With explicit configuration
2961
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
2962
+ * name: "Person",
2963
+ * namespace: "person://",
2964
+ * resolveLanguage: "literal"
2965
+ * });
130
2966
  *
131
- * // After
132
- * await Poll.delete(perspective, id);
2967
+ * // With property mapping
2968
+ * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
2969
+ * name: "Contact",
2970
+ * namespace: "contact://",
2971
+ * propertyMapping: {
2972
+ * "name": "foaf://name",
2973
+ * "email": "foaf://mbox"
2974
+ * }
2975
+ * });
2976
+ *
2977
+ * // With x-ad4m metadata in schema
2978
+ * const schema = {
2979
+ * "title": "Product",
2980
+ * "x-ad4m": { "namespace": "product://" },
2981
+ * "properties": {
2982
+ * "name": {
2983
+ * "type": "string",
2984
+ * "x-ad4m": { "through": "product://title" }
2985
+ * }
2986
+ * }
2987
+ * };
2988
+ * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
133
2989
  * ```
134
2990
  *
135
- * @param batchId - Optional batch identifier for grouping removals.
2991
+ * @param schema - JSON Schema definition
2992
+ * @param options - Configuration options
2993
+ * @returns Generated Ad4mModel subclass
2994
+ * @throws Error when namespace cannot be inferred
136
2995
  */
137
- static async delete(perspective, id, batchId) {
138
- const instance = new this(perspective, id);
139
- await instance.delete(batchId);
2996
+ static fromJSONSchema(schema, options) {
2997
+ // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
2998
+ if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
2999
+ 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").');
3000
+ }
3001
+ // Determine namespace with cascading precedence
3002
+ const namespace = this.determineNamespace(schema, options);
3003
+ // Create the dynamic class
3004
+ const DynamicModelClass = class extends Ad4mModel {
3005
+ };
3006
+ // Set up class metadata
3007
+ if (!options.name || options.name.trim() === '') {
3008
+ throw new Error("options.name is required and cannot be empty");
3009
+ }
3010
+ DynamicModelClass.className = options.name;
3011
+ DynamicModelClass.prototype.className = options.name;
3012
+ // Generate properties and relations metadata
3013
+ const properties = {};
3014
+ const relations = {};
3015
+ if (schema.properties) {
3016
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
3017
+ const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
3018
+ const isRequired = schema.required?.includes(propertyName) || false;
3019
+ const propertyType = normalizeSchemaType(propertySchema.type);
3020
+ const isArray = isArrayType(propertySchema);
3021
+ if (isArray) {
3022
+ // Handle arrays as relations
3023
+ // Store the singular form as the relation key since SDNA generation expects singular
3024
+ relations[propertyName] = {
3025
+ through: predicate,
3026
+ local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
3027
+ };
3028
+ // Define the property on prototype
3029
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3030
+ configurable: true,
3031
+ writable: true,
3032
+ value: []
3033
+ });
3034
+ // Add relation methods
3035
+ const adderName = `add${capitalize(propertyName)}`;
3036
+ const removerName = `remove${capitalize(propertyName)}`;
3037
+ const setterName = `set${capitalize(propertyName)}`;
3038
+ DynamicModelClass.prototype[adderName] = function () {
3039
+ // Placeholder function for SDNA generation
3040
+ };
3041
+ DynamicModelClass.prototype[removerName] = function () {
3042
+ // Placeholder function for SDNA generation
3043
+ };
3044
+ DynamicModelClass.prototype[setterName] = function () {
3045
+ // Placeholder function for SDNA generation
3046
+ };
3047
+ }
3048
+ else {
3049
+ // Handle regular properties
3050
+ let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
3051
+ // If no specific resolveLanguage for this property, use the global one
3052
+ if (!resolveLanguage && options.resolveLanguage) {
3053
+ resolveLanguage = options.resolveLanguage;
3054
+ }
3055
+ const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
3056
+ // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
3057
+ let readOnly = this.getPropertyOption(propertyName, propertySchema, options, 'readOnly');
3058
+ if (readOnly === undefined) {
3059
+ const xWritable = propertySchema["x-ad4m"]?.writable;
3060
+ readOnly = xWritable !== undefined ? !xWritable : false;
3061
+ }
3062
+ const writable = !readOnly;
3063
+ let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
3064
+ // Handle nested objects by serializing to JSON
3065
+ if (isObjectType(propertySchema) && !resolveLanguage) {
3066
+ resolveLanguage = 'literal';
3067
+ console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
3068
+ }
3069
+ // Ensure numeric properties use literal language for correct typing
3070
+ if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
3071
+ resolveLanguage = 'literal';
3072
+ }
3073
+ // Default resolveLanguage to 'literal' for all remaining property types,
3074
+ // matching the @Property decorator behaviour. Without this, string values
3075
+ // stored as literal:// URLs are returned unparsed.
3076
+ if (resolveLanguage === undefined || resolveLanguage === null) {
3077
+ resolveLanguage = 'literal';
3078
+ }
3079
+ // If property is required, ensure it has an initial value
3080
+ if (isRequired && !initial) {
3081
+ if (isObjectType(propertySchema)) {
3082
+ initial = 'literal://json:{}';
3083
+ }
3084
+ else {
3085
+ initial = "ad4m://undefined";
3086
+ }
3087
+ }
3088
+ properties[propertyName] = {
3089
+ through: predicate,
3090
+ required: isRequired,
3091
+ writable: writable,
3092
+ ...(resolveLanguage && { resolveLanguage }),
3093
+ ...(local !== undefined && { local }),
3094
+ ...(initial && { initial })
3095
+ };
3096
+ // Define the property on prototype
3097
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
3098
+ configurable: true,
3099
+ writable: true,
3100
+ value: this.getDefaultValueForType(propertyType)
3101
+ });
3102
+ // Add setter function if writable
3103
+ if (writable) {
3104
+ const setterName = propertyNameToSetterName(propertyName);
3105
+ DynamicModelClass.prototype[setterName] = function () {
3106
+ // This is a placeholder function that the SDNA generation looks for
3107
+ // The actual setter logic is handled by the Ad4mModel base class
3108
+ };
3109
+ }
3110
+ }
3111
+ }
3112
+ }
3113
+ // No auto-flag generation — models with all-optional properties use
3114
+ // open-world structural matching. Consumers who need type discrimination
3115
+ // should add an explicit @Flag to their model definition.
3116
+ // Attach metadata to WeakMap registries
3117
+ for (const [propName, propMeta] of Object.entries(properties)) {
3118
+ setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);
3119
+ }
3120
+ for (const [relName, relMeta] of Object.entries(relations)) {
3121
+ setRelationRegistryEntry(DynamicModelClass, relName, {
3122
+ predicate: relMeta.through || "",
3123
+ kind: 'hasMany',
3124
+ ...(relMeta.getter !== undefined && { getter: relMeta.getter }),
3125
+ ...(relMeta.local !== undefined && { local: relMeta.local }),
3126
+ });
3127
+ }
3128
+ // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
3129
+ DynamicModelClass.prototype.__jsonSchema = schema;
3130
+ DynamicModelClass.prototype.__jsonSchemaOptions = options;
3131
+ // Apply the Model decorator to set up the generateSDNA method
3132
+ const ModelDecorator = Model({ name: options.name });
3133
+ ModelDecorator(DynamicModelClass);
3134
+ return DynamicModelClass;
140
3135
  }
141
3136
  /**
142
- * Generates the SHACL shape for this model class.
143
- * Attached dynamically by the `@Model` decorator.
3137
+ * Determines the namespace for predicates using cascading precedence
144
3138
  */
145
- static generateSHACL() {
146
- throw new Error("generateSHACL() is only available on classes decorated with @Model");
3139
+ static determineNamespace(schema, options) {
3140
+ // 1. Explicit namespace in options (highest precedence)
3141
+ if (options.namespace) {
3142
+ return options.namespace;
3143
+ }
3144
+ // 2. x-ad4m metadata in schema
3145
+ if (schema["x-ad4m"]?.namespace) {
3146
+ return schema["x-ad4m"].namespace;
3147
+ }
3148
+ // 3. Infer from schema title
3149
+ if (schema.title) {
3150
+ return `${schema.title.toLowerCase()}://`;
3151
+ }
3152
+ // 4. Try to extract from $id if it's a URL
3153
+ if (schema.$id) {
3154
+ try {
3155
+ const url = new URL(schema.$id);
3156
+ const pathParts = url.pathname.split('/').filter(p => p);
3157
+ if (pathParts.length > 0) {
3158
+ const lastPart = pathParts[pathParts.length - 1];
3159
+ const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
3160
+ return `${baseName.toLowerCase()}://`;
3161
+ }
3162
+ }
3163
+ catch {
3164
+ // If $id is not a valid URL, continue to error
3165
+ }
3166
+ }
3167
+ // 5. Error if no namespace can be determined
3168
+ throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
3169
+ - options.namespace
3170
+ - schema["x-ad4m"].namespace
3171
+ - schema.title
3172
+ - valid schema.$id`);
147
3173
  }
148
- /** @param id - Auto-generated from a random literal if omitted. */
149
- constructor(perspective, id) {
150
- /** Tracks whether save() has ever been called on this instance (even in an uncommitted batch). */
151
- this._savedOnce = false;
152
- this._id = id ? id : Literal.from(makeRandomId(24)).toUrl();
153
- this._perspective = perspective;
154
- // Wire up real relation adder/remover/setter methods for decorator-based classes.
155
- // The @HasMany / @HasOne decorators place empty stubs on the prototype at class-definition
156
- // time (e.g. `addLocations = () => {}`). Here, at instance-creation time, we replace each
157
- // stub with a closure that actually calls the private implementation so that callers like
158
- // `instance.addLocations(value)` persist the link in the perspective.
159
- const proto = Object.getPrototypeOf(this);
160
- const relations = getRelationsMetadata(proto.constructor);
161
- for (const key of Object.keys(relations)) {
162
- // Reverse relations (@BelongsToOne / @BelongsToMany) are read-only traversals —
163
- // the link is owned by the other side, so no mutator methods should exist here.
164
- if (relations[key].direction === "reverse")
165
- continue;
166
- const cap = capitalize(key);
167
- this[`add${cap}`] = (value, batchId) => mutation.setRelationAdder(this._mutationContext(), key, value, batchId);
168
- this[`remove${cap}`] = (value, batchId) => mutation.setRelationRemover(this._mutationContext(), key, value, batchId);
169
- this[`set${cap}`] = (value, batchId) => mutation.setRelationSetter(this._mutationContext(), key, value, batchId);
3174
+ /**
3175
+ * Determines the predicate for a specific property using cascading precedence
3176
+ */
3177
+ static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
3178
+ // 1. Explicit property mapping (highest precedence)
3179
+ if (options.propertyMapping?.[propertyName]) {
3180
+ return options.propertyMapping[propertyName];
3181
+ }
3182
+ // 2. x-ad4m metadata in property schema
3183
+ if (propertySchema["x-ad4m"]?.through) {
3184
+ return propertySchema["x-ad4m"].through;
3185
+ }
3186
+ // 3. Generate from namespace + property name
3187
+ if (options.predicateTemplate) {
3188
+ const normalizedNs = normalizeNamespaceString(namespace);
3189
+ const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
3190
+ const nsNoScheme = rest || '';
3191
+ return options.predicateTemplate
3192
+ .replace('${namespace}', nsNoScheme)
3193
+ .replace('${scheme}', scheme)
3194
+ .replace('${ns}', nsNoScheme)
3195
+ .replace('${title}', schema.title || '')
3196
+ .replace('${property}', propertyName);
3197
+ }
3198
+ // 4. Custom predicate generator
3199
+ if (options.predicateGenerator) {
3200
+ return options.predicateGenerator(schema.title || '', propertyName);
3201
+ }
3202
+ // 5. Default: namespace + property name
3203
+ const normalizedNs = normalizeNamespaceString(namespace);
3204
+ if (normalizedNs.includes('://')) {
3205
+ // For namespaces like "product://", append property directly
3206
+ return `${normalizedNs}${propertyName}`;
3207
+ }
3208
+ else {
3209
+ return `${normalizedNs}://${propertyName}`;
170
3210
  }
171
3211
  }
172
3212
  /**
173
- * The unique identifier (base expression URI) of this instance.
3213
+ * Gets property-specific options using cascading precedence
174
3214
  */
175
- get id() {
176
- return this._id;
3215
+ static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
3216
+ // 1. Property-specific options
3217
+ if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
3218
+ return options.propertyOptions[propertyName][optionName];
3219
+ }
3220
+ // 2. x-ad4m metadata in property
3221
+ if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
3222
+ return propertySchema["x-ad4m"][optionName];
3223
+ }
3224
+ // 3. Global option
3225
+ if (options[optionName] !== undefined) {
3226
+ return options[optionName];
3227
+ }
3228
+ // 4. Default value
3229
+ return defaultValue;
177
3230
  }
178
- /** Read-only perspective access for subclasses. */
179
- get perspective() {
180
- return this._perspective;
3231
+ /**
3232
+ * Gets default value for a JSON Schema type
3233
+ */
3234
+ static getDefaultValueForType(type) {
3235
+ switch (type) {
3236
+ case 'string': return '';
3237
+ case 'number': return 0;
3238
+ case 'integer': return 0;
3239
+ case 'boolean': return false;
3240
+ case 'array': return [];
3241
+ case 'object': return {};
3242
+ default: return '';
3243
+ }
181
3244
  }
182
- /** Builds the context object for all mutation functions. */
183
- _mutationContext() {
184
- return {
185
- perspective: this._perspective,
186
- id: this._id,
187
- instance: this,
188
- };
3245
+ }
3246
+ Ad4mModel.classNamesByClass = new WeakMap();
3247
+ /** Query builder for Ad4mModel queries.
3248
+ * Allows building queries with a fluent interface and either running them once
3249
+ * or subscribing to updates.
3250
+ *
3251
+ * @example
3252
+ * ```typescript
3253
+ * const builder = Recipe.query(perspective)
3254
+ * .where({ category: "Dessert" })
3255
+ * .order({ rating: "DESC" })
3256
+ * .limit(10);
3257
+ *
3258
+ * // Run once
3259
+ * const recipes = await builder.run();
3260
+ *
3261
+ * // Or subscribe to updates
3262
+ * await builder.subscribe(recipes => {
3263
+ * console.log("Updated recipes:", recipes);
3264
+ * });
3265
+ * ```
3266
+ */
3267
+ export class ModelQueryBuilder {
3268
+ constructor(perspective, ctor, query) {
3269
+ this.queryParams = {};
3270
+ this.modelClassName = null;
3271
+ this.useSurrealDBFlag = true;
3272
+ this.perspective = perspective;
3273
+ this.ctor = ctor;
3274
+ if (query)
3275
+ this.queryParams = query;
189
3276
  }
190
3277
  /**
191
- * Generates a SurrealQL query string for this model.
3278
+ * Disposes of the current subscription if one exists.
192
3279
  *
193
- * @param perspective - The perspective context
194
- * @param query - Query parameters (where, order, limit, offset, properties, relations)
195
- * @returns Complete SurrealQL query string ready for execution
3280
+ * This method:
3281
+ * 1. Stops the keepalive signals to the subscription
3282
+ * 2. Unsubscribes from GraphQL subscription updates
3283
+ * 3. Notifies the backend to clean up subscription resources
3284
+ * 4. Clears the subscription reference
3285
+ *
3286
+ * You should call this method when you're done with a subscription
3287
+ * to prevent memory leaks and ensure proper cleanup.
196
3288
  */
197
- static async queryToSurrealQL(perspective, query) {
198
- return ops.queryToSurrealQL(this, perspective, query);
3289
+ dispose() {
3290
+ if (this.currentSubscription) {
3291
+ this.currentSubscription.dispose();
3292
+ this.currentSubscription = undefined;
3293
+ }
199
3294
  }
200
- /** @internal */
201
- static async instancesFromSurrealResult(perspective, query, result, _hydrateRelations = true) {
202
- return ops.instancesFromSurrealResult(this, perspective, query, result, _hydrateRelations);
3295
+ /**
3296
+ * Adds where conditions to the query.
3297
+ *
3298
+ * @param conditions - The conditions to filter by
3299
+ * @returns The query builder for chaining
3300
+ *
3301
+ * @example
3302
+ * ```typescript
3303
+ * .where({
3304
+ * category: "Dessert",
3305
+ * rating: { gt: 4 },
3306
+ * tags: ["vegan", "quick"],
3307
+ * published: true
3308
+ * })
3309
+ * ```
3310
+ */
3311
+ where(conditions) {
3312
+ this.queryParams.where = conditions;
3313
+ return this;
203
3314
  }
204
3315
  /**
205
- * Internal implementation used by findAll and eager relation hydration.
206
- * Pass `_hydrateRelations = false` to prevent recursive model hydration (depth guard).
3316
+ * Sets the order for the query results.
3317
+ *
3318
+ * @param orderBy - The ordering criteria
3319
+ * @returns The query builder for chaining
3320
+ *
3321
+ * @example
3322
+ * ```typescript
3323
+ * .order({ createdAt: "DESC" })
3324
+ * ```
207
3325
  */
208
- static async _findAllInternal(perspective, query = {}, _hydrateRelations = true) {
209
- return ops._findAllInternal(this, perspective, query, _hydrateRelations);
3326
+ order(orderBy) {
3327
+ this.queryParams.order = orderBy;
3328
+ return this;
210
3329
  }
211
3330
  /**
212
- * Returns all instances matching `query`.
3331
+ * Sets the maximum number of results to return.
3332
+ *
3333
+ * @param limit - Maximum number of results
3334
+ * @returns The query builder for chaining
213
3335
  *
214
3336
  * @example
215
3337
  * ```typescript
216
- * const recipes = await Recipe.findAll(perspective, {
217
- * where: { rating: { gt: 4 } }, order: { createdAt: "DESC" }, limit: 10,
218
- * });
3338
+ * .limit(10)
219
3339
  * ```
220
3340
  */
221
- static async findAll(perspective, query = {}) {
222
- return ops.findAll(this, perspective, query);
3341
+ limit(limit) {
3342
+ this.queryParams.limit = limit;
3343
+ return this;
223
3344
  }
224
3345
  /**
225
- * Returns the first matching instance, or `null` if none found.
3346
+ * Sets the number of results to skip.
3347
+ *
3348
+ * @param offset - Number of results to skip
3349
+ * @returns The query builder for chaining
226
3350
  *
227
3351
  * @example
228
3352
  * ```typescript
229
- * const post = await TestPost.findOne(perspective, { where: { id: someId } });
3353
+ * .offset(20) // Skip first 20 results
230
3354
  * ```
231
3355
  */
232
- static async findOne(perspective, query = {}) {
233
- return ops.findOne(this, perspective, query);
3356
+ offset(offset) {
3357
+ this.queryParams.offset = offset;
3358
+ return this;
234
3359
  }
235
3360
  /**
236
- * Like `findAll` but also returns the unfiltered total count (useful for pagination UI).
3361
+ * Scopes the query to instances linked from a parent.
3362
+ *
3363
+ * The predicate is resolved in order of precedence:
3364
+ * 1. **Instance only** — the parent's constructor is used as the model
3365
+ * class; its relation metadata is scanned for a relation whose
3366
+ * `target()` matches the queried model class.
3367
+ * 2. **Instance + options with `field`** — direct field-name lookup on
3368
+ * the parent model's relation metadata (disambiguates when a parent
3369
+ * has multiple relations targeting the same child class).
3370
+ * 3. **String id + model class** — same metadata scan (or field lookup if
3371
+ * options include `field`).
3372
+ * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
3373
+ *
3374
+ * Passing a plain string id with no second argument throws because the
3375
+ * predicate cannot be resolved without a model class.
3376
+ *
3377
+ * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
3378
+ * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
3379
+ * @param options - Optional settings: `field` for direct relation-name lookup
3380
+ * @returns The query builder for chaining
237
3381
  *
238
3382
  * @example
239
3383
  * ```typescript
240
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, { limit: 10 });
241
- * console.log(`Showing ${results.length} of ${totalCount}`);
3384
+ * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
3385
+ * Recipe.query(perspective).parent(cookbook).get();
3386
+ *
3387
+ * // Instance + field — disambiguate when parent has multiple relations to same child
3388
+ * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
3389
+ *
3390
+ * // String id + model class
3391
+ * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
3392
+ *
3393
+ * // String id + model class + field
3394
+ * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
3395
+ *
3396
+ * // String id + raw predicate (escape hatch)
3397
+ * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
242
3398
  * ```
243
3399
  */
244
- static async findAllAndCount(perspective, query = {}) {
245
- return ops.findAllAndCount(this, perspective, query);
3400
+ parent(idOrInstance, modelOrPredicate, options) {
3401
+ const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;
3402
+ // Handle options-object as second arg: parent(instance, { field: "recipes" })
3403
+ if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {
3404
+ if (typeof idOrInstance === 'string') {
3405
+ throw new Error('parent() called with a string id and options object requires a model class as second argument');
3406
+ }
3407
+ const model = idOrInstance.constructor;
3408
+ this.queryParams.parent = { id, model, field: modelOrPredicate.field };
3409
+ return this;
3410
+ }
3411
+ const field = options?.field;
3412
+ if (typeof modelOrPredicate === 'string') {
3413
+ // Raw predicate string → raw form of ParentScope
3414
+ this.queryParams.parent = { id, predicate: modelOrPredicate };
3415
+ }
3416
+ else if (typeof modelOrPredicate === 'function') {
3417
+ // Model class → model form of ParentScope
3418
+ this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };
3419
+ }
3420
+ else if (typeof idOrInstance !== 'string') {
3421
+ // Ad4mModel instance — derive model class from constructor
3422
+ this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };
3423
+ }
3424
+ else {
3425
+ throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');
3426
+ }
3427
+ return this;
246
3428
  }
247
3429
  /**
248
- * Fetches a single page of results (`pageNumber` is 1-based).
3430
+ * Specifies which properties to include in the results.
3431
+ *
3432
+ * @param properties - Array of property names to include
3433
+ * @returns The query builder for chaining
249
3434
  *
250
3435
  * @example
251
3436
  * ```typescript
252
- * const page = await Recipe.paginate(perspective, 10, 1);
253
- * console.log(`Page ${page.pageNumber}, ${page.results.length} items`);
3437
+ * .properties(["name", "description", "rating"])
254
3438
  * ```
255
3439
  */
256
- static async paginate(perspective, pageSize, pageNumber, query) {
257
- return ops.paginate(this, perspective, pageSize, pageNumber, query ?? {});
3440
+ properties(properties) {
3441
+ this.queryParams.properties = properties;
3442
+ return this;
258
3443
  }
259
3444
  /**
260
- * Generates a SurrealQL COUNT query for this model.
261
- * @private
3445
+ * Specifies which relations to eager-load (hydrate into model instances).
3446
+ *
3447
+ * Without `include`, relation fields contain raw expression URIs (strings).
3448
+ * With `include`, the URIs are resolved into fully-hydrated model instances
3449
+ * using the `target` class declared in the relation decorator.
3450
+ *
3451
+ * Supports nested includes for multi-level eager loading.
3452
+ *
3453
+ * @param map - An IncludeMap describing which relations to hydrate
3454
+ * @returns The query builder for chaining
3455
+ *
3456
+ * @example
3457
+ * ```typescript
3458
+ * // Hydrate comments one level deep
3459
+ * const recipes = await Recipe.query(perspective)
3460
+ * .include({ comments: true })
3461
+ * .run();
3462
+ * // recipe.comments is now Comment[] (model instances), not string[]
3463
+ *
3464
+ * // Nested: hydrate comments AND each comment's author
3465
+ * const recipes = await Recipe.query(perspective)
3466
+ * .include({ comments: { author: true } })
3467
+ * .run();
3468
+ * ```
262
3469
  */
263
- static async countQueryToSurrealQL(perspective, query) {
264
- return ops.countQueryToSurrealQL(this, perspective, query);
3470
+ include(map) {
3471
+ this.queryParams.include = map;
3472
+ return this;
265
3473
  }
266
- /** Returns the count of instances matching `query`. */
267
- static async count(perspective, query = {}) {
268
- return ops.count(this, perspective, query);
3474
+ overrideModelClassName(className) {
3475
+ this.modelClassName = className;
3476
+ return this;
269
3477
  }
270
3478
  /**
271
- * Persists the instance (create if new, update if existing).
3479
+ * Enables or disables SurrealDB query path.
272
3480
  *
273
- * @param batchId - When provided the caller must call `perspective.commitBatch(batchId)`
3481
+ * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
3482
+ * @returns The query builder for chaining
274
3483
  *
275
3484
  * @example
276
3485
  * ```typescript
277
- * const recipe = new Recipe(perspective);
278
- * recipe.name = "Spaghetti";
279
- * await recipe.save(); // create
280
- * recipe.name = "Bolognese";
281
- * await recipe.save(); // update (detected automatically)
3486
+ * // Use SurrealDB (default)
3487
+ * const recipes = await Recipe.query(perspective)
3488
+ * .where({ category: "Dessert" })
3489
+ * .useSurrealDB(true)
3490
+ * .get();
3491
+ *
3492
+ * // Use Prolog (legacy)
3493
+ * const recipesProlog = await Recipe.query(perspective)
3494
+ * .where({ category: "Dessert" })
3495
+ * .useSurrealDB(false)
3496
+ * .get();
282
3497
  * ```
3498
+ *
3499
+ * @remarks
3500
+ * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
3501
+ * if useSurrealDB(true) is set (default).
283
3502
  */
284
- async save(batchId) {
285
- await mutation.saveInstance(this._mutationContext(), batchId, this._savedOnce);
286
- this._savedOnce = true;
3503
+ useSurrealDB(enabled = true) {
3504
+ this.useSurrealDBFlag = enabled;
3505
+ return this;
287
3506
  }
288
3507
  /**
289
- * Gets the model instance with all properties and relations populated.
3508
+ * Executes the query once and returns the results.
290
3509
  *
291
- * @returns The populated model instance
292
- * @throws Will throw if data retrieval fails
3510
+ * @returns Array of matching entities
293
3511
  *
294
3512
  * @example
295
3513
  * ```typescript
296
- * const recipe = new Recipe(perspective, existingId);
297
- * await recipe.get();
298
- * console.log(recipe.name, recipe.ingredients);
3514
+ * const recipes = await Recipe.query(perspective)
3515
+ * .where({ category: "Dessert" })
3516
+ * .get();
299
3517
  * ```
300
3518
  */
301
- async get(include) {
302
- const metadata = this.constructor.getModelMetadata();
303
- return fetchInstanceData(this, this._perspective, this._id, metadata, include);
3519
+ async get() {
3520
+ let results;
3521
+ if (this.useSurrealDBFlag) {
3522
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3523
+ const result = await this.perspective.querySurrealDB(surrealQuery);
3524
+ ({ results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result));
3525
+ }
3526
+ else {
3527
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3528
+ const result = await this.perspective.infer(query);
3529
+ ({ results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result));
3530
+ }
3531
+ return results;
3532
+ }
3533
+ /**
3534
+ * Returns the first matching instance, or `null` if none match.
3535
+ *
3536
+ * Internally sets `limit: 1` and delegates to `get()`.
3537
+ *
3538
+ * @returns The first matching instance, or `null`
3539
+ *
3540
+ * @example
3541
+ * ```typescript
3542
+ * const recipe = await Recipe.query(perspective)
3543
+ * .where({ name: "Pasta" })
3544
+ * .first();
3545
+ * ```
3546
+ */
3547
+ async first() {
3548
+ this.queryParams.limit = 1;
3549
+ const results = await this.get();
3550
+ return results[0] ?? null;
304
3551
  }
305
3552
  /**
306
- * Removes this instance from the perspective, including all incoming links
307
- * that point to it (e.g. parent→child membership links created by
308
- * `create({ parent: ... })`). This ensures that `findAll({ parent: ... })`
309
- * will no longer return this instance after deletion.
3553
+ * Subscribes to the query and receives updates when results change.
3554
+ *
3555
+ * This method:
3556
+ * 1. Creates and initializes a SurrealDB live query subscription (default)
3557
+ * 2. Sets up the callback to process future updates
3558
+ * 3. Returns the initial results immediately
3559
+ *
3560
+ * Remember to call dispose() when you're done with the subscription
3561
+ * to clean up resources.
3562
+ *
3563
+ * @param callback - Function to call with updated results
3564
+ * @returns Initial results array
310
3565
  *
311
3566
  * @example
312
- * await vote.delete();
3567
+ * ```typescript
3568
+ * const builder = Recipe.query(perspective)
3569
+ * .where({ status: "cooking" });
3570
+ *
3571
+ * const initialRecipes = await builder.subscribe(recipes => {
3572
+ * console.log("Updated recipes:", recipes);
3573
+ * });
313
3574
  *
314
- * @param batchId - Optional batch identifier for grouping removals.
3575
+ * // When done with subscription:
3576
+ * builder.dispose();
3577
+ * ```
3578
+ *
3579
+ * @remarks
3580
+ * By default, this uses SurrealDB live queries for real-time updates.
3581
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
315
3582
  */
316
- async delete(batchId) {
317
- // Remove all incoming links that point to this instance so that parent
318
- // collections (parent queries) are kept consistent.
319
- const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._id }));
320
- for (const link of incomingLinks) {
321
- await this._perspective.remove(link);
3583
+ async subscribe(callback) {
3584
+ // Clean up any existing subscription
3585
+ this.dispose();
3586
+ const ctor = this.ctor;
3587
+ if (this.useSurrealDBFlag) {
3588
+ const surrealQuery = await ctor.queryToSurrealQL(this.perspective, this.queryParams);
3589
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3590
+ const processResults = async (result) => {
3591
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3592
+ callback(results);
3593
+ };
3594
+ this.currentSubscription.onResult(processResults);
3595
+ // Process initial result
3596
+ const { results } = await ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3597
+ // Also invoke callback with initial results so subscribers see them
3598
+ callback(results);
3599
+ return results;
3600
+ }
3601
+ else {
3602
+ const query = await ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
3603
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
3604
+ const processResults = async (result) => {
3605
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
3606
+ callback(results);
3607
+ };
3608
+ this.currentSubscription.onResult(processResults);
3609
+ const { results } = await ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
3610
+ // Also invoke callback with initial results so subscribers see them
3611
+ callback(results);
3612
+ return results;
322
3613
  }
323
- await this._perspective.removeSubject(this, this._id, batchId);
324
3614
  }
325
3615
  /**
326
- * Returns a fluent query builder for this model.
3616
+ * Gets the total count of matching entities.
3617
+ *
3618
+ * @returns Total count
327
3619
  *
328
3620
  * @example
329
3621
  * ```typescript
330
- * const top5 = await Recipe.query(perspective)
3622
+ * const totalDesserts = await Recipe.query(perspective)
331
3623
  * .where({ category: "Dessert" })
332
- * .order({ rating: "DESC" })
333
- * .limit(5)
334
- * .run();
3624
+ * .count();
335
3625
  * ```
336
3626
  */
337
- static query(perspective, query) {
338
- return new ModelQueryBuilder(perspective, this, query);
3627
+ async count() {
3628
+ if (this.useSurrealDBFlag) {
3629
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3630
+ const result = await this.perspective.querySurrealDB(surrealQuery);
3631
+ // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
3632
+ // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
3633
+ // This ensures count() returns the same number as get().length
3634
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3635
+ return totalCount;
3636
+ }
3637
+ else {
3638
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3639
+ const result = await this.perspective.infer(query);
3640
+ return result?.[0]?.TotalCount || 0;
3641
+ }
339
3642
  }
340
3643
  /**
341
- * Runs `callback` in an atomic batch; commits on success, aborts + rethrows on failure.
3644
+ * Subscribes to count updates for matching entities.
3645
+ *
3646
+ * This method:
3647
+ * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
3648
+ * 2. Sets up the callback to process future count updates
3649
+ * 3. Returns the initial count immediately
3650
+ *
3651
+ * Remember to call dispose() when you're done with the subscription
3652
+ * to clean up resources.
3653
+ *
3654
+ * @param callback - Function to call with updated count
3655
+ * @returns Initial count
342
3656
  *
343
3657
  * @example
344
3658
  * ```typescript
345
- * await Ad4mModel.transaction(perspective, async (tx) => {
346
- * await post.save(tx.batchId);
347
- * await comment.save(tx.batchId);
3659
+ * const builder = Recipe.query(perspective)
3660
+ * .where({ status: "active" });
3661
+ *
3662
+ * const initialCount = await builder.countSubscribe(count => {
3663
+ * console.log("Active items:", count);
348
3664
  * });
3665
+ *
3666
+ * // When done with subscription:
3667
+ * builder.dispose();
349
3668
  * ```
3669
+ *
3670
+ * @remarks
3671
+ * By default, this uses SurrealDB live queries for real-time updates.
3672
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
350
3673
  */
351
- static async transaction(perspective, callback) {
352
- return runTransaction(perspective, callback);
3674
+ async countSubscribe(callback) {
3675
+ // Clean up any existing subscription
3676
+ this.dispose();
3677
+ if (this.useSurrealDBFlag) {
3678
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
3679
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3680
+ const processResults = async (result) => {
3681
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
3682
+ callback(totalCount);
3683
+ };
3684
+ this.currentSubscription.onResult(processResults);
3685
+ const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
3686
+ callback(totalCount);
3687
+ return totalCount;
3688
+ }
3689
+ else {
3690
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
3691
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
3692
+ const processResults = async (result) => {
3693
+ const newCount = result?.[0]?.TotalCount || 0;
3694
+ callback(newCount);
3695
+ };
3696
+ this.currentSubscription.onResult(processResults);
3697
+ const initialCount = this.currentSubscription.result?.[0]?.TotalCount || 0;
3698
+ callback(initialCount);
3699
+ return initialCount;
3700
+ }
353
3701
  }
354
3702
  /**
355
- * Fires `callback` immediately with current results, then on every relevant perspective change.
3703
+ * Gets a page of results with pagination metadata.
356
3704
  *
357
- * @param options - Query params plus optional `debounce` (ms) and `onError` handler
358
- * @param callback - Receives the fresh result set on each delivery
359
- * @returns `Subscription` with `unsubscribe()` — call it in cleanup to avoid leaks
3705
+ * @param pageSize - Number of items per page
3706
+ * @param pageNumber - Which page to retrieve (1-based)
3707
+ * @returns Paginated results with metadata
360
3708
  *
361
3709
  * @example
362
3710
  * ```typescript
363
- * const sub = Post.subscribe(
364
- * perspective,
365
- * { where: { published: true }, debounce: 300 },
366
- * (posts) => setPosts(posts),
367
- * );
368
- * sub.unsubscribe(); // in cleanup
3711
+ * const page = await Recipe.query(perspective)
3712
+ * .where({ category: "Main" })
3713
+ * .paginate(10, 1);
3714
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
369
3715
  * ```
370
3716
  */
371
- static subscribe(perspective, options, callback) {
372
- return createSubscription((p, q) => this.findAll(p, q ?? {}), () => this.getModelMetadata(), perspective, options, callback, this);
3717
+ async paginate(pageSize, pageNumber) {
3718
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3719
+ if (this.useSurrealDBFlag) {
3720
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3721
+ const result = await this.perspective.querySurrealDB(surrealQuery);
3722
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3723
+ return { results, totalCount, pageSize, pageNumber };
3724
+ }
3725
+ else {
3726
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3727
+ const result = await this.perspective.infer(prologQuery);
3728
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
3729
+ return { results, totalCount, pageSize, pageNumber };
3730
+ }
373
3731
  }
374
3732
  /**
375
- * Generates an `Ad4mModel` subclass from a JSON Schema definition.
3733
+ * Subscribes to paginated results updates.
3734
+ *
3735
+ * This method:
3736
+ * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
3737
+ * 2. Sets up the callback to process future page updates
3738
+ * 3. Returns the initial page immediately
376
3739
  *
377
- * Predicate resolution order: explicit options → `x-ad4m` in schema → inferred from title/names.
3740
+ * Remember to call dispose() when you're done with the subscription
3741
+ * to clean up resources.
3742
+ *
3743
+ * @param pageSize - Number of items per page
3744
+ * @param pageNumber - Which page to retrieve (1-based)
3745
+ * @param callback - Function to call with updated pagination results
3746
+ * @returns Initial pagination results
378
3747
  *
379
3748
  * @example
380
3749
  * ```typescript
381
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
382
- * name: "Person", namespace: "person://", resolveLanguage: "literal",
3750
+ * const builder = Recipe.query(perspective)
3751
+ * .where({ category: "Main" });
3752
+ *
3753
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
3754
+ * console.log("Updated page:", page.results);
383
3755
  * });
3756
+ *
3757
+ * // When done with subscription:
3758
+ * builder.dispose();
384
3759
  * ```
3760
+ *
3761
+ * @remarks
3762
+ * By default, this uses SurrealDB live queries for real-time updates.
3763
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
385
3764
  */
386
- static fromJSONSchema(schema, options) {
387
- return createModelFromJSONSchema(this, schema, options);
3765
+ async paginateSubscribe(pageSize, pageNumber, callback) {
3766
+ // Clean up any existing subscription
3767
+ this.dispose();
3768
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
3769
+ if (this.useSurrealDBFlag) {
3770
+ const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
3771
+ this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
3772
+ const processResults = async (result) => {
3773
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
3774
+ callback({ results, totalCount, pageSize, pageNumber });
3775
+ };
3776
+ this.currentSubscription.onResult(processResults);
3777
+ const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
3778
+ const initialPage = { results, totalCount, pageSize, pageNumber };
3779
+ callback(initialPage);
3780
+ return initialPage;
3781
+ }
3782
+ else {
3783
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
3784
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
3785
+ const processResults = async (r) => {
3786
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
3787
+ callback({ results, totalCount, pageSize, pageNumber });
3788
+ };
3789
+ this.currentSubscription.onResult(processResults);
3790
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
3791
+ const initialPrologPage = { results, totalCount, pageSize, pageNumber };
3792
+ callback(initialPrologPage);
3793
+ return initialPrologPage;
3794
+ }
388
3795
  }
389
3796
  }
390
- Ad4mModel.classNamesByClass = new WeakMap();
3797
+ // ── Standalone Prolog fact generator ──────────────────────────────────────────
3798
+ /**
3799
+ * Convert a camelCase or PascalCase identifier to snake_case.
3800
+ * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
3801
+ */
3802
+ function toSnakeCase(str) {
3803
+ return str
3804
+ .replace(/([A-Z])/g, "_$1")
3805
+ .toLowerCase()
3806
+ .replace(/^_/, "");
3807
+ }
3808
+ function buildInstanceClause(predicateName, metadata) {
3809
+ const props = metadata.properties;
3810
+ // Collect flags first — these are the strongest recognizers
3811
+ const flags = Object.values(props).filter((p) => p.flag && p.predicate && p.initial);
3812
+ if (flags.length > 0) {
3813
+ const conditions = flags
3814
+ .map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
3815
+ .join(",\n ");
3816
+ return `${predicateName}(X) :-\n ${conditions}.`;
3817
+ }
3818
+ // Fallback: required non-flag properties
3819
+ const required = Object.values(props).filter((p) => p.required && p.predicate && !p.flag);
3820
+ if (required.length > 0) {
3821
+ const conditions = required
3822
+ .map((p) => `triple(X, '${p.predicate}', _)`)
3823
+ .join(",\n ");
3824
+ return `${predicateName}(X) :-\n ${conditions}.`;
3825
+ }
3826
+ // Open-world structural fallback: match nodes that have at least one of the
3827
+ // model's declared property predicates. Uses disjunction (;) so any single
3828
+ // predicate is enough.
3829
+ const allPredicates = Object.values(props)
3830
+ .filter((p) => p.predicate)
3831
+ .map((p) => p.predicate);
3832
+ if (metadata.relations) {
3833
+ for (const rel of Object.values(metadata.relations)) {
3834
+ if (rel.predicate)
3835
+ allPredicates.push(rel.predicate);
3836
+ }
3837
+ }
3838
+ if (allPredicates.length > 0) {
3839
+ const disjunction = allPredicates
3840
+ .map((pred) => `triple(X, '${pred}', _)`)
3841
+ .join(" ;\n ");
3842
+ return `${predicateName}(X) :-\n (${disjunction}).`;
3843
+ }
3844
+ return null;
3845
+ }
3846
+ function buildPropertyClause(modelPredicateName, prop) {
3847
+ if (prop.flag)
3848
+ return null;
3849
+ if (!prop.predicate)
3850
+ return null;
3851
+ const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
3852
+ return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
3853
+ }
3854
+ function buildRelationClause(modelPredicateName, relation) {
3855
+ if (!relation.predicate)
3856
+ return null;
3857
+ const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
3858
+ if (relation.direction === "reverse") {
3859
+ return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
3860
+ }
3861
+ return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
3862
+ }
3863
+ /**
3864
+ * Generate Prolog predicate facts from a model class's decorator metadata.
3865
+ *
3866
+ * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
3867
+ * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
3868
+ * Prolog clauses that can be prepended to any `perspective.infer()` call.
3869
+ *
3870
+ * The generated predicates are:
3871
+ * - **Instance recognizer** — `modelName(X)` — matches instances of the model
3872
+ * - **Property getters** — `modelName_propName(X, Value)` — one per property
3873
+ * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
3874
+ *
3875
+ * @example
3876
+ * ```typescript
3877
+ * import { generatePrologFacts } from '@coasys/ad4m';
3878
+ *
3879
+ * const facts = generatePrologFacts(Poll);
3880
+ * const result = await perspective.infer(\`
3881
+ * \${facts}
3882
+ * recent_popular_poll(X) :-
3883
+ * poll(X),
3884
+ * poll_vote_count(X, N), N > 10.
3885
+ * \`);
3886
+ * ```
3887
+ *
3888
+ * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
3889
+ * @returns A multi-line Prolog string ready for use with `perspective.infer()`
3890
+ */
3891
+ export function generatePrologFacts(ModelClass) {
3892
+ const metadata = ModelClass.getModelMetadata();
3893
+ const predicateName = toSnakeCase(metadata.className);
3894
+ const lines = [];
3895
+ lines.push(`% ${metadata.className} — generated Prolog facts`);
3896
+ // Instance recognizer
3897
+ const instanceClause = buildInstanceClause(predicateName, metadata);
3898
+ if (instanceClause) {
3899
+ lines.push("");
3900
+ lines.push(`% Instance recognizer`);
3901
+ lines.push(instanceClause);
3902
+ }
3903
+ // Property getters
3904
+ const propClauses = Object.values(metadata.properties)
3905
+ .map((p) => buildPropertyClause(predicateName, p))
3906
+ .filter((c) => c !== null);
3907
+ if (propClauses.length > 0) {
3908
+ lines.push("");
3909
+ lines.push(`% Field getters`);
3910
+ lines.push(...propClauses);
3911
+ }
3912
+ // Relation getters
3913
+ const relClauses = Object.values(metadata.relations)
3914
+ .map((c) => buildRelationClause(predicateName, c))
3915
+ .filter((c) => c !== null);
3916
+ if (relClauses.length > 0) {
3917
+ lines.push("");
3918
+ lines.push(`% Relation getters`);
3919
+ lines.push(...relClauses);
3920
+ }
3921
+ return lines.join("\n");
3922
+ }