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

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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6046
  3. package/lib/index.js +5977 -6040
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2799
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3249
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -1,289 +1,38 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _Ad4mModel_baseExpression, _Ad4mModel_subjectClassName, _Ad4mModel_source, _Ad4mModel_perspective;
13
1
  import { Literal } from "../Literal";
14
2
  import { Link } from "../links/Links";
15
- import { makeRandomPrologAtom, ModelOptions } from "./decorators";
16
- import { propertyNameToSetterName } from "./util";
17
- import { escapeSurrealString } from "../utils";
18
- function capitalize(word) {
19
- return word.charAt(0).toUpperCase() + word.slice(1);
20
- }
21
- function buildSourceQuery(source) {
22
- // Constrains the query to instances that have the provided source
23
- if (!source)
24
- return "";
25
- return `triple("${source}", "ad4m://has_child", Base)`;
26
- }
27
- // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
28
- function buildAuthorAndTimestampQuery() {
29
- // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
30
- return `
31
- findall(
32
- [T, A],
33
- link(Base, _, _, T, A),
34
- AllLinks
35
- ),
36
- sort(AllLinks, SortedLinks),
37
- SortedLinks = [[Timestamp, Author]|_]
38
- `;
39
- }
40
- function buildPropertiesQuery(properties) {
41
- // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
42
- // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
43
- // an Expression in JSON literal, or the direct literal value if it is a simple literal
44
- // If no properties are provided, all are included
45
- return `
46
- findall([PropertyName, PropertyValue, Resolve], (
47
- % Constrain to specified properties if provided
48
- ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
49
- resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
50
- ), Properties)
51
- `;
52
- }
53
- function buildCollectionsQuery(collections) {
54
- // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
55
- // If no collections are provided, all are included
56
- return `
57
- findall([CollectionName, CollectionValues], (
58
- % Constrain to specified collections if provided
59
- ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
60
-
61
- collection(SubjectClass, CollectionName),
62
- collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
63
- ), Collections)
64
- `;
65
- }
66
- function buildWhereQuery(where = {}) {
67
- // Constrains the query to instances that match the provided where conditions
68
- function formatValue(value) {
69
- // Wrap strings in quotes
70
- return typeof value === "string" ? `"${value}"` : value;
71
- }
72
- return Object.entries(where)
73
- .map(([key, value]) => {
74
- const isSpecial = ["base", "author", "timestamp"].includes(key);
75
- const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
76
- // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
77
- const field = capitalize(key);
78
- // Handle direct array values (for IN conditions)
79
- if (Array.isArray(value)) {
80
- const formattedValues = value.map((v) => formatValue(v)).join(", ");
81
- if (isSpecial)
82
- return `member(${field}, [${formattedValues}])`;
83
- else
84
- return `${getter}, member(Value${key}, [${formattedValues}])`;
85
- }
86
- // Handle operation object
87
- if (typeof value === "object" && value !== null) {
88
- const { not, between, lt, lte, gt, gte } = value;
89
- // Handle NOT operation
90
- if (not !== undefined) {
91
- if (Array.isArray(not)) {
92
- // NOT IN array
93
- const formattedValues = not.map((v) => formatValue(v)).join(", ");
94
- if (isSpecial)
95
- return `\\+ member(${field}, [${formattedValues}])`;
96
- else
97
- return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
98
- }
99
- else {
100
- // NOT EQUAL
101
- if (isSpecial)
102
- return `${field} \\= ${formatValue(not)}`;
103
- else
104
- return `${getter}, Value${key} \\= ${formatValue(not)}`;
105
- }
106
- }
107
- // Handle BETWEEN
108
- if (between !== undefined && Array.isArray(between) && between.length === 2) {
109
- if (isSpecial)
110
- return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
111
- else
112
- return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
113
- }
114
- // Handle lt, lte, gt, & gte operations
115
- const operators = [
116
- { value: lt, symbol: "<" },
117
- { value: lte, symbol: "=<" },
118
- { value: gt, symbol: ">" },
119
- { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
120
- ];
121
- for (const { value, symbol } of operators) {
122
- if (value !== undefined)
123
- return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
124
- }
125
- }
126
- // Default to direct equality
127
- if (isSpecial)
128
- return `${field} = ${formatValue(value)}`;
129
- else
130
- return `${getter}, Value${key} = ${formatValue(value)}`;
131
- })
132
- .join(", ");
133
- }
134
- function buildCountQuery(count) {
135
- return count ? "length(UnsortedInstances, TotalCount)" : "";
136
- }
137
- function buildOrderQuery(order) {
138
- if (!order)
139
- return "SortedInstances = UnsortedInstances";
140
- const [propertyName, direction] = Object.entries(order)[0];
141
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
142
- }
143
- function buildOffsetQuery(offset) {
144
- if (!offset || offset < 0)
145
- return "InstancesWithOffset = SortedInstances";
146
- return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
147
- }
148
- function buildLimitQuery(limit) {
149
- if (!limit || limit < 0)
150
- return "AllInstances = InstancesWithOffset";
151
- return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
152
- }
153
- function normalizeNamespaceString(namespace) {
154
- if (!namespace)
155
- return '';
156
- if (namespace.includes('://')) {
157
- const [scheme, rest] = namespace.split('://');
158
- const path = (rest || '').replace(/\/+$/, '');
159
- return `${scheme}://${path}`;
160
- }
161
- else {
162
- return namespace.replace(/\/+$/, '');
163
- }
164
- }
165
- function normalizeSchemaType(type) {
166
- if (!type)
167
- return undefined;
168
- if (typeof type === "string")
169
- return type;
170
- if (Array.isArray(type) && type.length > 0) {
171
- const nonNull = type.find((t) => t !== "null");
172
- return nonNull || type[0];
173
- }
174
- return undefined;
175
- }
176
- function isSchemaType(schema, expectedType) {
177
- return normalizeSchemaType(schema.type) === expectedType;
178
- }
179
- function isArrayType(schema) {
180
- return isSchemaType(schema, "array");
181
- }
182
- function isObjectType(schema) {
183
- return isSchemaType(schema, "object");
184
- }
185
- function isNumericType(schema) {
186
- const normalized = normalizeSchemaType(schema.type);
187
- return normalized === "number" || normalized === "integer";
188
- }
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";
189
27
  /**
190
- * Base class for defining data models in AD4M.
191
- *
192
- * @description
193
- * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
194
- * Each model instance is represented as a subgraph in the perspective, with properties and collections
195
- * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
196
- * instances based on their properties and relationships.
197
- *
198
- * Key concepts:
199
- * - Each model instance has a unique base expression that serves as its identifier
200
- * - Properties are stored as links with predicates defined by the `through` option
201
- * - Collections represent one-to-many relationships as sets of links
202
- * - Queries are translated to Prolog for efficient graph pattern matching
203
- * - Changes are tracked through the perspective's subscription system
204
- *
205
- * @example
206
- * ```typescript
207
- * // Define a recipe model
208
- * @ModelOptions({ name: "Recipe" })
209
- * class Recipe extends Ad4mModel {
210
- * // Required property with literal value
211
- * @Property({
212
- * through: "recipe://name",
213
- * resolveLanguage: "literal"
214
- * })
215
- * name: string = "";
216
- *
217
- * // Optional property with custom initial value
218
- * @Optional({
219
- * through: "recipe://status",
220
- * initial: "recipe://draft"
221
- * })
222
- * status: string = "";
28
+ * Base class for all AD4M data models.
223
29
  *
224
- * // Read-only computed property
225
- * @ReadOnly({
226
- * through: "recipe://rating",
227
- * getter: `
228
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
229
- * sum_list(Ratings, Sum),
230
- * length(Ratings, Count),
231
- * Value is Sum / Count
232
- * `
233
- * })
234
- * averageRating: number = 0;
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.
235
34
  *
236
- * // Collection of ingredients
237
- * @Collection({ through: "recipe://ingredient" })
238
- * ingredients: string[] = [];
239
- *
240
- * // Collection of comments that are instances of another model
241
- * @Collection({
242
- * through: "recipe://comment",
243
- * where: { isInstance: Comment }
244
- * })
245
- * comments: Comment[] = [];
246
- * }
247
- *
248
- * // Create and save a new recipe
249
- * const recipe = new Recipe(perspective);
250
- * recipe.name = "Chocolate Cake";
251
- * recipe.ingredients = ["flour", "sugar", "cocoa"];
252
- * await recipe.save();
253
- *
254
- * // Query recipes in different ways
255
- * // Get all recipes
256
- * const allRecipes = await Recipe.findAll(perspective);
257
- *
258
- * // Find recipes with specific criteria
259
- * const desserts = await Recipe.findAll(perspective, {
260
- * where: {
261
- * status: "recipe://published",
262
- * averageRating: { gt: 4 }
263
- * },
264
- * order: { name: "ASC" },
265
- * limit: 10
266
- * });
267
- *
268
- * // Use the fluent query builder
269
- * const popularRecipes = await Recipe.query(perspective)
270
- * .where({ averageRating: { gt: 4.5 } })
271
- * .order({ averageRating: "DESC" })
272
- * .limit(5)
273
- * .get();
274
- *
275
- * // Subscribe to real-time updates
276
- * await Recipe.query(perspective)
277
- * .where({ status: "recipe://cooking" })
278
- * .subscribe(recipes => {
279
- * console.log("Currently being cooked:", recipes);
280
- * });
281
- *
282
- * // Paginate results
283
- * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
284
- * .where({ status: "recipe://published" })
285
- * .paginate(10, 1);
286
- * ```
35
+ * See [README.md](./README.md) for a full worked example and decorator reference.
287
36
  */
288
37
  export class Ad4mModel {
289
38
  static async getClassName(perspective) {
@@ -302,7 +51,8 @@ export class Ad4mModel {
302
51
  // Get or create the cached name for this perspective
303
52
  const perspectiveID = perspective.uuid;
304
53
  if (!classCache[perspectiveID]) {
305
- classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
54
+ classCache[perspectiveID] =
55
+ await perspective.stringOrTemplateObjectToSubjectClassName(this);
306
56
  }
307
57
  return classCache[perspectiveID];
308
58
  }
@@ -313,1838 +63,230 @@ export class Ad4mModel {
313
63
  get timestamp() {
314
64
  return this.createdAt;
315
65
  }
316
- /**
317
- * Extracts metadata from decorators for query building.
318
- *
319
- * @description
320
- * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
321
- * and returns it in a structured format that's easier to work with for query builders
322
- * and other systems that need to introspect model structure.
323
- *
324
- * The metadata includes:
325
- * - Class name from @ModelOptions
326
- * - Property metadata (predicates, types, constraints, etc.)
327
- * - Collection metadata (predicates, filters, etc.)
328
- *
329
- * For models created via `fromJSONSchema()`, this method will derive metadata from
330
- * the stored `__properties` and `__collections` structures that were populated during
331
- * the dynamic class creation. If these structures are empty but a JSON schema was
332
- * attached to the class, it can fall back to deriving metadata from that schema.
333
- *
334
- * @returns Structured metadata object containing className, properties, and collections
335
- * @throws Error if the class doesn't have @ModelOptions decorator
336
- *
337
- * @example
338
- * ```typescript
339
- * @ModelOptions({ name: "Recipe" })
340
- * class Recipe extends Ad4mModel {
341
- * @Property({ through: "recipe://name", resolveLanguage: "literal" })
342
- * name: string = "";
343
- *
344
- * @Collection({ through: "recipe://ingredient" })
345
- * ingredients: string[] = [];
346
- * }
347
- *
348
- * const metadata = Recipe.getModelMetadata();
349
- * console.log(metadata.className); // "Recipe"
350
- * console.log(metadata.properties.name.predicate); // "recipe://name"
351
- * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
352
- * ```
353
- */
66
+ /** Returns the class name, property predicates, and relation predicates from decorators. */
354
67
  static getModelMetadata() {
355
- // Access the prototype with any type to access decorator-added properties
356
- const prototype = this.prototype;
357
- // Validate that the class has @ModelOptions decorator
358
- // The decorator sets prototype.className, so we check for its existence
359
- if (!prototype.className || prototype.className === 'Ad4mModel') {
360
- throw new Error("Model class must be decorated with @ModelOptions");
361
- }
362
- // Extract className
363
- const className = prototype.className;
364
- // Extract properties from prototype.__properties
365
- const propertiesMetadata = {};
366
- const prototypeProperties = prototype.__properties || {};
367
- for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
368
- const options = opts;
369
- propertiesMetadata[propertyName] = {
370
- name: propertyName,
371
- predicate: options.through || "",
372
- required: options.required || false,
373
- writable: options.writable || false,
374
- ...(options.initial !== undefined && { initial: options.initial }),
375
- ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),
376
- ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),
377
- ...(options.getter !== undefined && { getter: options.getter }),
378
- ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
379
- ...(options.local !== undefined && { local: options.local }),
380
- ...(options.transform !== undefined && { transform: options.transform }),
381
- ...(options.flag !== undefined && { flag: options.flag })
382
- };
383
- }
384
- // Extract collections from prototype.__collections
385
- const collectionsMetadata = {};
386
- const prototypeCollections = prototype.__collections || {};
387
- for (const [collectionName, opts] of Object.entries(prototypeCollections)) {
388
- const options = opts;
389
- collectionsMetadata[collectionName] = {
390
- name: collectionName,
391
- predicate: options.through || "",
392
- ...(options.where !== undefined && { where: options.where }),
393
- ...(options.local !== undefined && { local: options.local }),
394
- ...(options.getter !== undefined && { getter: options.getter })
395
- };
396
- }
397
- // Fallback: If both structures are empty but a JSON schema is attached, derive from it
398
- // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated
399
- const hasProperties = Object.keys(propertiesMetadata).length > 0;
400
- const hasCollections = Object.keys(collectionsMetadata).length > 0;
401
- const hasMetadata = hasProperties || hasCollections;
402
- if (!hasMetadata && prototype.__jsonSchema) {
403
- // Derive metadata from the attached JSON schema
404
- const schema = prototype.__jsonSchema;
405
- const options = prototype.__jsonSchemaOptions || {};
406
- if (schema.properties) {
407
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
408
- const isArray = isArrayType(propertySchema);
409
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, this.determineNamespace(schema, options), options);
410
- if (isArray) {
411
- collectionsMetadata[propertyName] = {
412
- name: propertyName,
413
- predicate: predicate,
414
- ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
415
- };
416
- }
417
- else {
418
- const isRequired = schema.required?.includes(propertyName) || false;
419
- propertiesMetadata[propertyName] = {
420
- name: propertyName,
421
- predicate: predicate,
422
- required: isRequired,
423
- writable: propertySchema["x-ad4m"]?.writable !== false,
424
- ...(propertySchema["x-ad4m"]?.resolveLanguage && { resolveLanguage: propertySchema["x-ad4m"].resolveLanguage }),
425
- ...(propertySchema["x-ad4m"]?.initial && { initial: propertySchema["x-ad4m"].initial }),
426
- ...(propertySchema["x-ad4m"]?.local !== undefined && { local: propertySchema["x-ad4m"].local })
427
- };
428
- }
429
- }
430
- }
431
- }
432
- return {
433
- className,
434
- properties: propertiesMetadata,
435
- collections: collectionsMetadata
436
- };
68
+ return _getModelMetadata(this);
437
69
  }
438
70
  /**
439
- * Constructs a new model instance.
440
- *
441
- * @param perspective - The perspective where this model will be stored
442
- * @param baseExpression - Optional unique identifier for this instance
443
- * @param source - Optional source expression this instance is linked to
71
+ * Installs the SHACL/SDNA subject class in `perspective` (idempotent).
444
72
  *
445
- * @example
446
- * ```typescript
447
- * // Create a new recipe with auto-generated base expression
448
- * const recipe = new Recipe(perspective);
449
- *
450
- * // Create with specific base expression
451
- * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
452
- *
453
- * // Create with source link
454
- * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
455
- * ```
456
- */
457
- constructor(perspective, baseExpression, source) {
458
- _Ad4mModel_baseExpression.set(this, void 0);
459
- _Ad4mModel_subjectClassName.set(this, void 0);
460
- _Ad4mModel_source.set(this, void 0);
461
- _Ad4mModel_perspective.set(this, void 0);
462
- __classPrivateFieldSet(this, _Ad4mModel_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
463
- __classPrivateFieldSet(this, _Ad4mModel_perspective, perspective, "f");
464
- __classPrivateFieldSet(this, _Ad4mModel_source, source || "ad4m://self", "f");
465
- }
466
- /**
467
- * Gets the base expression of the subject.
468
- */
469
- get baseExpression() {
470
- return __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f");
471
- }
472
- /**
473
- * Protected getter for the perspective.
474
- * Allows subclasses to access the perspective while keeping it private from external code.
475
- */
476
- get perspective() {
477
- return __classPrivateFieldGet(this, _Ad4mModel_perspective, "f");
478
- }
479
- /**
480
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
481
- * @private
482
- */
483
- getPropertyMetadata(key) {
484
- const proto = Object.getPrototypeOf(this);
485
- return proto.__properties?.[key];
486
- }
487
- /**
488
- * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
489
- * @private
490
- */
491
- getCollectionMetadata(key) {
492
- const proto = Object.getPrototypeOf(this);
493
- return proto.__collections?.[key];
494
- }
495
- /**
496
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
497
- * Replaces Prolog query: property_setter(C, key, Setter)
498
- * @private
499
- */
500
- generatePropertySetterAction(key, metadata) {
501
- // Check if property is read-only
502
- if (metadata.writable === false) {
503
- throw new Error(`Property "${key}" is read-only and cannot be written`);
504
- }
505
- if (metadata.prologSetter) {
506
- // Custom Prolog setter - throw error for now (Phase 2)
507
- throw new Error(`Custom Prolog setter for property "${key}" not yet supported without Prolog. ` +
508
- `Use standard @Property decorator or enable Prolog for custom setters.`);
509
- }
510
- if (!metadata.through) {
511
- throw new Error(`Property "${key}" has no 'through' predicate defined`);
512
- }
513
- return [{
514
- action: "setSingleTarget",
515
- source: "this",
516
- predicate: metadata.through,
517
- target: "value",
518
- ...(metadata.local && { local: true })
519
- }];
520
- }
521
- /**
522
- * Generate collection action from metadata (Phase 1: Prolog-free refactor)
523
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
524
- * @private
525
- */
526
- generateCollectionAction(key, actionType) {
527
- const metadata = this.getCollectionMetadata(key);
528
- if (!metadata) {
529
- throw new Error(`Collection "${key}" has no metadata defined`);
530
- }
531
- if (!metadata.through) {
532
- throw new Error(`Collection "${key}" has no 'through' predicate defined`);
533
- }
534
- const actionMap = {
535
- adder: "addLink",
536
- remover: "removeLink",
537
- setter: "collectionSetter"
538
- };
539
- return [{
540
- action: actionMap[actionType],
541
- source: "this",
542
- predicate: metadata.through,
543
- target: "value",
544
- ...(metadata.local && { local: true })
545
- }];
546
- }
547
- static async assignValuesToInstance(perspective, instance, values) {
548
- // Map properties to object
549
- const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
550
- let finalValue = value;
551
- // Handle UTF-8 byte sequences from Prolog URL decoding
552
- if (!resolve && typeof value === 'string') {
553
- // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
554
- // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
555
- const codePoints = Array.from(value, ch => ch.codePointAt(0));
556
- const looksByteString = codePoints.every(cp => cp <= 0xFF);
557
- const hasHighByte = codePoints.some(cp => cp >= 0x80);
558
- if (looksByteString && hasHighByte) {
559
- try {
560
- const bytes = Uint8Array.from(codePoints);
561
- const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
562
- if (decoded !== value)
563
- finalValue = decoded;
564
- }
565
- catch (error) {
566
- // If UTF-8 conversion fails, keep the original value
567
- console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
568
- }
569
- }
570
- }
571
- // Resolve the value if necessary
572
- if (resolve) {
573
- let resolvedExpression = await perspective.getExpression(value);
574
- if (resolvedExpression) {
575
- try {
576
- // Attempt to parse the data as JSON
577
- finalValue = JSON.parse(resolvedExpression.data);
578
- }
579
- catch (error) {
580
- // If parsing fails, keep the original data
581
- finalValue = resolvedExpression.data;
582
- }
583
- }
584
- }
585
- // Apply transform function if it exists
586
- const transform = instance["__properties"]?.[name]?.transform;
587
- if (transform && typeof transform === "function") {
588
- finalValue = transform(finalValue);
589
- }
590
- return [name, finalValue];
591
- })));
592
- // Filter out properties that are read-only (getters without setters)
593
- const writableProps = Object.fromEntries(Object.entries(propsObject).filter(([key]) => {
594
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key);
595
- if (!descriptor) {
596
- // No descriptor means it's a regular property on the instance, allow it
597
- return true;
598
- }
599
- // Check if it's an accessor descriptor (has get/set) vs data descriptor (has value/writable)
600
- const isAccessor = descriptor.get !== undefined || descriptor.set !== undefined;
601
- if (isAccessor) {
602
- // Accessor descriptor: only allow if it has a setter
603
- return descriptor.set !== undefined;
604
- }
605
- else {
606
- // Data descriptor: only allow if writable is not explicitly false
607
- return descriptor.writable !== false;
608
- }
609
- }));
610
- // Assign properties to instance
611
- Object.assign(instance, writableProps);
612
- }
613
- async getData() {
614
- // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
615
- // Use SurrealDB for data queries
616
- try {
617
- const ctor = this.constructor;
618
- const metadata = ctor.getModelMetadata();
619
- // Query for all links from this specific node (base expression)
620
- // Using formatSurrealValue to prevent SQL injection by properly escaping the value
621
- const safeBaseExpression = ctor.formatSurrealValue(__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"));
622
- // Note: We use ORDER BY timestamp ASC because:
623
- // - For collections: we want chronological order (oldest to newest)
624
- // - For properties: we select the LAST element to get "latest wins" semantics
625
- const linksQuery = `
626
- SELECT id, predicate, out.uri AS target, author, timestamp
627
- FROM link
628
- WHERE in.uri = ${safeBaseExpression}
629
- ORDER BY timestamp ASC
630
- `;
631
- const links = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(linksQuery);
632
- if (links && links.length > 0) {
633
- let minTimestamp = null;
634
- let maxTimestamp = null;
635
- let latestAuthor = null;
636
- let originalAuthor = null;
637
- // Process properties (skip those with custom getter)
638
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
639
- if (propMeta.getter)
640
- continue; // Handle via custom getter evaluation
641
- const matching = links.filter((l) => l.predicate === propMeta.predicate);
642
- if (matching.length > 0) {
643
- // "Latest wins" semantics: select the last element since links are ordered ASC.
644
- // The last element has the most recent timestamp and represents the current property value.
645
- const link = matching[matching.length - 1];
646
- let value = link.target;
647
- // Track timestamps/authors for createdAt and updatedAt
648
- if (link.timestamp) {
649
- if (!minTimestamp || link.timestamp < minTimestamp) {
650
- minTimestamp = link.timestamp;
651
- originalAuthor = link.author;
652
- }
653
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
654
- maxTimestamp = link.timestamp;
655
- latestAuthor = link.author;
656
- }
657
- }
658
- // Handle resolveLanguage
659
- if (propMeta.resolveLanguage && propMeta.resolveLanguage !== 'literal') {
660
- try {
661
- const expression = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getExpression(value);
662
- if (expression) {
663
- try {
664
- value = JSON.parse(expression.data);
665
- }
666
- catch {
667
- value = expression.data;
668
- }
669
- }
670
- }
671
- catch (e) {
672
- console.warn(`Failed to resolve expression for ${propName}:`, e);
673
- }
674
- }
675
- else if (propMeta.resolveLanguage === 'literal' && typeof value === 'string' && value.startsWith('literal://')) {
676
- // Only parse literal URIs when resolveLanguage is explicitly 'literal'.
677
- // Without this guard, properties pointing to baseExpressions of other models
678
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
679
- try {
680
- const parsed = Literal.fromUrl(value).get();
681
- value = parsed.data !== undefined ? parsed.data : parsed;
682
- }
683
- catch (e) {
684
- // Keep original value
685
- }
686
- }
687
- // Apply transform if exists
688
- if (propMeta.transform && typeof propMeta.transform === 'function') {
689
- value = propMeta.transform(value);
690
- }
691
- this[propName] = value;
692
- }
693
- }
694
- // Process collections (skip those with custom getter)
695
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
696
- if (collMeta.getter)
697
- continue; // Handle via custom getter evaluation
698
- const matching = links.filter((l) => l.predicate === collMeta.predicate);
699
- // Collections preserve chronological order: links are sorted ASC by timestamp,
700
- // so the collection reflects the order in which items were added (oldest to newest).
701
- let values = matching.map((l) => l.target);
702
- // Apply where.condition filtering if present
703
- if (collMeta.where?.condition && values.length > 0) {
704
- try {
705
- // Filter values by evaluating condition for each value
706
- const filteredValues = [];
707
- for (const value of values) {
708
- let condition = collMeta.where.condition
709
- .replace(/\$perspective/g, `'${__classPrivateFieldGet(this, _Ad4mModel_perspective, "f").uuid}'`)
710
- .replace(/\$base/g, `'${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}'`)
711
- .replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
712
- // If condition starts with WHERE, wrap it in array length check pattern
713
- // Using array::len() to properly count matching links
714
- if (condition.trim().startsWith('WHERE')) {
715
- condition = `array::len(SELECT * FROM link ${condition}) > 0`;
716
- }
717
- const filterQuery = `RETURN ${condition}`;
718
- const result = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").querySurrealDB(filterQuery);
719
- // RETURN can return the value directly or in an array
720
- const isTrue = result === true || (Array.isArray(result) && result.length > 0 && result[0] === true);
721
- if (isTrue) {
722
- filteredValues.push(value);
723
- }
724
- }
725
- values = filteredValues;
726
- }
727
- catch (error) {
728
- console.warn(`Failed to apply condition filter for ${collName}:`, error);
729
- // Keep unfiltered values on error
730
- }
731
- }
732
- // Apply where.isInstance filtering if present
733
- if (collMeta.where?.isInstance && values.length > 0) {
734
- try {
735
- const className = typeof collMeta.where.isInstance === 'string'
736
- ? collMeta.where.isInstance
737
- : collMeta.where.isInstance.name;
738
- const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
739
- if (filterMetadata) {
740
- values = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(values, filterMetadata);
741
- }
742
- }
743
- catch (error) {
744
- // Keep unfiltered values on error
745
- }
746
- }
747
- this[collName] = values;
748
- }
749
- // Set author and timestamps
750
- if (originalAuthor) {
751
- this.author = originalAuthor;
752
- }
753
- if (minTimestamp) {
754
- this.createdAt = minTimestamp;
755
- }
756
- if (maxTimestamp) {
757
- this.updatedAt = maxTimestamp;
758
- }
759
- }
760
- // Evaluate SurrealQL getters
761
- await ctor.evaluateCustomGettersForInstance(this, __classPrivateFieldGet(this, _Ad4mModel_perspective, "f"), metadata);
762
- // Apply where.isInstance filtering to getter collections
763
- // (non-getter collections were already filtered above)
764
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
765
- if (collMeta.getter && collMeta.where?.isInstance && this[collName]?.length > 0) {
766
- try {
767
- const className = typeof collMeta.where.isInstance === 'string'
768
- ? collMeta.where.isInstance
769
- : collMeta.where.isInstance.name;
770
- const filterMetadata = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").getSubjectClassMetadataFromSDNA(className);
771
- if (filterMetadata) {
772
- const filtered = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").batchCheckSubjectInstances(this[collName], filterMetadata);
773
- this[collName] = filtered;
774
- }
775
- }
776
- catch (error) {
777
- // Keep unfiltered values on error
778
- }
779
- }
780
- }
781
- }
782
- catch (e) {
783
- console.error(`SurrealDB getData also failed for ${__classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f")}:`, e);
784
- }
785
- return this;
786
- }
787
- // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
788
- static async queryToProlog(perspective, query, modelClassName) {
789
- const { source, properties, collections, where, order, offset, limit, count } = query;
790
- const className = modelClassName || (await this.getClassName(perspective));
791
- const instanceQueries = [
792
- buildAuthorAndTimestampQuery(),
793
- buildSourceQuery(source),
794
- buildPropertiesQuery(properties),
795
- buildCollectionsQuery(collections),
796
- buildWhereQuery(where),
797
- ];
798
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
799
- const fullQuery = `
800
- findall([Base, Properties, Collections, Timestamp, Author], (
801
- subject_class("${className}", SubjectClass),
802
- instance(SubjectClass, Base),
803
- ${instanceQueries.filter((q) => q).join(", ")}
804
- ), UnsortedInstances),
805
- ${resultSetQueries.filter((q) => q).join(", ")}
806
- `;
807
- return fullQuery;
808
- }
809
- /**
810
- * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
811
- * @private
73
+ * @example `await Promise.all([Post, Comment, Tag].map(M => M.register(perspective)));`
812
74
  */
813
- static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
814
- const safeBaseExpression = this.formatSurrealValue(instance.baseExpression);
815
- // Evaluate property getters
816
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
817
- if (propMeta.getter) {
818
- try {
819
- // Replace 'Base' placeholder with actual base expression
820
- const query = propMeta.getter.replace(/Base/g, safeBaseExpression);
821
- // Query from node table to have graph traversal context
822
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
823
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null && result[0].value !== 'None' && result[0].value !== '') {
824
- instance[propName] = result[0].value;
825
- }
826
- }
827
- catch (error) {
828
- console.warn(`Failed to evaluate getter for ${propName}:`, error);
829
- }
830
- }
831
- }
832
- // Evaluate collection getters
833
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
834
- if (collMeta.getter) {
835
- try {
836
- // Replace 'Base' placeholder with actual base expression
837
- const query = collMeta.getter.replace(/Base/g, safeBaseExpression);
838
- // Query from node table to have graph traversal context
839
- const result = await perspective.querySurrealDB(`SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`);
840
- if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
841
- // Filter out 'None' from collection results
842
- const value = result[0].value;
843
- instance[collName] = Array.isArray(value)
844
- ? value.filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None')
845
- : value;
846
- }
847
- }
848
- catch (error) {
849
- console.warn(`Failed to evaluate getter for ${collName}:`, error);
850
- }
851
- }
852
- }
75
+ static async register(perspective) {
76
+ await perspective.ensureSDNASubjectClass(this);
853
77
  }
854
78
  /**
855
- * Generates a SurrealQL query from a Query object.
856
- *
857
- * @description
858
- * This method translates high-level query parameters into a SurrealQL query string
859
- * that can be executed against the SurrealDB backend. Unlike Prolog queries which
860
- * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
861
- * stored in SurrealDB.
862
- *
863
- * The generated query uses a CTE (Common Table Expression) pattern:
864
- * 1. First, identify candidate base expressions by filtering links based on where conditions
865
- * 2. Then, for each candidate base, resolve properties and collections via subqueries
866
- * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
867
- *
868
- * Key architectural notes:
869
- * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
870
- * - No SDNA knowledge at the database level
871
- * - Properties are resolved via subqueries that look for links with specific predicates
872
- * - Collections are similar but return multiple values instead of one
873
- * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
874
- *
875
- * @param perspective - The perspective to query (used for metadata extraction)
876
- * @param query - Query parameters (where, order, limit, offset, properties, collections)
877
- * @returns Complete SurrealQL query string ready for execution
79
+ * One-shot factory: constructs, assigns `data`, saves, and returns the new instance.
878
80
  *
879
81
  * @example
880
82
  * ```typescript
881
- * const query = Recipe.queryToSurrealQL(perspective, {
882
- * where: { name: "Pasta", rating: { gt: 4 } },
883
- * order: { timestamp: "DESC" },
884
- * limit: 10
885
- * });
886
- * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
887
- * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
83
+ * const post = await Post.create(perspective, { title: 'Hello', body: 'World' });
888
84
  * ```
889
85
  */
890
- static async queryToSurrealQL(perspective, query) {
891
- const metadata = this.getModelMetadata();
892
- const { source, where, order, offset, limit } = query;
893
- // Build list of graph traversal filters for required predicates
894
- const graphTraversalFilters = [];
895
- // Add source filter if specified (filter to nodes that are children of this source)
896
- // Source filter means: find targets of 'ad4m://has_child' links from the specified source
897
- if (source) {
898
- // Use graph traversal: node must be target of has_child link from source
899
- graphTraversalFilters.push(`count(<-link[WHERE perspective = $perspective AND in.uri = ${this.formatSurrealValue(source)} AND predicate = 'ad4m://has_child']) > 0`);
900
- }
901
- // Add filters for required properties
902
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
903
- if (propMeta.required) {
904
- // For flag properties, also filter by the target value
905
- if (propMeta.flag && propMeta.initial) {
906
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
907
- }
908
- else {
909
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
910
- }
911
- }
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);
912
94
  }
913
- // If no required properties, we need at least one property to define the model
914
- // Use any property with an initial value as the defining characteristic
915
- if (graphTraversalFilters.length === 0) {
916
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
917
- if (propMeta.initial) {
918
- // For flag properties, also filter by the target value
919
- if (propMeta.flag) {
920
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
921
- }
922
- else {
923
- graphTraversalFilters.push(`count(->link[WHERE perspective = $perspective AND predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
924
- }
925
- break; // Just need one defining property
926
- }
927
- }
928
- }
929
- // Build user WHERE clause filters using graph traversal
930
- const userWhereClause = this.buildGraphTraversalWhereClause(metadata, where);
931
- // Build complete WHERE clause using graph traversal filters
932
- const whereConditions = [];
933
- // Add all graph traversal filters for required properties
934
- whereConditions.push(...graphTraversalFilters);
935
- // Add user where conditions if any
936
- if (userWhereClause) {
937
- whereConditions.push(userWhereClause);
938
- }
939
- // Always ensure node has at least one link in this perspective
940
- whereConditions.push(`count(->link[WHERE perspective = $perspective]) > 0`);
941
- // Build the query FROM node using direct graph traversal in WHERE
942
- // This avoids slow subqueries and uses graph indexes for fast traversal
943
- const fullQuery = `
944
- SELECT
945
- id AS source,
946
- uri AS source_uri,
947
- ->link[WHERE perspective = $perspective] AS links
948
- FROM node
949
- WHERE ${whereConditions.join(' AND ')}
950
- `.trim();
951
- return fullQuery;
95
+ return instance;
952
96
  }
953
97
  /**
954
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
955
- *
956
- * @description
957
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
958
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
98
+ * Fetches the instance, merges `data` into it, then saves.
959
99
  *
960
- * Handles several condition types:
961
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
962
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
963
- * - NOT operators: Use `NOT` prefix
964
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
965
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
100
+ * This is a convenience alternative to the three-step pattern:
101
+ * ```typescript
102
+ * // Before
103
+ * const instance = new Vote(perspective, id);
104
+ * instance.score = newScore;
105
+ * await instance.save();
966
106
  *
967
- * @param metadata - Model metadata containing property predicates
968
- * @param where - Where conditions from the query
969
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
107
+ * // After
108
+ * await Vote.update(perspective, id, { score: newScore });
109
+ * ```
970
110
  *
971
- * @private
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.
972
114
  */
973
- static buildGraphTraversalWhereClause(metadata, where) {
974
- if (!where)
975
- return '';
976
- const conditions = [];
977
- for (const [propertyName, condition] of Object.entries(where)) {
978
- // Check if this is a special field (base, author, timestamp)
979
- // Note: author and timestamp filtering is done in JavaScript after query
980
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
981
- if (isSpecial) {
982
- // Skip author and timestamp - they'll be filtered in JavaScript
983
- // Only handle 'base' (which maps to 'uri') here
984
- if (propertyName === 'author' || propertyName === 'timestamp') {
985
- continue; // Skip - will be filtered post-query
986
- }
987
- const columnName = 'uri'; // base maps to uri in node table
988
- // Handle base/uri field directly
989
- if (Array.isArray(condition)) {
990
- // Array values (IN clause)
991
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
992
- conditions.push(`${columnName} IN [${formattedValues}]`);
993
- }
994
- else if (typeof condition === 'object' && condition !== null) {
995
- // Operator object
996
- const ops = condition;
997
- if (ops.not !== undefined) {
998
- if (Array.isArray(ops.not)) {
999
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1000
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1001
- }
1002
- else {
1003
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1004
- }
1005
- }
1006
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1007
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1008
- }
1009
- if (ops.gt !== undefined) {
1010
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1011
- }
1012
- if (ops.gte !== undefined) {
1013
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1014
- }
1015
- if (ops.lt !== undefined) {
1016
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1017
- }
1018
- if (ops.lte !== undefined) {
1019
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1020
- }
1021
- if (ops.contains !== undefined) {
1022
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1023
- }
1024
- }
1025
- else {
1026
- // Simple equality
1027
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1028
- }
1029
- }
1030
- else {
1031
- // Handle regular properties via graph traversal
1032
- const propMeta = metadata.properties[propertyName];
1033
- if (!propMeta)
1034
- continue; // Skip if property not found in metadata
1035
- const predicate = escapeSurrealString(propMeta.predicate);
1036
- // Use fn::parse_literal() for properties with resolveLanguage
1037
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
1038
- if (Array.isArray(condition)) {
1039
- // Array values (IN clause)
1040
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1041
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
1042
- }
1043
- else if (typeof condition === 'object' && condition !== null) {
1044
- // Operator object
1045
- const ops = condition;
1046
- if (ops.not !== undefined) {
1047
- if (Array.isArray(ops.not)) {
1048
- // For NOT IN with array: must NOT have a link with value in the array
1049
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1050
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
1051
- }
1052
- else {
1053
- // For NOT with single value: must NOT have this value
1054
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)}]) = 0`);
1055
- }
1056
- }
1057
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1058
- // post-query because fn::parse_literal() comparisons in SurrealDB
1059
- // don't work reliably with numeric comparisons.
1060
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1061
- // However, we still need to ensure the property exists
1062
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1063
- ops.lt !== undefined || ops.lte !== undefined ||
1064
- ops.between !== undefined || ops.contains !== undefined;
1065
- if (hasComparisonOps) {
1066
- // Ensure we only get nodes that have this property
1067
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}']) > 0`);
1068
- }
1069
- }
1070
- else {
1071
- // Simple equality
1072
- conditions.push(`count(->link[WHERE perspective = $perspective AND predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)}]) > 0`);
1073
- }
1074
- }
1075
- }
1076
- return conditions.join(' AND ');
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;
1077
121
  }
1078
122
  /**
1079
- * Builds the WHERE clause for SurrealQL queries.
1080
- *
1081
- * @description
1082
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
1083
- * For each property filter, generates a subquery that checks for links with the appropriate
1084
- * predicate and target value.
1085
- *
1086
- * Handles several condition types:
1087
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
1088
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
1089
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
1090
- * - gt, gte, lt, lte: comparison operators
1091
- * - not: negation (single value or array)
1092
- * - between: range check
1093
- * - contains: substring/element check (uses SurrealQL CONTAINS)
1094
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
123
+ * Deletes the instance with the given `id` from the perspective.
1095
124
  *
1096
- * All conditions are joined with AND.
125
+ * This is a convenience alternative to:
126
+ * ```typescript
127
+ * // Before
128
+ * const instance = new Poll(perspective, id);
129
+ * await instance.delete();
1097
130
  *
1098
- * @param metadata - Model metadata containing property predicates
1099
- * @param where - Where conditions from the query
1100
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
131
+ * // After
132
+ * await Poll.delete(perspective, id);
133
+ * ```
1101
134
  *
1102
- * @private
135
+ * @param batchId - Optional batch identifier for grouping removals.
1103
136
  */
1104
- static buildSurrealWhereClause(metadata, where) {
1105
- if (!where)
1106
- return '';
1107
- const conditions = [];
1108
- for (const [propertyName, condition] of Object.entries(where)) {
1109
- // Check if this is a special field (base, author, timestamp)
1110
- // Note: author and timestamp filtering is done in JavaScript after GROUP BY
1111
- // because they need to be computed from the grouped links first
1112
- const isSpecial = ['base', 'author', 'timestamp'].includes(propertyName);
1113
- if (isSpecial) {
1114
- // Skip author and timestamp - they'll be filtered in JavaScript
1115
- // Only handle 'base' (which maps to 'source') here
1116
- if (propertyName === 'author' || propertyName === 'timestamp') {
1117
- continue; // Skip - will be filtered post-query
1118
- }
1119
- const columnName = 'source'; // base maps to source
1120
- // Handle base/source field directly
1121
- if (Array.isArray(condition)) {
1122
- // Array values (IN clause)
1123
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1124
- conditions.push(`${columnName} IN [${formattedValues}]`);
1125
- }
1126
- else if (typeof condition === 'object' && condition !== null) {
1127
- // Operator object
1128
- const ops = condition;
1129
- if (ops.not !== undefined) {
1130
- if (Array.isArray(ops.not)) {
1131
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1132
- conditions.push(`${columnName} NOT IN [${formattedValues}]`);
1133
- }
1134
- else {
1135
- conditions.push(`${columnName} != ${this.formatSurrealValue(ops.not)}`);
1136
- }
1137
- }
1138
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1139
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.between[0])} AND ${columnName} <= ${this.formatSurrealValue(ops.between[1])}`);
1140
- }
1141
- if (ops.gt !== undefined) {
1142
- conditions.push(`${columnName} > ${this.formatSurrealValue(ops.gt)}`);
1143
- }
1144
- if (ops.gte !== undefined) {
1145
- conditions.push(`${columnName} >= ${this.formatSurrealValue(ops.gte)}`);
1146
- }
1147
- if (ops.lt !== undefined) {
1148
- conditions.push(`${columnName} < ${this.formatSurrealValue(ops.lt)}`);
1149
- }
1150
- if (ops.lte !== undefined) {
1151
- conditions.push(`${columnName} <= ${this.formatSurrealValue(ops.lte)}`);
1152
- }
1153
- if (ops.contains !== undefined) {
1154
- conditions.push(`${columnName} CONTAINS ${this.formatSurrealValue(ops.contains)}`);
1155
- }
1156
- }
1157
- else {
1158
- // Simple equality
1159
- conditions.push(`${columnName} = ${this.formatSurrealValue(condition)}`);
1160
- }
1161
- }
1162
- else {
1163
- // Handle regular properties via subqueries
1164
- const propMeta = metadata.properties[propertyName];
1165
- if (!propMeta)
1166
- continue; // Skip if property not found in metadata
1167
- const predicate = escapeSurrealString(propMeta.predicate);
1168
- // Use fn::parse_literal() for properties with resolveLanguage
1169
- const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(target)' : 'target';
1170
- if (Array.isArray(condition)) {
1171
- // Array values (IN clause)
1172
- const formattedValues = condition.map(v => this.formatSurrealValue(v)).join(', ');
1173
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1174
- }
1175
- else if (typeof condition === 'object' && condition !== null) {
1176
- // Operator object
1177
- const ops = condition;
1178
- if (ops.not !== undefined) {
1179
- if (Array.isArray(ops.not)) {
1180
- // For NOT IN with array: exclude sources that HAVE a value in the array
1181
- const formattedValues = ops.not.map(v => this.formatSurrealValue(v)).join(', ');
1182
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}])`);
1183
- }
1184
- else {
1185
- // For NOT with single value: exclude sources that HAVE this value
1186
- conditions.push(`source NOT IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(ops.not)})`);
1187
- }
1188
- }
1189
- // Note: gt, gte, lt, lte, between, contains operators are filtered in JavaScript
1190
- // post-query because fn::parse_literal() comparisons in SurrealDB subqueries
1191
- // don't work reliably with numeric comparisons.
1192
- // These are handled in instancesFromSurrealResult along with author/timestamp filtering.
1193
- // However, we still need to ensure the property exists by filtering on the predicate
1194
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1195
- ops.lt !== undefined || ops.lte !== undefined ||
1196
- ops.between !== undefined || ops.contains !== undefined;
1197
- if (hasComparisonOps) {
1198
- // Ensure we only get instances that have this property
1199
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}')`);
1200
- }
1201
- }
1202
- else {
1203
- // Simple equality
1204
- conditions.push(`source IN (SELECT VALUE source FROM link WHERE predicate = '${predicate}' AND ${targetField} = ${this.formatSurrealValue(condition)})`);
1205
- }
1206
- }
1207
- }
1208
- return conditions.join(' AND ');
137
+ static async delete(perspective, id, batchId) {
138
+ const instance = new this(perspective, id);
139
+ await instance.delete(batchId);
1209
140
  }
1210
141
  /**
1211
- * Builds the SELECT fields for SurrealQL queries.
1212
- *
1213
- * @description
1214
- * Generates the field list for the SELECT clause, resolving properties and collections
1215
- * via subqueries. Each property is fetched with a subquery that finds the link with the
1216
- * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
1217
- *
1218
- * Field types:
1219
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
1220
- * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
1221
- * - Author/Timestamp: Always included to provide metadata about each instance
1222
- *
1223
- * If properties or collections arrays are provided, only those fields are included.
1224
- * Otherwise, all properties/collections from metadata are included.
1225
- *
1226
- * @param metadata - Model metadata containing property and collection predicates
1227
- * @param properties - Optional array of property names to include (default: all)
1228
- * @param collections - Optional array of collection names to include (default: all)
1229
- * @returns Comma-separated SELECT field list
1230
- *
1231
- * @private
142
+ * Generates the SHACL shape for this model class.
143
+ * Attached dynamically by the `@Model` decorator.
1232
144
  */
1233
- static buildSurrealSelectFields(metadata, properties, collections) {
1234
- const fields = [];
1235
- // Determine properties to fetch
1236
- const propsToFetch = properties || Object.keys(metadata.properties);
1237
- for (const propName of propsToFetch) {
1238
- const propMeta = metadata.properties[propName];
1239
- if (!propMeta)
1240
- continue; // Skip if not found
1241
- // Reference source directly since we're selecting from link table
1242
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1243
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}' LIMIT 1) AS ${propName}`);
1244
- }
1245
- // Determine collections to fetch
1246
- const collsToFetch = collections || Object.keys(metadata.collections);
1247
- for (const collName of collsToFetch) {
1248
- const collMeta = metadata.collections[collName];
1249
- if (!collMeta)
1250
- continue; // Skip if not found
1251
- // Reference source directly since we're selecting from link table
1252
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1253
- fields.push(`(SELECT VALUE target FROM link WHERE source = source AND predicate = '${escapedPredicate}') AS ${collName}`);
1254
- }
1255
- // Always add author and timestamp fields
1256
- fields.push(`(SELECT VALUE author FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS author`);
1257
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp ASC LIMIT 1) AS createdAt`);
1258
- fields.push(`(SELECT VALUE timestamp FROM link WHERE source = source ORDER BY timestamp DESC LIMIT 1) AS updatedAt`);
1259
- return fields.join(',\n ');
145
+ static generateSHACL() {
146
+ throw new Error("generateSHACL() is only available on classes decorated with @Model");
1260
147
  }
1261
- /**
1262
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
1263
- * Compatible with GROUP BY source queries.
1264
- *
1265
- * @private
1266
- */
1267
- static buildSurrealSelectFieldsWithAggregation(metadata, properties, collections) {
1268
- const fields = [];
1269
- // Determine properties to fetch
1270
- const propsToFetch = properties || Object.keys(metadata.properties);
1271
- for (const propName of propsToFetch) {
1272
- const propMeta = metadata.properties[propName];
1273
- if (!propMeta)
1274
- continue; // Skip if not found
1275
- // Use array::first to get the first target value for this predicate
1276
- const escapedPredicate = escapeSurrealString(propMeta.predicate);
1277
- fields.push(`array::first(target[WHERE predicate = '${escapedPredicate}']) AS ${propName}`);
1278
- }
1279
- // Determine collections to fetch
1280
- const collsToFetch = collections || Object.keys(metadata.collections);
1281
- for (const collName of collsToFetch) {
1282
- const collMeta = metadata.collections[collName];
1283
- if (!collMeta)
1284
- continue; // Skip if not found
1285
- // Use array filtering to get all target values for this predicate
1286
- const escapedPredicate = escapeSurrealString(collMeta.predicate);
1287
- fields.push(`target[WHERE predicate = '${escapedPredicate}'] AS ${collName}`);
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);
1288
170
  }
1289
- // Always add author and timestamp fields
1290
- fields.push(`array::first(author) AS author`);
1291
- fields.push(`array::first(timestamp) AS createdAt`);
1292
- fields.push(`array::last(timestamp) AS updatedAt`);
1293
- return fields.join(',\n ');
1294
171
  }
1295
172
  /**
1296
- * Formats a value for use in SurrealQL queries.
1297
- *
1298
- * @description
1299
- * Handles different value types:
1300
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
1301
- * - Numbers/booleans: Converted to string
1302
- * - Arrays: Recursively formatted and wrapped in brackets
1303
- *
1304
- * @param value - The value to format
1305
- * @returns Formatted value string ready for SurrealQL
1306
- *
1307
- * @private
173
+ * The unique identifier (base expression URI) of this instance.
1308
174
  */
1309
- static formatSurrealValue(value) {
1310
- if (typeof value === 'string') {
1311
- // Escape backslashes first, then single quotes and other special characters
1312
- const escaped = value
1313
- .replace(/\\/g, '\\\\') // Backslash -> \\
1314
- .replace(/'/g, "\\'") // Single quote -> \'
1315
- .replace(/"/g, '\\"') // Double quote -> \"
1316
- .replace(/\n/g, '\\n') // Newline -> \n
1317
- .replace(/\r/g, '\\r') // Carriage return -> \r
1318
- .replace(/\t/g, '\\t'); // Tab -> \t
1319
- return `'${escaped}'`;
1320
- }
1321
- else if (typeof value === 'number' || typeof value === 'boolean') {
1322
- return String(value);
1323
- }
1324
- else if (Array.isArray(value)) {
1325
- return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
1326
- }
1327
- else {
1328
- return String(value);
1329
- }
175
+ get id() {
176
+ return this._id;
1330
177
  }
1331
- static async instancesFromPrologResult(perspective, query, result) {
1332
- if (!result?.[0]?.AllInstances)
1333
- return { results: [], totalCount: 0 };
1334
- // Map results to instances
1335
- const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
1336
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
1337
- try {
1338
- const instance = new this(perspective, Base);
1339
- // Remove unrequested attributes from instance
1340
- if (requestedAttribtes.length) {
1341
- Object.keys(instance).forEach((key) => {
1342
- if (!requestedAttribtes.includes(key))
1343
- delete instance[key];
1344
- });
1345
- }
1346
- // Collect values to assign to instance
1347
- const values = [...Properties, ...Collections, ["createdAt", Timestamp], ["author", Author]];
1348
- await Ad4mModel.assignValuesToInstance(perspective, instance, values);
1349
- return instance;
1350
- }
1351
- catch (error) {
1352
- console.error(`Failed to process instance ${Base}:`, error);
1353
- // Return null for failed instances - we'll filter these out below
1354
- return null;
1355
- }
1356
- }));
1357
- return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
178
+ /** Read-only perspective access for subclasses. */
179
+ get perspective() {
180
+ return this._perspective;
181
+ }
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
+ };
1358
189
  }
1359
190
  /**
1360
- * Converts SurrealDB query results to Ad4mModel instances.
191
+ * Generates a SurrealQL query string for this model.
1361
192
  *
1362
193
  * @param perspective - The perspective context
1363
- * @param query - The query parameters used
1364
- * @param result - Array of result objects from SurrealDB
1365
- * @returns Promise resolving to results with total count
1366
- *
1367
- * @internal
194
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
195
+ * @returns Complete SurrealQL query string ready for execution
1368
196
  */
1369
- static async instancesFromSurrealResult(perspective, query, result) {
1370
- if (!result || result.length === 0)
1371
- return { results: [], totalCount: 0 };
1372
- const metadata = this.getModelMetadata();
1373
- const requestedProperties = query?.properties || [];
1374
- const requestedCollections = query?.collections || [];
1375
- // The query used GROUP BY with graph traversal, so each row has:
1376
- // - source: the node ID (e.g., "node:abc123")
1377
- // - source_uri: the actual URI (the base expression)
1378
- // - links: array of link objects with {predicate, target, author, timestamp}
1379
- const instances = [];
1380
- for (const row of result) {
1381
- let base;
1382
- try {
1383
- // Use source_uri as the base (the actual URI), not the node ID
1384
- base = row.source_uri;
1385
- // Skip rows without a source_uri field
1386
- if (!base) {
1387
- continue;
1388
- }
1389
- const links = row.links || [];
1390
- const instance = new this(perspective, base);
1391
- // Track both earliest (createdAt) and most recent (updatedAt) timestamps
1392
- let minTimestamp = null;
1393
- let maxTimestamp = null;
1394
- let originalAuthor = null;
1395
- let latestAuthor = null;
1396
- // Process each link (track index for collection ordering)
1397
- for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
1398
- const link = links[linkIndex];
1399
- const predicate = link.predicate;
1400
- const target = link.target;
1401
- // Skip 'None' values
1402
- if (target === 'None')
1403
- continue;
1404
- // Track both earliest (createdAt) and latest (updatedAt) timestamps with their authors
1405
- if (link.timestamp) {
1406
- if (!minTimestamp || link.timestamp < minTimestamp) {
1407
- minTimestamp = link.timestamp;
1408
- originalAuthor = link.author;
1409
- }
1410
- if (!maxTimestamp || link.timestamp > maxTimestamp) {
1411
- maxTimestamp = link.timestamp;
1412
- latestAuthor = link.author;
1413
- }
1414
- }
1415
- // Find matching property (skip those with getter)
1416
- let foundProperty = false;
1417
- for (const [propName, propMeta] of Object.entries(metadata.properties)) {
1418
- if (propMeta.getter)
1419
- continue; // Handle via getter evaluation
1420
- if (propMeta.predicate === predicate) {
1421
- // For properties, take the first value (or we could use timestamp to get latest)
1422
- // Note: Empty objects {} are truthy, so we need to check for them explicitly
1423
- const currentValue = instance[propName];
1424
- const isEmptyObject = typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue) && Object.keys(currentValue).length === 0;
1425
- if (!currentValue || currentValue === "" || currentValue === 0 || isEmptyObject) {
1426
- let convertedValue = target;
1427
- // Only process if target has a value
1428
- if (target !== undefined && target !== null && target !== '') {
1429
- // Check if we need to resolve a non-literal language expression.
1430
- // resolveLanguage must be defined and not 'literal' to trigger expression resolution.
1431
- // Also skip if the target itself is a literal:// URI — those are handled by the
1432
- // literal-parsing branch below (avoids calling getExpression on empty literals like
1433
- // "literal://string:" which would cause a deserialization error).
1434
- if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string' && !target.startsWith('literal://')) {
1435
- // For non-literal languages, resolve the expression via perspective.getExpression()
1436
- // Note: Literals are already parsed by SurrealDB's fn::parse_literal()
1437
- try {
1438
- const expression = await perspective.getExpression(target);
1439
- if (expression) {
1440
- // Parse the expression data if it's a JSON string
1441
- try {
1442
- convertedValue = JSON.parse(expression.data);
1443
- }
1444
- catch {
1445
- // If parsing fails, use the data as-is
1446
- convertedValue = expression.data;
1447
- }
1448
- }
1449
- }
1450
- catch (e) {
1451
- console.warn(`Failed to resolve expression for ${propName} with target "${target}":`, e);
1452
- console.warn("Falling back to raw value");
1453
- convertedValue = target; // Fall back to raw value
1454
- }
1455
- }
1456
- else if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
1457
- // Only parse literal URIs when resolveLanguage is explicitly set to 'literal'.
1458
- // Without this check, properties pointing to baseExpressions of other models
1459
- // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
1460
- try {
1461
- const parsed = Literal.fromUrl(target).get();
1462
- if (parsed.data !== undefined) {
1463
- convertedValue = parsed.data;
1464
- }
1465
- else {
1466
- convertedValue = parsed;
1467
- }
1468
- }
1469
- catch (e) {
1470
- // If literal parsing fails, just use the value as-is (don't bail)
1471
- convertedValue = target;
1472
- }
1473
- }
1474
- else if (typeof target === 'string') {
1475
- // Type conversion: check the instance property's current type
1476
- const expectedType = typeof instance[propName];
1477
- if (expectedType === 'number') {
1478
- convertedValue = Number(target);
1479
- }
1480
- else if (expectedType === 'boolean') {
1481
- convertedValue = target === 'true' || target === '1';
1482
- }
1483
- }
1484
- }
1485
- // Apply transform function if it exists
1486
- if (propMeta.transform && typeof propMeta.transform === 'function') {
1487
- convertedValue = propMeta.transform(convertedValue);
1488
- }
1489
- instance[propName] = convertedValue;
1490
- }
1491
- foundProperty = true;
1492
- break;
1493
- }
1494
- }
1495
- // If not a property, check if it's a collection (skip those with getter)
1496
- if (!foundProperty) {
1497
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1498
- if (collMeta.getter)
1499
- continue; // Handle via getter evaluation
1500
- if (collMeta.predicate === predicate) {
1501
- // For collections, accumulate all values with their timestamps and indices for sorting
1502
- if (!instance[collName]) {
1503
- instance[collName] = [];
1504
- }
1505
- // Initialize timestamp tracking array if not already done
1506
- const timestampsKey = `__${collName}_timestamps`;
1507
- const indicesKey = `__${collName}_indices`;
1508
- if (!instance[timestampsKey]) {
1509
- instance[timestampsKey] = [];
1510
- }
1511
- if (!instance[indicesKey]) {
1512
- instance[indicesKey] = [];
1513
- }
1514
- if (!instance[collName].includes(target)) {
1515
- instance[collName].push(target);
1516
- instance[timestampsKey].push(link.timestamp || '');
1517
- // Track original position in the links array for stable sorting
1518
- instance[indicesKey].push(linkIndex);
1519
- }
1520
- break;
1521
- }
1522
- }
1523
- }
1524
- }
1525
- // Set author and timestamps
1526
- if (originalAuthor) {
1527
- instance.author = originalAuthor;
1528
- }
1529
- // Set createdAt from earliest timestamp
1530
- if (minTimestamp) {
1531
- if (typeof minTimestamp === 'string' && minTimestamp.includes('T')) {
1532
- instance.createdAt = new Date(minTimestamp).getTime();
1533
- }
1534
- else if (typeof minTimestamp === 'string') {
1535
- const parsed = parseInt(minTimestamp, 10);
1536
- instance.createdAt = isNaN(parsed) ? minTimestamp : parsed;
1537
- }
1538
- else {
1539
- instance.createdAt = minTimestamp;
1540
- }
1541
- }
1542
- // Set updatedAt from most recent timestamp
1543
- if (maxTimestamp) {
1544
- if (typeof maxTimestamp === 'string' && maxTimestamp.includes('T')) {
1545
- instance.updatedAt = new Date(maxTimestamp).getTime();
1546
- }
1547
- else if (typeof maxTimestamp === 'string') {
1548
- const parsed = parseInt(maxTimestamp, 10);
1549
- instance.updatedAt = isNaN(parsed) ? maxTimestamp : parsed;
1550
- }
1551
- else {
1552
- instance.updatedAt = maxTimestamp;
1553
- }
1554
- }
1555
- // Sort collections by timestamp to maintain insertion order
1556
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1557
- const timestampsKey = `__${collName}_timestamps`;
1558
- const indicesKey = `__${collName}_indices`;
1559
- if (instance[collName] && instance[timestampsKey]) {
1560
- // Create array of [value, timestamp, index] tuples
1561
- const pairs = instance[collName].map((value, index) => ({
1562
- value,
1563
- timestamp: instance[timestampsKey][index] || '',
1564
- originalIndex: instance[indicesKey]?.[index] ?? index
1565
- }));
1566
- // Sort by timestamp first, then by original index for stable sorting
1567
- pairs.sort((a, b) => {
1568
- const tsA = String(a.timestamp || '');
1569
- const tsB = String(b.timestamp || '');
1570
- const tsCompare = tsA.localeCompare(tsB);
1571
- if (tsCompare !== 0)
1572
- return tsCompare;
1573
- // Use original index as tiebreaker for stable sorting
1574
- return a.originalIndex - b.originalIndex;
1575
- });
1576
- // Replace collection with sorted values, filtering out empty strings and None
1577
- instance[collName] = pairs
1578
- .map(p => p.value)
1579
- .filter((v) => v !== undefined && v !== null && v !== '' && v !== 'None');
1580
- // Clean up temporary arrays
1581
- delete instance[timestampsKey];
1582
- delete instance[indicesKey];
1583
- }
1584
- }
1585
- // Filter by requested attributes if specified
1586
- if (requestedProperties.length > 0 || requestedCollections.length > 0) {
1587
- const requestedAttributes = [...requestedProperties, ...requestedCollections];
1588
- Object.keys(instance).forEach((key) => {
1589
- // Keep only requested attributes, plus always keep createdAt, updatedAt, author, and baseExpression
1590
- // Note: timestamp is a getter alias for createdAt, so we preserve createdAt instead
1591
- if (!requestedAttributes.includes(key) && key !== 'createdAt' && key !== 'updatedAt' && key !== 'author' && key !== 'baseExpression') {
1592
- delete instance[key];
1593
- }
1594
- });
1595
- }
1596
- instances.push(instance);
1597
- }
1598
- catch (error) {
1599
- console.error(`Failed to process SurrealDB instance ${base}:`, error);
1600
- }
1601
- }
1602
- // Evaluate custom getters for all instances (single pass)
1603
- // This populates collection values needed for where.isInstance filtering
1604
- for (const instance of instances) {
1605
- await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
1606
- }
1607
- // Filter collections by where.isInstance if specified
1608
- // Do this after initial evaluation so collection values exist for filtering
1609
- for (const instance of instances) {
1610
- for (const [collName, collMeta] of Object.entries(metadata.collections)) {
1611
- if (collMeta.where?.isInstance && instance[collName]?.length > 0) {
1612
- try {
1613
- const targetClass = collMeta.where.isInstance;
1614
- const subjects = instance[collName];
1615
- // Get the class metadata from SDNA to pass to batchCheckSubjectInstances
1616
- const targetClassName = typeof targetClass === 'string'
1617
- ? targetClass
1618
- : targetClass.prototype?.className || targetClass.name;
1619
- const classMetadata = await perspective.getSubjectClassMetadataFromSDNA(targetClassName);
1620
- if (!classMetadata) {
1621
- continue;
1622
- }
1623
- // Check which subjects are instances of the target class
1624
- const validSubjects = await perspective.batchCheckSubjectInstances(subjects, classMetadata);
1625
- // Update the collection with filtered instances
1626
- instance[collName] = validSubjects;
1627
- }
1628
- catch (error) {
1629
- // On error, leave the collection unfiltered rather than breaking everything
1630
- }
1631
- }
1632
- }
1633
- }
1634
- // Filter by where conditions that couldn't be filtered in SQL
1635
- // This includes:
1636
- // - author/timestamp (computed from grouped links)
1637
- // - Properties with comparison operators (gt, gte, lt, lte, between, contains)
1638
- // because fn::parse_literal() comparisons in SurrealDB subqueries don't work reliably
1639
- let filteredInstances = instances;
1640
- if (query.where) {
1641
- filteredInstances = instances.filter(instance => {
1642
- for (const [propertyName, condition] of Object.entries(query.where)) {
1643
- // Skip 'base' as it's filtered in SQL
1644
- if (propertyName === 'base')
1645
- continue;
1646
- // For author and timestamp, always filter in JS
1647
- if (propertyName === 'author' || propertyName === 'timestamp') {
1648
- if (!this.matchesCondition(instance[propertyName], condition)) {
1649
- return false;
1650
- }
1651
- continue;
1652
- }
1653
- // For regular properties, only filter comparison operators in JS
1654
- // Simple equality and NOT are handled in SQL, but gt/gte/lt/lte/between/contains need JS
1655
- if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {
1656
- const ops = condition;
1657
- // Check if any comparison operators are present
1658
- const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
1659
- ops.lt !== undefined || ops.lte !== undefined ||
1660
- ops.between !== undefined || ops.contains !== undefined;
1661
- if (hasComparisonOps) {
1662
- if (!this.matchesCondition(instance[propertyName], condition)) {
1663
- return false;
1664
- }
1665
- }
1666
- }
1667
- }
1668
- return true;
1669
- });
1670
- }
1671
- // Apply ordering in JavaScript
1672
- // If limit/offset is used but no explicit order, default to ordering by timestamp (ASC)
1673
- // This ensures consistent pagination behavior
1674
- const effectiveOrder = query.order ||
1675
- (query.limit !== undefined || query.offset !== undefined ? { timestamp: 'ASC' } : null);
1676
- if (effectiveOrder) {
1677
- const orderPropName = Object.keys(effectiveOrder)[0];
1678
- const orderDirection = Object.values(effectiveOrder)[0];
1679
- filteredInstances.sort((a, b) => {
1680
- let aVal = a[orderPropName];
1681
- let bVal = b[orderPropName];
1682
- // Handle undefined values - push them to the end
1683
- if (aVal === undefined && bVal === undefined)
1684
- return 0;
1685
- if (aVal === undefined)
1686
- return orderDirection === 'ASC' ? 1 : -1;
1687
- if (bVal === undefined)
1688
- return orderDirection === 'ASC' ? -1 : 1;
1689
- // Compare values
1690
- let comparison = 0;
1691
- if (typeof aVal === 'number' && typeof bVal === 'number') {
1692
- comparison = aVal - bVal;
1693
- }
1694
- else if (typeof aVal === 'string' && typeof bVal === 'string') {
1695
- comparison = aVal.localeCompare(bVal);
1696
- }
1697
- else {
1698
- // Convert to strings for comparison
1699
- comparison = String(aVal).localeCompare(String(bVal));
1700
- }
1701
- return orderDirection === 'DESC' ? -comparison : comparison;
1702
- });
1703
- }
1704
- // Calculate totalCount BEFORE applying limit/offset
1705
- const totalCount = filteredInstances.length;
1706
- // Apply offset and limit in JavaScript
1707
- let paginatedInstances = filteredInstances;
1708
- if (query.offset !== undefined || query.limit !== undefined) {
1709
- const start = query.offset || 0;
1710
- const end = query.limit ? start + query.limit : undefined;
1711
- paginatedInstances = filteredInstances.slice(start, end);
1712
- }
1713
- return {
1714
- results: paginatedInstances,
1715
- totalCount
1716
- };
197
+ static async queryToSurrealQL(perspective, query) {
198
+ return ops.queryToSurrealQL(this, perspective, query);
199
+ }
200
+ /** @internal */
201
+ static async instancesFromSurrealResult(perspective, query, result, _hydrateRelations = true) {
202
+ return ops.instancesFromSurrealResult(this, perspective, query, result, _hydrateRelations);
1717
203
  }
1718
204
  /**
1719
- * Checks if a value matches a condition (for post-query filtering).
1720
- * @private
205
+ * Internal implementation used by findAll and eager relation hydration.
206
+ * Pass `_hydrateRelations = false` to prevent recursive model hydration (depth guard).
1721
207
  */
1722
- static matchesCondition(value, condition) {
1723
- // Handle array values (IN clause)
1724
- if (Array.isArray(condition)) {
1725
- return condition.includes(value);
1726
- }
1727
- // Handle operator object
1728
- if (typeof condition === 'object' && condition !== null) {
1729
- const ops = condition;
1730
- // Special case: 'not' operator (exclusive with other operators)
1731
- if (ops.not !== undefined) {
1732
- if (Array.isArray(ops.not)) {
1733
- return !ops.not.includes(value);
1734
- }
1735
- else {
1736
- return value !== ops.not;
1737
- }
1738
- }
1739
- // Special case: 'between' operator (inclusive range, exclusive with gt/gte/lt/lte)
1740
- if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
1741
- return value >= ops.between[0] && value <= ops.between[1];
1742
- }
1743
- // For all other operators (gt, gte, lt, lte, contains), we need to check ALL of them
1744
- // and return true only if ALL conditions are satisfied
1745
- let allConditionsMet = true;
1746
- if (ops.gt !== undefined) {
1747
- allConditionsMet = allConditionsMet && (value > ops.gt);
1748
- }
1749
- if (ops.gte !== undefined) {
1750
- allConditionsMet = allConditionsMet && (value >= ops.gte);
1751
- }
1752
- if (ops.lt !== undefined) {
1753
- allConditionsMet = allConditionsMet && (value < ops.lt);
1754
- }
1755
- if (ops.lte !== undefined) {
1756
- allConditionsMet = allConditionsMet && (value <= ops.lte);
1757
- }
1758
- if (ops.contains !== undefined) {
1759
- if (typeof value === 'string') {
1760
- allConditionsMet = allConditionsMet && value.includes(String(ops.contains));
1761
- }
1762
- else if (Array.isArray(value)) {
1763
- allConditionsMet = allConditionsMet && value.includes(ops.contains);
1764
- }
1765
- else {
1766
- allConditionsMet = false;
1767
- }
1768
- }
1769
- return allConditionsMet;
1770
- }
1771
- // Simple equality
1772
- return value === condition;
208
+ static async _findAllInternal(perspective, query = {}, _hydrateRelations = true) {
209
+ return ops._findAllInternal(this, perspective, query, _hydrateRelations);
1773
210
  }
1774
211
  /**
1775
- * Gets all instances of the model in the perspective that match the query params.
1776
- *
1777
- * @param perspective - The perspective to search in
1778
- * @param query - Optional query parameters to filter results
1779
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1780
- * @returns Array of matching models
212
+ * Returns all instances matching `query`.
1781
213
  *
1782
214
  * @example
1783
215
  * ```typescript
1784
- * // Get all recipes (uses SurrealDB by default)
1785
- * const allRecipes = await Recipe.findAll(perspective);
1786
- *
1787
- * // Get recipes with specific criteria (uses SurrealDB)
1788
216
  * const recipes = await Recipe.findAll(perspective, {
1789
- * where: {
1790
- * name: "Pasta",
1791
- * rating: { gt: 4 }
1792
- * },
1793
- * order: { createdAt: "DESC" },
1794
- * limit: 10
217
+ * where: { rating: { gt: 4 } }, order: { createdAt: "DESC" }, limit: 10,
1795
218
  * });
1796
- *
1797
- * // Explicitly use Prolog (legacy, for backward compatibility)
1798
- * const recipesProlog = await Recipe.findAll(perspective, {}, false);
1799
219
  * ```
1800
220
  */
1801
- static async findAll(perspective, query = {}, useSurrealDB = true) {
1802
- if (useSurrealDB) {
1803
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
1804
- const result = await perspective.querySurrealDB(surrealQuery);
1805
- const { results } = await this.instancesFromSurrealResult(perspective, query, result);
1806
- return results;
1807
- }
1808
- else {
1809
- const prologQuery = await this.queryToProlog(perspective, query);
1810
- const result = await perspective.infer(prologQuery);
1811
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
1812
- return results;
1813
- }
221
+ static async findAll(perspective, query = {}) {
222
+ return ops.findAll(this, perspective, query);
1814
223
  }
1815
224
  /**
1816
- * Gets all instances with count of total matches without offset & limit applied.
1817
- *
1818
- * @param perspective - The perspective to search in
1819
- * @param query - Optional query parameters to filter results
1820
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1821
- * @returns Object containing results array and total count
225
+ * Returns the first matching instance, or `null` if none found.
1822
226
  *
1823
227
  * @example
1824
228
  * ```typescript
1825
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
1826
- * where: { category: "Dessert" },
1827
- * limit: 10
1828
- * });
1829
- * console.log(`Showing 10 of ${totalCount} dessert recipes`);
1830
- *
1831
- * // Use Prolog explicitly (legacy)
1832
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
229
+ * const post = await TestPost.findOne(perspective, { where: { id: someId } });
1833
230
  * ```
1834
231
  */
1835
- static async findAllAndCount(perspective, query = {}, useSurrealDB = true) {
1836
- if (useSurrealDB) {
1837
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
1838
- const result = await perspective.querySurrealDB(surrealQuery);
1839
- return await this.instancesFromSurrealResult(perspective, query, result);
1840
- }
1841
- else {
1842
- const prologQuery = await this.queryToProlog(perspective, query);
1843
- const result = await perspective.infer(prologQuery);
1844
- return await this.instancesFromPrologResult(perspective, query, result);
1845
- }
232
+ static async findOne(perspective, query = {}) {
233
+ return ops.findOne(this, perspective, query);
1846
234
  }
1847
235
  /**
1848
- * Helper function for pagination with explicit page size and number.
1849
- *
1850
- * @param perspective - The perspective to search in
1851
- * @param pageSize - Number of items per page
1852
- * @param pageNumber - Which page to retrieve (1-based)
1853
- * @param query - Optional additional query parameters
1854
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1855
- * @returns Paginated results with metadata
236
+ * Like `findAll` but also returns the unfiltered total count (useful for pagination UI).
1856
237
  *
1857
238
  * @example
1858
239
  * ```typescript
1859
- * const page = await Recipe.paginate(perspective, 10, 1, {
1860
- * where: { category: "Main Course" }
1861
- * });
1862
- * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
1863
- *
1864
- * // Use Prolog explicitly (legacy)
1865
- * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
240
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, { limit: 10 });
241
+ * console.log(`Showing ${results.length} of ${totalCount}`);
1866
242
  * ```
1867
243
  */
1868
- static async paginate(perspective, pageSize, pageNumber, query, useSurrealDB = true) {
1869
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1870
- if (useSurrealDB) {
1871
- const surrealQuery = await this.queryToSurrealQL(perspective, paginationQuery);
1872
- const result = await perspective.querySurrealDB(surrealQuery);
1873
- const { results, totalCount } = await this.instancesFromSurrealResult(perspective, paginationQuery, result);
1874
- return { results, totalCount, pageSize, pageNumber };
1875
- }
1876
- else {
1877
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
1878
- const result = await perspective.infer(prologQuery);
1879
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
1880
- return { results, totalCount, pageSize, pageNumber };
1881
- }
1882
- }
1883
- static async countQueryToProlog(perspective, query = {}, modelClassName) {
1884
- const { source, where } = query;
1885
- const className = modelClassName || (await this.getClassName(perspective));
1886
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
1887
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
1888
- const fullQuery = `
1889
- findall([Base, Properties, Collections, Timestamp, Author], (
1890
- subject_class("${className}", SubjectClass),
1891
- instance(SubjectClass, Base),
1892
- ${instanceQueries.filter((q) => q).join(", ")}
1893
- ), UnsortedInstances),
1894
- ${resultSetQueries.filter((q) => q).join(", ")}
1895
- `;
1896
- return fullQuery;
1897
- }
1898
- /**
1899
- * Generates a SurrealQL COUNT query for the model.
1900
- *
1901
- * @param perspective - The perspective context
1902
- * @param query - Query parameters to filter the count
1903
- * @returns SurrealQL COUNT query string
1904
- *
1905
- * @private
1906
- */
1907
- static async countQueryToSurrealQL(perspective, query) {
1908
- // Use the same query as the main query (with GROUP BY), just without LIMIT/OFFSET
1909
- // We'll count the number of rows returned (one row per source)
1910
- const countQuery = { ...query };
1911
- delete countQuery.limit;
1912
- delete countQuery.offset;
1913
- return await this.queryToSurrealQL(perspective, countQuery);
244
+ static async findAllAndCount(perspective, query = {}) {
245
+ return ops.findAllAndCount(this, perspective, query);
1914
246
  }
1915
247
  /**
1916
- * Gets a count of all matching instances.
1917
- *
1918
- * @param perspective - The perspective to search in
1919
- * @param query - Optional query parameters to filter results
1920
- * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1921
- * @returns Total count of matching entities
248
+ * Fetches a single page of results (`pageNumber` is 1-based).
1922
249
  *
1923
250
  * @example
1924
251
  * ```typescript
1925
- * const totalRecipes = await Recipe.count(perspective);
1926
- * const activeRecipes = await Recipe.count(perspective, {
1927
- * where: { status: "active" }
1928
- * });
1929
- *
1930
- * // Use Prolog explicitly (legacy)
1931
- * const countProlog = await Recipe.count(perspective, {}, false);
252
+ * const page = await Recipe.paginate(perspective, 10, 1);
253
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} items`);
1932
254
  * ```
1933
255
  */
1934
- static async count(perspective, query = {}, useSurrealDB = true) {
1935
- if (useSurrealDB) {
1936
- const surrealQuery = await this.queryToSurrealQL(perspective, query);
1937
- const result = await perspective.querySurrealDB(surrealQuery);
1938
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
1939
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
1940
- // This ensures count() returns the same number as findAll().length
1941
- const { totalCount } = await this.instancesFromSurrealResult(perspective, query, result);
1942
- return totalCount;
1943
- }
1944
- else {
1945
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
1946
- return result?.[0]?.TotalCount || 0;
1947
- }
1948
- }
1949
- async setProperty(key, value, batchId) {
1950
- // Phase 1: Use metadata instead of Prolog queries
1951
- const metadata = this.getPropertyMetadata(key);
1952
- if (!metadata) {
1953
- console.warn(`Property "${key}" has no metadata, skipping`);
1954
- return;
1955
- }
1956
- // Generate actions from metadata (replaces Prolog query)
1957
- const actions = this.generatePropertySetterAction(key, metadata);
1958
- // Get resolve language from metadata (replaces Prolog query)
1959
- let resolveLanguage = metadata.resolveLanguage;
1960
- // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
1961
- if (value === undefined || value === null || value === "") {
1962
- return;
1963
- }
1964
- if (resolveLanguage) {
1965
- value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
1966
- }
1967
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
256
+ static async paginate(perspective, pageSize, pageNumber, query) {
257
+ return ops.paginate(this, perspective, pageSize, pageNumber, query ?? {});
1968
258
  }
1969
- async setCollectionSetter(key, value, batchId) {
1970
- // Phase 1: Use metadata instead of Prolog queries
1971
- const metadata = this.getCollectionMetadata(key);
1972
- if (!metadata) {
1973
- console.warn(`Collection "${key}" has no metadata, skipping`);
1974
- return;
1975
- }
1976
- // Generate actions from metadata (replaces Prolog query)
1977
- const actions = this.generateCollectionAction(key, 'setter');
1978
- if (value != null) {
1979
- if (Array.isArray(value)) {
1980
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })), batchId);
1981
- }
1982
- else {
1983
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
1984
- }
1985
- }
1986
- }
1987
- async setCollectionAdder(key, value, batchId) {
1988
- // Phase 1: Use metadata instead of Prolog queries
1989
- const metadata = this.getCollectionMetadata(key);
1990
- if (!metadata) {
1991
- console.warn(`Collection "${key}" has no metadata, skipping`);
1992
- return;
1993
- }
1994
- // Generate actions from metadata (replaces Prolog query)
1995
- const actions = this.generateCollectionAction(key, 'adder');
1996
- if (value != null) {
1997
- if (Array.isArray(value)) {
1998
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
1999
- }
2000
- else {
2001
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2002
- }
2003
- }
259
+ /**
260
+ * Generates a SurrealQL COUNT query for this model.
261
+ * @private
262
+ */
263
+ static async countQueryToSurrealQL(perspective, query) {
264
+ return ops.countQueryToSurrealQL(this, perspective, query);
2004
265
  }
2005
- async setCollectionRemover(key, value, batchId) {
2006
- // Phase 1: Use metadata instead of Prolog queries
2007
- const metadata = this.getCollectionMetadata(key);
2008
- if (!metadata) {
2009
- console.warn(`Collection "${key}" has no metadata, skipping`);
2010
- return;
2011
- }
2012
- // Generate actions from metadata (replaces Prolog query)
2013
- const actions = this.generateCollectionAction(key, 'remover');
2014
- if (value != null) {
2015
- if (Array.isArray(value)) {
2016
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value: v }], batchId)));
2017
- }
2018
- else {
2019
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), [{ name: "value", value }], batchId);
2020
- }
2021
- }
266
+ /** Returns the count of instances matching `query`. */
267
+ static async count(perspective, query = {}) {
268
+ return ops.count(this, perspective, query);
2022
269
  }
2023
270
  /**
2024
- * Saves the model instance to the perspective.
2025
- * Creates a new instance with the base expression and links it to the source.
271
+ * Persists the instance (create if new, update if existing).
2026
272
  *
2027
- * @param batchId - Optional batch ID for batch operations
2028
- * @throws Will throw if instance creation, linking, or updating fails
273
+ * @param batchId - When provided the caller must call `perspective.commitBatch(batchId)`
2029
274
  *
2030
275
  * @example
2031
276
  * ```typescript
2032
277
  * const recipe = new Recipe(perspective);
2033
278
  * recipe.name = "Spaghetti";
2034
- * recipe.ingredients = ["pasta", "tomato sauce"];
2035
- * await recipe.save();
2036
- *
2037
- * // Or with batch operations:
2038
- * const batchId = await perspective.createBatch();
2039
- * await recipe.save(batchId);
2040
- * await perspective.commitBatch(batchId);
279
+ * await recipe.save(); // create
280
+ * recipe.name = "Bolognese";
281
+ * await recipe.save(); // update (detected automatically)
2041
282
  * ```
2042
283
  */
2043
284
  async save(batchId) {
2044
- // We use createSubject's initialValues to set properties (but not collections)
2045
- // We then later use innerUpdate to set collections
2046
- let batchCreatedHere = false;
2047
- if (!batchId) {
2048
- batchId = await this.perspective.createBatch();
2049
- batchCreatedHere = true;
2050
- }
2051
- // First filter out the properties that are not collections (arrays)
2052
- const initialValues = {};
2053
- for (const [key, value] of Object.entries(this)) {
2054
- if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
2055
- initialValues[key] = value;
2056
- }
2057
- }
2058
- // Get the class name instead of passing the instance to avoid Prolog query generation
2059
- const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
2060
- // Create the subject with the initial values
2061
- await this.perspective.createSubject(className, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
2062
- // Link the subject to the source
2063
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
2064
- // Set collections
2065
- await this.innerUpdate(false, batchId);
2066
- // If we got a batchId passed in, we let the caller decide when to commit.
2067
- // But then we can call getData() since the instance won't exist in the perspective
2068
- // until the bacht is committedl
2069
- if (batchCreatedHere) {
2070
- await this.perspective.commitBatch(batchId);
2071
- await this.getData();
2072
- }
2073
- }
2074
- cleanCopy() {
2075
- const cleanCopy = {};
2076
- const props = Object.entries(this);
2077
- for (const [key, value] of props) {
2078
- if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
2079
- cleanCopy[key] = value;
2080
- }
2081
- }
2082
- return cleanCopy;
2083
- }
2084
- async innerUpdate(setProperties = true, batchId) {
2085
- __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
2086
- const entries = Object.entries(this);
2087
- for (const [key, value] of entries) {
2088
- if (value !== undefined && value !== null) {
2089
- if (value?.action) {
2090
- switch (value.action) {
2091
- case "setter":
2092
- await this.setCollectionSetter(key, value.value, batchId);
2093
- break;
2094
- case "adder":
2095
- await this.setCollectionAdder(key, value.value, batchId);
2096
- break;
2097
- case "remover":
2098
- await this.setCollectionRemover(key, value.value, batchId);
2099
- break;
2100
- default:
2101
- await this.setCollectionSetter(key, value.value, batchId);
2102
- break;
2103
- }
2104
- }
2105
- else if (Array.isArray(value)) {
2106
- // Handle all arrays as collections, including empty ones (which clears the collection)
2107
- await this.setCollectionSetter(key, value, batchId);
2108
- }
2109
- else if (value !== undefined && value !== null && value !== "") {
2110
- if (setProperties) {
2111
- // Check if this is a collection property (has collection metadata)
2112
- const collMetadata = this.getCollectionMetadata(key);
2113
- if (collMetadata) {
2114
- // Skip - it's a collection, not a regular property
2115
- continue;
2116
- }
2117
- await this.setProperty(key, value, batchId);
2118
- }
2119
- }
2120
- }
2121
- }
2122
- }
2123
- /**
2124
- * Updates the model instance's properties and collections.
2125
- *
2126
- * @param batchId - Optional batch ID for batch operations
2127
- * @throws Will throw if property setting or collection updates fail
2128
- *
2129
- * @example
2130
- * ```typescript
2131
- * const recipe = await Recipe.findAll(perspective)[0];
2132
- * recipe.rating = 5;
2133
- * recipe.ingredients.push("garlic");
2134
- * await recipe.update();
2135
- *
2136
- * // Or with batch operations:
2137
- * const batchId = await perspective.createBatch();
2138
- * await recipe.update(batchId);
2139
- * await perspective.commitBatch(batchId);
2140
- * ```
2141
- */
2142
- async update(batchId) {
2143
- await this.innerUpdate(true, batchId);
2144
- await this.getData();
285
+ await mutation.saveInstance(this._mutationContext(), batchId, this._savedOnce);
286
+ this._savedOnce = true;
2145
287
  }
2146
288
  /**
2147
- * Gets the model instance with all properties and collections populated.
289
+ * Gets the model instance with all properties and relations populated.
2148
290
  *
2149
291
  * @returns The populated model instance
2150
292
  * @throws Will throw if data retrieval fails
@@ -2156,822 +298,93 @@ WHERE ${whereConditions.join(' AND ')}
2156
298
  * console.log(recipe.name, recipe.ingredients);
2157
299
  * ```
2158
300
  */
2159
- async get() {
2160
- __classPrivateFieldSet(this, _Ad4mModel_subjectClassName, await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").stringOrTemplateObjectToSubjectClassName(this.cleanCopy()), "f");
2161
- return await this.getData();
301
+ async get(include) {
302
+ const metadata = this.constructor.getModelMetadata();
303
+ return fetchInstanceData(this, this._perspective, this._id, metadata, include);
2162
304
  }
2163
305
  /**
2164
- * Deletes the model instance from the perspective.
2165
- *
2166
- * @param batchId - Optional batch ID for batch operations
2167
- * @throws Will throw if removal fails
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.
2168
310
  *
2169
311
  * @example
2170
- * ```typescript
2171
- * const recipe = await Recipe.findAll(perspective)[0];
2172
- * await recipe.delete();
312
+ * await vote.delete();
2173
313
  *
2174
- * // Or with batch operations:
2175
- * const batchId = await perspective.createBatch();
2176
- * await recipe.delete(batchId);
2177
- * await perspective.commitBatch(batchId);
2178
- * ```
314
+ * @param batchId - Optional batch identifier for grouping removals.
2179
315
  */
2180
316
  async delete(batchId) {
2181
- await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), 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);
322
+ }
323
+ await this._perspective.removeSubject(this, this._id, batchId);
2182
324
  }
2183
325
  /**
2184
- * Creates a query builder for fluent query construction.
2185
- *
2186
- * @param perspective - The perspective to query
2187
- * @param query - Optional initial query parameters
2188
- * @returns A new query builder instance
326
+ * Returns a fluent query builder for this model.
2189
327
  *
2190
328
  * @example
2191
329
  * ```typescript
2192
- * const recipes = await Recipe.query(perspective)
330
+ * const top5 = await Recipe.query(perspective)
2193
331
  * .where({ category: "Dessert" })
2194
332
  * .order({ rating: "DESC" })
2195
333
  * .limit(5)
2196
334
  * .run();
2197
- *
2198
- * // With real-time updates
2199
- * await Recipe.query(perspective)
2200
- * .where({ status: "cooking" })
2201
- * .subscribe(recipes => {
2202
- * console.log("Currently cooking:", recipes);
2203
- * });
2204
335
  * ```
2205
336
  */
2206
337
  static query(perspective, query) {
2207
338
  return new ModelQueryBuilder(perspective, this, query);
2208
339
  }
2209
340
  /**
2210
- * Creates an Ad4mModel class from a JSON Schema definition.
2211
- *
2212
- * @description
2213
- * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
2214
- * enabling integration with systems that use JSON Schema for type definitions.
2215
- *
2216
- * The method follows a cascading approach for determining predicates:
2217
- * 1. Explicit configuration in options parameter (highest precedence)
2218
- * 2. x-ad4m metadata in the JSON Schema
2219
- * 3. Inference from schema title and property names
2220
- * 4. Error if no namespace can be determined
2221
- *
2222
- * @example
2223
- * ```typescript
2224
- * // With explicit configuration
2225
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
2226
- * name: "Person",
2227
- * namespace: "person://",
2228
- * resolveLanguage: "literal"
2229
- * });
2230
- *
2231
- * // With property mapping
2232
- * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
2233
- * name: "Contact",
2234
- * namespace: "contact://",
2235
- * propertyMapping: {
2236
- * "name": "foaf://name",
2237
- * "email": "foaf://mbox"
2238
- * }
2239
- * });
2240
- *
2241
- * // With x-ad4m metadata in schema
2242
- * const schema = {
2243
- * "title": "Product",
2244
- * "x-ad4m": { "namespace": "product://" },
2245
- * "properties": {
2246
- * "name": {
2247
- * "type": "string",
2248
- * "x-ad4m": { "through": "product://title" }
2249
- * }
2250
- * }
2251
- * };
2252
- * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
2253
- * ```
2254
- *
2255
- * @param schema - JSON Schema definition
2256
- * @param options - Configuration options
2257
- * @returns Generated Ad4mModel subclass
2258
- * @throws Error when namespace cannot be inferred
2259
- */
2260
- static fromJSONSchema(schema, options) {
2261
- // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
2262
- if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
2263
- 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").');
2264
- }
2265
- // Determine namespace with cascading precedence
2266
- const namespace = this.determineNamespace(schema, options);
2267
- // Create the dynamic class
2268
- const DynamicModelClass = class extends Ad4mModel {
2269
- };
2270
- // Set up class metadata
2271
- if (!options.name || options.name.trim() === '') {
2272
- throw new Error("options.name is required and cannot be empty");
2273
- }
2274
- DynamicModelClass.className = options.name;
2275
- DynamicModelClass.prototype.className = options.name;
2276
- // Generate properties and collections metadata
2277
- const properties = {};
2278
- const collections = {};
2279
- if (schema.properties) {
2280
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
2281
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
2282
- const isRequired = schema.required?.includes(propertyName) || false;
2283
- const propertyType = normalizeSchemaType(propertySchema.type);
2284
- const isArray = isArrayType(propertySchema);
2285
- if (isArray) {
2286
- // Handle arrays as collections
2287
- // Store the singular form as the collection key since SDNA generation expects singular
2288
- collections[propertyName] = {
2289
- through: predicate,
2290
- local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
2291
- };
2292
- // Define the property on prototype
2293
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
2294
- configurable: true,
2295
- writable: true,
2296
- value: []
2297
- });
2298
- // Add collection methods
2299
- const adderName = `add${capitalize(propertyName)}`;
2300
- const removerName = `remove${capitalize(propertyName)}`;
2301
- const setterName = `setCollection${capitalize(propertyName)}`;
2302
- DynamicModelClass.prototype[adderName] = function () {
2303
- // Placeholder function for SDNA generation
2304
- };
2305
- DynamicModelClass.prototype[removerName] = function () {
2306
- // Placeholder function for SDNA generation
2307
- };
2308
- DynamicModelClass.prototype[setterName] = function () {
2309
- // Placeholder function for SDNA generation
2310
- };
2311
- }
2312
- else {
2313
- // Handle regular properties
2314
- let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
2315
- // If no specific resolveLanguage for this property, use the global one
2316
- if (!resolveLanguage && options.resolveLanguage) {
2317
- resolveLanguage = options.resolveLanguage;
2318
- }
2319
- const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
2320
- const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
2321
- let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
2322
- // Handle nested objects by serializing to JSON
2323
- if (isObjectType(propertySchema) && !resolveLanguage) {
2324
- resolveLanguage = 'literal';
2325
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
2326
- }
2327
- // Ensure numeric properties use literal language for correct typing
2328
- if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
2329
- resolveLanguage = 'literal';
2330
- }
2331
- // If property is required, ensure it has an initial value
2332
- if (isRequired && !initial) {
2333
- if (isObjectType(propertySchema)) {
2334
- initial = 'literal://json:{}';
2335
- }
2336
- else {
2337
- initial = "ad4m://undefined";
2338
- }
2339
- }
2340
- properties[propertyName] = {
2341
- through: predicate,
2342
- required: isRequired,
2343
- writable: writable,
2344
- ...(resolveLanguage && { resolveLanguage }),
2345
- ...(local !== undefined && { local }),
2346
- ...(initial && { initial })
2347
- };
2348
- // Define the property on prototype
2349
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
2350
- configurable: true,
2351
- writable: true,
2352
- value: this.getDefaultValueForType(propertyType)
2353
- });
2354
- // Add setter function if writable
2355
- if (writable) {
2356
- const setterName = propertyNameToSetterName(propertyName);
2357
- DynamicModelClass.prototype[setterName] = function () {
2358
- // This is a placeholder function that the SDNA generation looks for
2359
- // The actual setter logic is handled by the Ad4mModel base class
2360
- };
2361
- }
2362
- }
2363
- }
2364
- }
2365
- // Validate that at least one property has an initial value (needed for valid SDNA constructor)
2366
- // Collections don't create constructor actions, only properties with initial values do
2367
- const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
2368
- if (!hasPropertyWithInitial) {
2369
- // If no properties have initial values, add a type identifier automatically
2370
- const typeProperty = `ad4m://type`;
2371
- let typeValue;
2372
- if (namespace.includes('://')) {
2373
- const [scheme, rest] = namespace.split('://');
2374
- const path = (rest || '').replace(/\/+$/, '');
2375
- if (path) {
2376
- typeValue = `${scheme}://${path}/instance`;
2377
- }
2378
- else {
2379
- typeValue = `${scheme}://instance`;
2380
- }
2381
- }
2382
- else {
2383
- const path = namespace.replace(/\/+$/, '');
2384
- typeValue = `${path}/instance`;
2385
- }
2386
- properties['__ad4m_type'] = {
2387
- through: typeProperty,
2388
- required: true,
2389
- writable: false,
2390
- initial: typeValue,
2391
- flag: true
2392
- };
2393
- // Add the type property to the prototype
2394
- Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
2395
- configurable: true,
2396
- writable: false,
2397
- value: typeValue
2398
- });
2399
- console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
2400
- }
2401
- // Attach metadata to prototype
2402
- DynamicModelClass.prototype.__properties = properties;
2403
- DynamicModelClass.prototype.__collections = collections;
2404
- // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
2405
- DynamicModelClass.prototype.__jsonSchema = schema;
2406
- DynamicModelClass.prototype.__jsonSchemaOptions = options;
2407
- // Apply the ModelOptions decorator to set up the generateSDNA method
2408
- const ModelOptionsDecorator = ModelOptions({ name: options.name });
2409
- ModelOptionsDecorator(DynamicModelClass);
2410
- return DynamicModelClass;
2411
- }
2412
- /**
2413
- * Determines the namespace for predicates using cascading precedence
2414
- */
2415
- static determineNamespace(schema, options) {
2416
- // 1. Explicit namespace in options (highest precedence)
2417
- if (options.namespace) {
2418
- return options.namespace;
2419
- }
2420
- // 2. x-ad4m metadata in schema
2421
- if (schema["x-ad4m"]?.namespace) {
2422
- return schema["x-ad4m"].namespace;
2423
- }
2424
- // 3. Infer from schema title
2425
- if (schema.title) {
2426
- return `${schema.title.toLowerCase()}://`;
2427
- }
2428
- // 4. Try to extract from $id if it's a URL
2429
- if (schema.$id) {
2430
- try {
2431
- const url = new URL(schema.$id);
2432
- const pathParts = url.pathname.split('/').filter(p => p);
2433
- if (pathParts.length > 0) {
2434
- const lastPart = pathParts[pathParts.length - 1];
2435
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
2436
- return `${baseName.toLowerCase()}://`;
2437
- }
2438
- }
2439
- catch {
2440
- // If $id is not a valid URL, continue to error
2441
- }
2442
- }
2443
- // 5. Error if no namespace can be determined
2444
- throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
2445
- - options.namespace
2446
- - schema["x-ad4m"].namespace
2447
- - schema.title
2448
- - valid schema.$id`);
2449
- }
2450
- /**
2451
- * Determines the predicate for a specific property using cascading precedence
2452
- */
2453
- static determinePredicate(schema, propertyName, propertySchema, namespace, options) {
2454
- // 1. Explicit property mapping (highest precedence)
2455
- if (options.propertyMapping?.[propertyName]) {
2456
- return options.propertyMapping[propertyName];
2457
- }
2458
- // 2. x-ad4m metadata in property schema
2459
- if (propertySchema["x-ad4m"]?.through) {
2460
- return propertySchema["x-ad4m"].through;
2461
- }
2462
- // 3. Generate from namespace + property name
2463
- if (options.predicateTemplate) {
2464
- const normalizedNs = normalizeNamespaceString(namespace);
2465
- const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
2466
- const nsNoScheme = rest || '';
2467
- return options.predicateTemplate
2468
- .replace('${namespace}', nsNoScheme)
2469
- .replace('${scheme}', scheme)
2470
- .replace('${ns}', nsNoScheme)
2471
- .replace('${title}', schema.title || '')
2472
- .replace('${property}', propertyName);
2473
- }
2474
- // 4. Custom predicate generator
2475
- if (options.predicateGenerator) {
2476
- return options.predicateGenerator(schema.title || '', propertyName);
2477
- }
2478
- // 5. Default: namespace + property name
2479
- const normalizedNs = normalizeNamespaceString(namespace);
2480
- if (normalizedNs.includes('://')) {
2481
- // For namespaces like "product://", append property directly
2482
- return `${normalizedNs}${propertyName}`;
2483
- }
2484
- else {
2485
- return `${normalizedNs}://${propertyName}`;
2486
- }
2487
- }
2488
- /**
2489
- * Gets property-specific options using cascading precedence
2490
- */
2491
- static getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
2492
- // 1. Property-specific options
2493
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
2494
- return options.propertyOptions[propertyName][optionName];
2495
- }
2496
- // 2. x-ad4m metadata in property
2497
- if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
2498
- return propertySchema["x-ad4m"][optionName];
2499
- }
2500
- // 3. Global option
2501
- if (options[optionName] !== undefined) {
2502
- return options[optionName];
2503
- }
2504
- // 4. Default value
2505
- return defaultValue;
2506
- }
2507
- /**
2508
- * Gets default value for a JSON Schema type
2509
- */
2510
- static getDefaultValueForType(type) {
2511
- switch (type) {
2512
- case 'string': return '';
2513
- case 'number': return 0;
2514
- case 'integer': return 0;
2515
- case 'boolean': return false;
2516
- case 'array': return [];
2517
- case 'object': return {};
2518
- default: return '';
2519
- }
2520
- }
2521
- }
2522
- _Ad4mModel_baseExpression = new WeakMap(), _Ad4mModel_subjectClassName = new WeakMap(), _Ad4mModel_source = new WeakMap(), _Ad4mModel_perspective = new WeakMap();
2523
- Ad4mModel.classNamesByClass = new WeakMap();
2524
- /** Query builder for Ad4mModel queries.
2525
- * Allows building queries with a fluent interface and either running them once
2526
- * or subscribing to updates.
2527
- *
2528
- * @example
2529
- * ```typescript
2530
- * const builder = Recipe.query(perspective)
2531
- * .where({ category: "Dessert" })
2532
- * .order({ rating: "DESC" })
2533
- * .limit(10);
2534
- *
2535
- * // Run once
2536
- * const recipes = await builder.run();
2537
- *
2538
- * // Or subscribe to updates
2539
- * await builder.subscribe(recipes => {
2540
- * console.log("Updated recipes:", recipes);
2541
- * });
2542
- * ```
2543
- */
2544
- export class ModelQueryBuilder {
2545
- constructor(perspective, ctor, query) {
2546
- this.queryParams = {};
2547
- this.modelClassName = null;
2548
- this.useSurrealDBFlag = true;
2549
- this.perspective = perspective;
2550
- this.ctor = ctor;
2551
- if (query)
2552
- this.queryParams = query;
2553
- }
2554
- /**
2555
- * Disposes of the current subscription if one exists.
2556
- *
2557
- * This method:
2558
- * 1. Stops the keepalive signals to the subscription
2559
- * 2. Unsubscribes from GraphQL subscription updates
2560
- * 3. Notifies the backend to clean up subscription resources
2561
- * 4. Clears the subscription reference
2562
- *
2563
- * You should call this method when you're done with a subscription
2564
- * to prevent memory leaks and ensure proper cleanup.
2565
- */
2566
- dispose() {
2567
- if (this.currentSubscription) {
2568
- this.currentSubscription.dispose();
2569
- this.currentSubscription = undefined;
2570
- }
2571
- }
2572
- /**
2573
- * Adds where conditions to the query.
2574
- *
2575
- * @param conditions - The conditions to filter by
2576
- * @returns The query builder for chaining
2577
- *
2578
- * @example
2579
- * ```typescript
2580
- * .where({
2581
- * category: "Dessert",
2582
- * rating: { gt: 4 },
2583
- * tags: ["vegan", "quick"],
2584
- * published: true
2585
- * })
2586
- * ```
2587
- */
2588
- where(conditions) {
2589
- this.queryParams.where = conditions;
2590
- return this;
2591
- }
2592
- /**
2593
- * Sets the order for the query results.
2594
- *
2595
- * @param orderBy - The ordering criteria
2596
- * @returns The query builder for chaining
2597
- *
2598
- * @example
2599
- * ```typescript
2600
- * .order({ createdAt: "DESC" })
2601
- * ```
2602
- */
2603
- order(orderBy) {
2604
- this.queryParams.order = orderBy;
2605
- return this;
2606
- }
2607
- /**
2608
- * Sets the maximum number of results to return.
2609
- *
2610
- * @param limit - Maximum number of results
2611
- * @returns The query builder for chaining
2612
- *
2613
- * @example
2614
- * ```typescript
2615
- * .limit(10)
2616
- * ```
2617
- */
2618
- limit(limit) {
2619
- this.queryParams.limit = limit;
2620
- return this;
2621
- }
2622
- /**
2623
- * Sets the number of results to skip.
2624
- *
2625
- * @param offset - Number of results to skip
2626
- * @returns The query builder for chaining
2627
- *
2628
- * @example
2629
- * ```typescript
2630
- * .offset(20) // Skip first 20 results
2631
- * ```
2632
- */
2633
- offset(offset) {
2634
- this.queryParams.offset = offset;
2635
- return this;
2636
- }
2637
- /**
2638
- * Sets the source filter for the query.
2639
- *
2640
- * @param source - The source to filter by
2641
- * @returns The query builder for chaining
2642
- *
2643
- * @example
2644
- * ```typescript
2645
- * .source("ad4m://self")
2646
- * ```
2647
- */
2648
- source(source) {
2649
- this.queryParams.source = source;
2650
- return this;
2651
- }
2652
- /**
2653
- * Specifies which properties to include in the results.
2654
- *
2655
- * @param properties - Array of property names to include
2656
- * @returns The query builder for chaining
2657
- *
2658
- * @example
2659
- * ```typescript
2660
- * .properties(["name", "description", "rating"])
2661
- * ```
2662
- */
2663
- properties(properties) {
2664
- this.queryParams.properties = properties;
2665
- return this;
2666
- }
2667
- /**
2668
- * Specifies which collections to include in the results.
2669
- *
2670
- * @param collections - Array of collection names to include
2671
- * @returns The query builder for chaining
2672
- *
2673
- * @example
2674
- * ```typescript
2675
- * .collections(["ingredients", "steps"])
2676
- * ```
2677
- */
2678
- collections(collections) {
2679
- this.queryParams.collections = collections;
2680
- return this;
2681
- }
2682
- overrideModelClassName(className) {
2683
- this.modelClassName = className;
2684
- return this;
2685
- }
2686
- /**
2687
- * Enables or disables SurrealDB query path.
2688
- *
2689
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
2690
- * @returns The query builder for chaining
2691
- *
2692
- * @example
2693
- * ```typescript
2694
- * // Use SurrealDB (default)
2695
- * const recipes = await Recipe.query(perspective)
2696
- * .where({ category: "Dessert" })
2697
- * .useSurrealDB(true)
2698
- * .get();
2699
- *
2700
- * // Use Prolog (legacy)
2701
- * const recipesProlog = await Recipe.query(perspective)
2702
- * .where({ category: "Dessert" })
2703
- * .useSurrealDB(false)
2704
- * .get();
2705
- * ```
2706
- *
2707
- * @remarks
2708
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
2709
- * if useSurrealDB(true) is set (default).
2710
- */
2711
- useSurrealDB(enabled = true) {
2712
- this.useSurrealDBFlag = enabled;
2713
- return this;
2714
- }
2715
- /**
2716
- * Executes the query once and returns the results.
2717
- *
2718
- * @returns Array of matching entities
2719
- *
2720
- * @example
2721
- * ```typescript
2722
- * const recipes = await Recipe.query(perspective)
2723
- * .where({ category: "Dessert" })
2724
- * .get();
2725
- * ```
2726
- */
2727
- async get() {
2728
- if (this.useSurrealDBFlag) {
2729
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
2730
- const result = await this.perspective.querySurrealDB(surrealQuery);
2731
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2732
- return results;
2733
- }
2734
- else {
2735
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
2736
- const result = await this.perspective.infer(query);
2737
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
2738
- return results;
2739
- }
2740
- }
2741
- /**
2742
- * Subscribes to the query and receives updates when results change.
2743
- *
2744
- * This method:
2745
- * 1. Creates and initializes a SurrealDB live query subscription (default)
2746
- * 2. Sets up the callback to process future updates
2747
- * 3. Returns the initial results immediately
2748
- *
2749
- * Remember to call dispose() when you're done with the subscription
2750
- * to clean up resources.
2751
- *
2752
- * @param callback - Function to call with updated results
2753
- * @returns Initial results array
2754
- *
2755
- * @example
2756
- * ```typescript
2757
- * const builder = Recipe.query(perspective)
2758
- * .where({ status: "cooking" });
2759
- *
2760
- * const initialRecipes = await builder.subscribe(recipes => {
2761
- * console.log("Updated recipes:", recipes);
2762
- * });
2763
- *
2764
- * // When done with subscription:
2765
- * builder.dispose();
2766
- * ```
2767
- *
2768
- * @remarks
2769
- * By default, this uses SurrealDB live queries for real-time updates.
2770
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
2771
- */
2772
- async subscribe(callback) {
2773
- // Clean up any existing subscription
2774
- this.dispose();
2775
- if (this.useSurrealDBFlag) {
2776
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
2777
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
2778
- const processResults = async (result) => {
2779
- // The result from live query subscription update (handled in PerspectiveInstance listener)
2780
- // is the new full set of results (because we re-query in Rust).
2781
- // So we just need to map it to instances.
2782
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2783
- callback(results);
2784
- };
2785
- this.currentSubscription.onResult(processResults);
2786
- // Process initial result
2787
- const { results } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
2788
- return results;
2789
- }
2790
- else {
2791
- // Note: Subscriptions currently only work with Prolog
2792
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
2793
- this.currentSubscription = await this.perspective.subscribeInfer(query);
2794
- const processResults = async (result) => {
2795
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
2796
- callback(results);
2797
- };
2798
- this.currentSubscription.onResult(processResults);
2799
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, this.currentSubscription.result);
2800
- return results;
2801
- }
2802
- }
2803
- /**
2804
- * Gets the total count of matching entities.
2805
- *
2806
- * @returns Total count
2807
- *
2808
- * @example
2809
- * ```typescript
2810
- * const totalDesserts = await Recipe.query(perspective)
2811
- * .where({ category: "Dessert" })
2812
- * .count();
2813
- * ```
2814
- */
2815
- async count() {
2816
- if (this.useSurrealDBFlag) {
2817
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
2818
- const result = await this.perspective.querySurrealDB(surrealQuery);
2819
- // Use instancesFromSurrealResult to apply JS-level filtering for advanced where conditions
2820
- // (e.g., gt, gte, lt, lte, between, contains on properties and author/timestamp)
2821
- // This ensures count() returns the same number as get().length
2822
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2823
- return totalCount;
2824
- }
2825
- else {
2826
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
2827
- const result = await this.perspective.infer(query);
2828
- return result?.[0]?.TotalCount || 0;
2829
- }
2830
- }
2831
- /**
2832
- * Subscribes to count updates for matching entities.
2833
- *
2834
- * This method:
2835
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
2836
- * 2. Sets up the callback to process future count updates
2837
- * 3. Returns the initial count immediately
2838
- *
2839
- * Remember to call dispose() when you're done with the subscription
2840
- * to clean up resources.
2841
- *
2842
- * @param callback - Function to call with updated count
2843
- * @returns Initial count
341
+ * Runs `callback` in an atomic batch; commits on success, aborts + rethrows on failure.
2844
342
  *
2845
343
  * @example
2846
344
  * ```typescript
2847
- * const builder = Recipe.query(perspective)
2848
- * .where({ status: "active" });
2849
- *
2850
- * const initialCount = await builder.countSubscribe(count => {
2851
- * console.log("Active items:", count);
345
+ * await Ad4mModel.transaction(perspective, async (tx) => {
346
+ * await post.save(tx.batchId);
347
+ * await comment.save(tx.batchId);
2852
348
  * });
2853
- *
2854
- * // When done with subscription:
2855
- * builder.dispose();
2856
349
  * ```
2857
- *
2858
- * @remarks
2859
- * By default, this uses SurrealDB live queries for real-time updates.
2860
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
2861
350
  */
2862
- async countSubscribe(callback) {
2863
- // Clean up any existing subscription
2864
- this.dispose();
2865
- if (this.useSurrealDBFlag) {
2866
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, this.queryParams);
2867
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
2868
- const processResults = async (result) => {
2869
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, result);
2870
- callback(totalCount);
2871
- };
2872
- this.currentSubscription.onResult(processResults);
2873
- const { totalCount } = await this.ctor.instancesFromSurrealResult(this.perspective, this.queryParams, this.currentSubscription.result);
2874
- return totalCount;
2875
- }
2876
- else {
2877
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
2878
- this.currentSubscription = await this.perspective.subscribeInfer(query);
2879
- const processResults = async (result) => {
2880
- const newCount = result?.[0]?.TotalCount || 0;
2881
- callback(newCount);
2882
- };
2883
- this.currentSubscription.onResult(processResults);
2884
- return this.currentSubscription.result?.[0]?.TotalCount || 0;
2885
- }
351
+ static async transaction(perspective, callback) {
352
+ return runTransaction(perspective, callback);
2886
353
  }
2887
354
  /**
2888
- * Gets a page of results with pagination metadata.
355
+ * Fires `callback` immediately with current results, then on every relevant perspective change.
2889
356
  *
2890
- * @param pageSize - Number of items per page
2891
- * @param pageNumber - Which page to retrieve (1-based)
2892
- * @returns Paginated results with metadata
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
2893
360
  *
2894
361
  * @example
2895
362
  * ```typescript
2896
- * const page = await Recipe.query(perspective)
2897
- * .where({ category: "Main" })
2898
- * .paginate(10, 1);
2899
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
363
+ * const sub = Post.subscribe(
364
+ * perspective,
365
+ * { where: { published: true }, debounce: 300 },
366
+ * (posts) => setPosts(posts),
367
+ * );
368
+ * sub.unsubscribe(); // in cleanup
2900
369
  * ```
2901
370
  */
2902
- async paginate(pageSize, pageNumber) {
2903
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
2904
- if (this.useSurrealDBFlag) {
2905
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
2906
- const result = await this.perspective.querySurrealDB(surrealQuery);
2907
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
2908
- return { results, totalCount, pageSize, pageNumber };
2909
- }
2910
- else {
2911
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
2912
- const result = await this.perspective.infer(prologQuery);
2913
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
2914
- return { results, totalCount, pageSize, pageNumber };
2915
- }
371
+ static subscribe(perspective, options, callback) {
372
+ return createSubscription((p, q) => this.findAll(p, q ?? {}), () => this.getModelMetadata(), perspective, options, callback, this);
2916
373
  }
2917
374
  /**
2918
- * Subscribes to paginated results updates.
2919
- *
2920
- * This method:
2921
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
2922
- * 2. Sets up the callback to process future page updates
2923
- * 3. Returns the initial page immediately
375
+ * Generates an `Ad4mModel` subclass from a JSON Schema definition.
2924
376
  *
2925
- * Remember to call dispose() when you're done with the subscription
2926
- * to clean up resources.
2927
- *
2928
- * @param pageSize - Number of items per page
2929
- * @param pageNumber - Which page to retrieve (1-based)
2930
- * @param callback - Function to call with updated pagination results
2931
- * @returns Initial pagination results
377
+ * Predicate resolution order: explicit options → `x-ad4m` in schema → inferred from title/names.
2932
378
  *
2933
379
  * @example
2934
380
  * ```typescript
2935
- * const builder = Recipe.query(perspective)
2936
- * .where({ category: "Main" });
2937
- *
2938
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
2939
- * console.log("Updated page:", page.results);
381
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
382
+ * name: "Person", namespace: "person://", resolveLanguage: "literal",
2940
383
  * });
2941
- *
2942
- * // When done with subscription:
2943
- * builder.dispose();
2944
384
  * ```
2945
- *
2946
- * @remarks
2947
- * By default, this uses SurrealDB live queries for real-time updates.
2948
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
2949
385
  */
2950
- async paginateSubscribe(pageSize, pageNumber, callback) {
2951
- // Clean up any existing subscription
2952
- this.dispose();
2953
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
2954
- if (this.useSurrealDBFlag) {
2955
- const surrealQuery = await this.ctor.queryToSurrealQL(this.perspective, paginationQuery);
2956
- this.currentSubscription = await this.perspective.subscribeSurrealDB(surrealQuery);
2957
- const processResults = async (result) => {
2958
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, result));
2959
- callback({ results, totalCount, pageSize, pageNumber });
2960
- };
2961
- this.currentSubscription.onResult(processResults);
2962
- const { results, totalCount } = (await this.ctor.instancesFromSurrealResult(this.perspective, paginationQuery, this.currentSubscription.result));
2963
- return { results, totalCount, pageSize, pageNumber };
2964
- }
2965
- else {
2966
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
2967
- this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
2968
- const processResults = async (r) => {
2969
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
2970
- callback({ results, totalCount, pageSize, pageNumber });
2971
- };
2972
- this.currentSubscription.onResult(processResults);
2973
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result));
2974
- return { results, totalCount, pageSize, pageNumber };
2975
- }
386
+ static fromJSONSchema(schema, options) {
387
+ return createModelFromJSONSchema(this, schema, options);
2976
388
  }
2977
389
  }
390
+ Ad4mModel.classNamesByClass = new WeakMap();