@coasys/ad4m 0.10.0 → 0.10.1-multi-user-1

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 (72) hide show
  1. package/lib/index.cjs +3730 -906
  2. package/lib/index.js +3722 -902
  3. package/lib/src/Ad4mClient.js +2 -1
  4. package/lib/src/Literal.js +4 -1
  5. package/lib/src/agent/Agent.d.ts +12 -0
  6. package/lib/src/agent/Agent.js +48 -0
  7. package/lib/src/agent/AgentClient.d.ts +3 -1
  8. package/lib/src/agent/AgentClient.js +23 -0
  9. package/lib/src/ai/AIClient.d.ts +8 -2
  10. package/lib/src/ai/AIClient.js +25 -14
  11. package/lib/src/ai/AIResolver.d.ts +25 -6
  12. package/lib/src/ai/AIResolver.js +102 -18
  13. package/lib/src/index.d.ts +4 -3
  14. package/lib/src/index.js +4 -3
  15. package/lib/src/language/Language.d.ts +12 -1
  16. package/lib/src/model/Ad4mModel.d.ts +622 -0
  17. package/lib/src/model/Ad4mModel.js +1118 -0
  18. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  19. package/lib/src/{subject → model}/Subject.js +18 -18
  20. package/lib/src/model/decorators.d.ts +502 -0
  21. package/lib/src/model/decorators.js +683 -0
  22. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodClient.js +13 -10
  24. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  25. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  26. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  27. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +73 -0
  28. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  29. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  30. package/lib/src/perspectives/PerspectiveClient.d.ts +23 -11
  31. package/lib/src/perspectives/PerspectiveClient.js +147 -51
  32. package/lib/src/perspectives/PerspectiveProxy.d.ts +494 -54
  33. package/lib/src/perspectives/PerspectiveProxy.js +684 -67
  34. package/lib/src/perspectives/PerspectiveResolver.d.ts +24 -9
  35. package/lib/src/perspectives/PerspectiveResolver.js +151 -46
  36. package/lib/src/runtime/RuntimeClient.d.ts +11 -2
  37. package/lib/src/runtime/RuntimeClient.js +94 -0
  38. package/lib/src/runtime/RuntimeResolver.d.ts +36 -1
  39. package/lib/src/runtime/RuntimeResolver.js +193 -0
  40. package/lib/src/schema.gql +65 -16
  41. package/lib/src/typeDefs.js +65 -16
  42. package/package.json +4 -3
  43. package/src/Ad4mClient.test.ts +51 -19
  44. package/src/Ad4mClient.ts +3 -1
  45. package/src/Literal.ts +4 -1
  46. package/src/agent/Agent.ts +36 -0
  47. package/src/agent/AgentClient.ts +30 -0
  48. package/src/ai/AIClient.ts +35 -14
  49. package/src/ai/AIResolver.ts +78 -16
  50. package/src/index.ts +4 -3
  51. package/src/language/Language.ts +16 -4
  52. package/src/model/Ad4mModel.ts +1279 -0
  53. package/src/{subject → model}/Subject.ts +16 -16
  54. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  55. package/src/neighbourhood/NeighbourhoodClient.ts +13 -10
  56. package/src/neighbourhood/NeighbourhoodProxy.test.ts +100 -0
  57. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  58. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  59. package/src/perspectives/PerspectiveClient.ts +156 -51
  60. package/src/perspectives/PerspectiveProxy.ts +766 -82
  61. package/src/perspectives/PerspectiveResolver.ts +134 -23
  62. package/src/runtime/RuntimeClient.ts +104 -2
  63. package/src/runtime/RuntimeResolver.ts +126 -1
  64. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  65. package/lib/src/subject/SDNADecorators.js +0 -360
  66. package/lib/src/subject/SubjectEntity.d.ts +0 -102
  67. package/lib/src/subject/SubjectEntity.js +0 -267
  68. package/src/subject/SubjectEntity.ts +0 -315
  69. package/yarn-error.log +0 -90
  70. /package/lib/src/{subject → model}/util.d.ts +0 -0
  71. /package/lib/src/{subject → model}/util.js +0 -0
  72. /package/src/{subject → model}/util.ts +0 -0
@@ -0,0 +1,1279 @@
1
+ import { Literal } from "../Literal";
2
+ import { Link } from "../links/Links";
3
+ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
+ import { makeRandomPrologAtom } from "./decorators";
5
+ import { singularToPlural } from "./util";
6
+
7
+ type ValueTuple = [name: string, value: any, resolve?: boolean];
8
+ type WhereOps = {
9
+ not: string | number | boolean | string[] | number[];
10
+ between: [number, number];
11
+ lt: number; // less than
12
+ lte: number; // less than or equal to
13
+ gt: number; // greater than
14
+ gte: number; // greater than or equal to
15
+ };
16
+ type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
17
+ type Where = { [propertyName: string]: WhereCondition };
18
+ type Order = { [propertyName: string]: "ASC" | "DESC" };
19
+
20
+ export type Query = {
21
+ source?: string;
22
+ properties?: string[];
23
+ collections?: string[]; // replace with include: Query[]
24
+ where?: Where;
25
+ order?: Order;
26
+ offset?: number;
27
+ limit?: number;
28
+ count?: boolean;
29
+ };
30
+
31
+ export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
32
+ export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
33
+ export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
34
+
35
+ function capitalize(word: string): string {
36
+ return word.charAt(0).toUpperCase() + word.slice(1);
37
+ }
38
+
39
+ function buildSourceQuery(source?: string): string {
40
+ // Constrains the query to instances that have the provided source
41
+ if (!source) return "";
42
+ return `triple("${source}", "ad4m://has_child", Base)`;
43
+ }
44
+
45
+ // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
46
+ function buildAuthorAndTimestampQuery(): string {
47
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
48
+ return `
49
+ findall(
50
+ [T, A],
51
+ link(Base, _, _, T, A),
52
+ AllLinks
53
+ ),
54
+ sort(AllLinks, SortedLinks),
55
+ SortedLinks = [[Timestamp, Author]|_]
56
+ `;
57
+ }
58
+
59
+ function buildPropertiesQuery(properties?: string[]): string {
60
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
61
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
62
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
63
+ // If no properties are provided, all are included
64
+ return `
65
+ findall([PropertyName, PropertyValue, Resolve], (
66
+ % Constrain to specified properties if provided
67
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
68
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
69
+ ), Properties)
70
+ `;
71
+ }
72
+
73
+ function buildCollectionsQuery(collections?: string[]): string {
74
+ // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
75
+ // If no collections are provided, all are included
76
+ return `
77
+ findall([CollectionName, CollectionValues], (
78
+ % Constrain to specified collections if provided
79
+ ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
80
+
81
+ collection(SubjectClass, CollectionName),
82
+ collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
83
+ ), Collections)
84
+ `;
85
+ }
86
+
87
+ function buildWhereQuery(where: Where = {}): string {
88
+ // Constrains the query to instances that match the provided where conditions
89
+
90
+ function formatValue(value) {
91
+ // Wrap strings in quotes
92
+ return typeof value === "string" ? `"${value}"` : value;
93
+ }
94
+
95
+ return (Object.entries(where) as [string, WhereCondition][])
96
+ .map(([key, value]) => {
97
+ const isSpecial = ["base", "author", "timestamp"].includes(key);
98
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
99
+ // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
100
+ const field = capitalize(key);
101
+
102
+ // Handle direct array values (for IN conditions)
103
+ if (Array.isArray(value)) {
104
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
105
+ if (isSpecial) return `member(${field}, [${formattedValues}])`;
106
+ else return `${getter}, member(Value${key}, [${formattedValues}])`;
107
+ }
108
+
109
+ // Handle operation object
110
+ if (typeof value === "object" && value !== null) {
111
+ const { not, between, lt, lte, gt, gte } = value;
112
+
113
+ // Handle NOT operation
114
+ if (not !== undefined) {
115
+ if (Array.isArray(not)) {
116
+ // NOT IN array
117
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
118
+ if (isSpecial) return `\\+ member(${field}, [${formattedValues}])`;
119
+ else return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
120
+ } else {
121
+ // NOT EQUAL
122
+ if (isSpecial) return `${field} \\= ${formatValue(not)}`;
123
+ else return `${getter}, Value${key} \\= ${formatValue(not)}`;
124
+ }
125
+ }
126
+
127
+ // Handle BETWEEN
128
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
129
+ if (isSpecial) return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
130
+ else return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
131
+ }
132
+
133
+ // Handle lt, lte, gt, & gte operations
134
+ const operators = [
135
+ { value: lt, symbol: "<" }, // LESS THAN
136
+ { value: lte, symbol: "=<" }, // LESS THAN OR EQUAL TO
137
+ { value: gt, symbol: ">" }, // GREATER THAN
138
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
139
+ ];
140
+
141
+ for (const { value, symbol } of operators) {
142
+ if (value !== undefined)
143
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
144
+ }
145
+ }
146
+
147
+ // Default to direct equality
148
+ if (isSpecial) return `${field} = ${formatValue(value)}`;
149
+ else return `${getter}, Value${key} = ${formatValue(value)}`;
150
+ })
151
+ .join(", ");
152
+ }
153
+
154
+ function buildCountQuery(count?: boolean): string {
155
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
156
+ }
157
+
158
+ function buildOrderQuery(order?: Order): string {
159
+ if (!order) return "SortedInstances = UnsortedInstances";
160
+ const [propertyName, direction] = Object.entries(order)[0];
161
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
162
+ }
163
+
164
+ function buildOffsetQuery(offset?: number): string {
165
+ if (!offset || offset < 0) return "InstancesWithOffset = SortedInstances";
166
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
167
+ }
168
+
169
+ function buildLimitQuery(limit?: number): string {
170
+ if (!limit || limit < 0) return "AllInstances = InstancesWithOffset";
171
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
172
+ }
173
+
174
+ /**
175
+ * Base class for defining data models in AD4M.
176
+ *
177
+ * @description
178
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
179
+ * Each model instance is represented as a subgraph in the perspective, with properties and collections
180
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
181
+ * instances based on their properties and relationships.
182
+ *
183
+ * Key concepts:
184
+ * - Each model instance has a unique base expression that serves as its identifier
185
+ * - Properties are stored as links with predicates defined by the `through` option
186
+ * - Collections represent one-to-many relationships as sets of links
187
+ * - Queries are translated to Prolog for efficient graph pattern matching
188
+ * - Changes are tracked through the perspective's subscription system
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * // Define a recipe model
193
+ * @ModelOptions({ name: "Recipe" })
194
+ * class Recipe extends Ad4mModel {
195
+ * // Required property with literal value
196
+ * @Property({
197
+ * through: "recipe://name",
198
+ * resolveLanguage: "literal"
199
+ * })
200
+ * name: string = "";
201
+ *
202
+ * // Optional property with custom initial value
203
+ * @Optional({
204
+ * through: "recipe://status",
205
+ * initial: "recipe://draft"
206
+ * })
207
+ * status: string = "";
208
+ *
209
+ * // Read-only computed property
210
+ * @ReadOnly({
211
+ * through: "recipe://rating",
212
+ * getter: `
213
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
214
+ * sum_list(Ratings, Sum),
215
+ * length(Ratings, Count),
216
+ * Value is Sum / Count
217
+ * `
218
+ * })
219
+ * averageRating: number = 0;
220
+ *
221
+ * // Collection of ingredients
222
+ * @Collection({ through: "recipe://ingredient" })
223
+ * ingredients: string[] = [];
224
+ *
225
+ * // Collection of comments that are instances of another model
226
+ * @Collection({
227
+ * through: "recipe://comment",
228
+ * where: { isInstance: Comment }
229
+ * })
230
+ * comments: Comment[] = [];
231
+ * }
232
+ *
233
+ * // Create and save a new recipe
234
+ * const recipe = new Recipe(perspective);
235
+ * recipe.name = "Chocolate Cake";
236
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
237
+ * await recipe.save();
238
+ *
239
+ * // Query recipes in different ways
240
+ * // Get all recipes
241
+ * const allRecipes = await Recipe.findAll(perspective);
242
+ *
243
+ * // Find recipes with specific criteria
244
+ * const desserts = await Recipe.findAll(perspective, {
245
+ * where: {
246
+ * status: "recipe://published",
247
+ * averageRating: { gt: 4 }
248
+ * },
249
+ * order: { name: "ASC" },
250
+ * limit: 10
251
+ * });
252
+ *
253
+ * // Use the fluent query builder
254
+ * const popularRecipes = await Recipe.query(perspective)
255
+ * .where({ averageRating: { gt: 4.5 } })
256
+ * .order({ averageRating: "DESC" })
257
+ * .limit(5)
258
+ * .get();
259
+ *
260
+ * // Subscribe to real-time updates
261
+ * await Recipe.query(perspective)
262
+ * .where({ status: "recipe://cooking" })
263
+ * .subscribe(recipes => {
264
+ * console.log("Currently being cooked:", recipes);
265
+ * });
266
+ *
267
+ * // Paginate results
268
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
269
+ * .where({ status: "recipe://published" })
270
+ * .paginate(10, 1);
271
+ * ```
272
+ */
273
+ export class Ad4mModel {
274
+ #baseExpression: string;
275
+ #subjectClassName: string;
276
+ #source: string;
277
+ #perspective: PerspectiveProxy;
278
+ author: string;
279
+ timestamp: string;
280
+
281
+ private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
282
+
283
+ static async getClassName(perspective: PerspectiveProxy) {
284
+ // Check if this is the Ad4mModel class itself or a subclass
285
+ const isBaseClass = this === Ad4mModel;
286
+
287
+ // For the base Ad4mModel class, we can't use the cache
288
+ if (isBaseClass) {
289
+ return await perspective.stringOrTemplateObjectToSubjectClassName(this);
290
+ }
291
+
292
+ // Get or create the cache for this class
293
+ let classCache = this.classNamesByClass.get(this);
294
+ if (!classCache) {
295
+ classCache = {};
296
+ this.classNamesByClass.set(this, classCache);
297
+ }
298
+
299
+ // Get or create the cached name for this perspective
300
+ const perspectiveID = perspective.uuid;
301
+ if (!classCache[perspectiveID]) {
302
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
303
+ }
304
+
305
+ return classCache[perspectiveID];
306
+ }
307
+
308
+ /**
309
+ * Constructs a new model instance.
310
+ *
311
+ * @param perspective - The perspective where this model will be stored
312
+ * @param baseExpression - Optional unique identifier for this instance
313
+ * @param source - Optional source expression this instance is linked to
314
+ *
315
+ * @example
316
+ * ```typescript
317
+ * // Create a new recipe with auto-generated base expression
318
+ * const recipe = new Recipe(perspective);
319
+ *
320
+ * // Create with specific base expression
321
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
322
+ *
323
+ * // Create with source link
324
+ * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
325
+ * ```
326
+ */
327
+ constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string) {
328
+ this.#baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl();
329
+ this.#perspective = perspective;
330
+ this.#source = source || "ad4m://self";
331
+ }
332
+
333
+ /**
334
+ * Gets the base expression of the subject.
335
+ */
336
+ get baseExpression() {
337
+ return this.#baseExpression;
338
+ }
339
+
340
+ /**
341
+ * Protected getter for the perspective.
342
+ * Allows subclasses to access the perspective while keeping it private from external code.
343
+ */
344
+ protected get perspective(): PerspectiveProxy {
345
+ return this.#perspective;
346
+ }
347
+
348
+ public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
349
+ // Map properties to object
350
+ const propsObject = Object.fromEntries(
351
+ await Promise.all(
352
+ values.map(async ([name, value, resolve]) => {
353
+ let finalValue = value;
354
+
355
+ // Handle UTF-8 byte sequences from Prolog URL decoding
356
+ if (!resolve && typeof value === 'string') {
357
+ // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
358
+ // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
359
+ const codePoints = Array.from(value, ch => ch.codePointAt(0)!);
360
+ const looksByteString = codePoints.every(cp => cp <= 0xFF);
361
+ const hasHighByte = codePoints.some(cp => cp >= 0x80);
362
+ if (looksByteString && hasHighByte) {
363
+ try {
364
+ const bytes = Uint8Array.from(codePoints);
365
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
366
+ if (decoded !== value) finalValue = decoded;
367
+ } catch (error) {
368
+ // If UTF-8 conversion fails, keep the original value
369
+ console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
370
+ }
371
+ }
372
+ }
373
+
374
+ // Resolve the value if necessary
375
+ if (resolve) {
376
+ let resolvedExpression = await perspective.getExpression(value);
377
+ if (resolvedExpression) {
378
+ try {
379
+ // Attempt to parse the data as JSON
380
+ finalValue = JSON.parse(resolvedExpression.data);
381
+ } catch (error) {
382
+ // If parsing fails, keep the original data
383
+ finalValue = resolvedExpression.data;
384
+ }
385
+ }
386
+ }
387
+ // Apply transform function if it exists
388
+ const transform = instance["__properties"]?.[name]?.transform;
389
+ if (transform && typeof transform === "function") {
390
+ finalValue = transform(finalValue);
391
+ }
392
+ return [name, finalValue];
393
+ })
394
+ )
395
+ );
396
+ // Assign properties to instance
397
+ Object.assign(instance, propsObject);
398
+ }
399
+
400
+ private async getData() {
401
+ // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
402
+ const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
403
+ const fullQuery = `
404
+ Base = "${this.#baseExpression}",
405
+ subject_class("${this.#subjectClassName}", SubjectClass),
406
+ ${subQueries.join(", ")}
407
+ `;
408
+
409
+ const result = await this.#perspective.infer(fullQuery);
410
+ if (result?.[0]) {
411
+ const { Properties, Collections, Timestamp, Author } = result?.[0];
412
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
413
+ await Ad4mModel.assignValuesToInstance(this.#perspective, this, values);
414
+ }
415
+
416
+ return this;
417
+ }
418
+
419
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
420
+ public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
421
+ const { source, properties, collections, where, order, offset, limit, count } = query;
422
+ const className = modelClassName || (await this.getClassName(perspective));
423
+
424
+ const instanceQueries = [
425
+ buildAuthorAndTimestampQuery(),
426
+ buildSourceQuery(source),
427
+ buildPropertiesQuery(properties),
428
+ buildCollectionsQuery(collections),
429
+ buildWhereQuery(where),
430
+ ];
431
+
432
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
433
+
434
+ const fullQuery = `
435
+ findall([Base, Properties, Collections, Timestamp, Author], (
436
+ subject_class("${className}", SubjectClass),
437
+ instance(SubjectClass, Base),
438
+ ${instanceQueries.filter((q) => q).join(", ")}
439
+ ), UnsortedInstances),
440
+ ${resultSetQueries.filter((q) => q).join(", ")}
441
+ `;
442
+
443
+ return fullQuery;
444
+ }
445
+
446
+ public static async instancesFromPrologResult<T extends Ad4mModel>(
447
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
448
+ perspective: PerspectiveProxy,
449
+ query: Query,
450
+ result: AllInstancesResult
451
+ ): Promise<ResultsWithTotalCount<T>> {
452
+ if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
453
+ // Map results to instances
454
+ const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
455
+ const allInstances = await Promise.all(
456
+ result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
457
+ try {
458
+ const instance = new this(perspective, Base) as any;
459
+ // Remove unrequested attributes from instance
460
+ if (requestedAttribtes.length) {
461
+ Object.keys(instance).forEach((key) => {
462
+ if (!requestedAttribtes.includes(key)) delete instance[key];
463
+ });
464
+ }
465
+ // Collect values to assign to instance
466
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
467
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
468
+
469
+ return instance;
470
+ } catch (error) {
471
+ console.error(`Failed to process instance ${Base}:`, error);
472
+ // Return null for failed instances - we'll filter these out below
473
+ return null;
474
+ }
475
+ })
476
+ );
477
+ return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
478
+ }
479
+
480
+ /**
481
+ * Gets all instances of the model in the perspective that match the query params.
482
+ *
483
+ * @param perspective - The perspective to search in
484
+ * @param query - Optional query parameters to filter results
485
+ * @returns Array of matching models
486
+ *
487
+ * @example
488
+ * ```typescript
489
+ * // Get all recipes
490
+ * const allRecipes = await Recipe.findAll(perspective);
491
+ *
492
+ * // Get recipes with specific criteria
493
+ * const recipes = await Recipe.findAll(perspective, {
494
+ * where: {
495
+ * name: "Pasta",
496
+ * rating: { gt: 4 }
497
+ * },
498
+ * order: { createdAt: "DESC" },
499
+ * limit: 10
500
+ * });
501
+ * ```
502
+ */
503
+ static async findAll<T extends Ad4mModel>(
504
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
505
+ perspective: PerspectiveProxy,
506
+ query: Query = {}
507
+ ): Promise<T[]> {
508
+ const prologQuery = await this.queryToProlog(perspective, query);
509
+ const result = await perspective.infer(prologQuery);
510
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
511
+ return results;
512
+ }
513
+
514
+ /**
515
+ * Gets all instances with count of total matches without offset & limit applied.
516
+ *
517
+ * @param perspective - The perspective to search in
518
+ * @param query - Optional query parameters to filter results
519
+ * @returns Object containing results array and total count
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
524
+ * where: { category: "Dessert" },
525
+ * limit: 10
526
+ * });
527
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
528
+ * ```
529
+ */
530
+ static async findAllAndCount<T extends Ad4mModel>(
531
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
532
+ perspective: PerspectiveProxy,
533
+ query: Query = {}
534
+ ): Promise<ResultsWithTotalCount<T>> {
535
+ const prologQuery = await this.queryToProlog(perspective, query);
536
+ const result = await perspective.infer(prologQuery);
537
+ return await this.instancesFromPrologResult(perspective, query, result);
538
+ }
539
+
540
+ /**
541
+ * Helper function for pagination with explicit page size and number.
542
+ *
543
+ * @param perspective - The perspective to search in
544
+ * @param pageSize - Number of items per page
545
+ * @param pageNumber - Which page to retrieve (1-based)
546
+ * @param query - Optional additional query parameters
547
+ * @returns Paginated results with metadata
548
+ *
549
+ * @example
550
+ * ```typescript
551
+ * const page = await Recipe.paginate(perspective, 10, 1, {
552
+ * where: { category: "Main Course" }
553
+ * });
554
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
555
+ * ```
556
+ */
557
+ static async paginate<T extends Ad4mModel>(
558
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
559
+ perspective: PerspectiveProxy,
560
+ pageSize: number,
561
+ pageNumber: number,
562
+ query?: Query
563
+ ): Promise<PaginationResult<T>> {
564
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
565
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
566
+ const result = await perspective.infer(prologQuery);
567
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
568
+ return { results, totalCount, pageSize, pageNumber };
569
+ }
570
+
571
+ static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
572
+ const { source, where } = query;
573
+ const className = modelClassName || (await this.getClassName(perspective));
574
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
575
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
576
+
577
+ const fullQuery = `
578
+ findall([Base, Properties, Collections, Timestamp, Author], (
579
+ subject_class("${className}", SubjectClass),
580
+ instance(SubjectClass, Base),
581
+ ${instanceQueries.filter((q) => q).join(", ")}
582
+ ), UnsortedInstances),
583
+ ${resultSetQueries.filter((q) => q).join(", ")}
584
+ `;
585
+
586
+ return fullQuery;
587
+ }
588
+
589
+ /**
590
+ * Gets a count of all matching instances.
591
+ *
592
+ * @param perspective - The perspective to search in
593
+ * @param query - Optional query parameters to filter results
594
+ * @returns Total count of matching entities
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * const totalRecipes = await Recipe.count(perspective);
599
+ * const activeRecipes = await Recipe.count(perspective, {
600
+ * where: { status: "active" }
601
+ * });
602
+ * ```
603
+ */
604
+ static async count(perspective: PerspectiveProxy, query: Query = {}) {
605
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
606
+
607
+ return result?.[0]?.TotalCount || 0;
608
+ }
609
+
610
+ private async setProperty(key: string, value: any, batchId?: string) {
611
+ const setters = await this.#perspective.infer(
612
+ `subject_class("${this.#subjectClassName}", C), property_setter(C, "${key}", Setter)`
613
+ );
614
+ if (setters && setters.length > 0) {
615
+ const actions = eval(setters[0].Setter);
616
+ const resolveLanguageResults = await this.#perspective.infer(
617
+ `subject_class("${this.#subjectClassName}", C), property_resolve_language(C, "${key}", Language)`
618
+ );
619
+ let resolveLanguage;
620
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
621
+ resolveLanguage = resolveLanguageResults[0].Language;
622
+ }
623
+
624
+ if (resolveLanguage) {
625
+ value = await this.#perspective.createExpression(value, resolveLanguage);
626
+ }
627
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
628
+ }
629
+ }
630
+
631
+ private async setCollectionSetter(key: string, value: any, batchId?: string) {
632
+ let collectionSetters = await this.#perspective.infer(
633
+ `subject_class("${this.#subjectClassName}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`
634
+ );
635
+ if (!collectionSetters) collectionSetters = [];
636
+
637
+ if (collectionSetters.length > 0) {
638
+ const actions = eval(collectionSetters[0].Setter);
639
+
640
+ if (value) {
641
+ if (Array.isArray(value)) {
642
+ await this.#perspective.executeAction(
643
+ actions,
644
+ this.#baseExpression,
645
+ value.map((v) => ({ name: "value", value: v })),
646
+ batchId
647
+ );
648
+ } else {
649
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
650
+ }
651
+ }
652
+ }
653
+ }
654
+
655
+ private async setCollectionAdder(key: string, value: any, batchId?: string) {
656
+ let adders = await this.#perspective.infer(
657
+ `subject_class("${this.#subjectClassName}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`
658
+ );
659
+ if (!adders) adders = [];
660
+
661
+ if (adders.length > 0) {
662
+ const actions = eval(adders[0].Adder);
663
+ if (value) {
664
+ if (Array.isArray(value)) {
665
+ await Promise.all(
666
+ value.map((v) =>
667
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
668
+ )
669
+ );
670
+ } else {
671
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
672
+ }
673
+ }
674
+ }
675
+ }
676
+
677
+ private async setCollectionRemover(key: string, value: any, batchId?: string) {
678
+ let removers = await this.#perspective.infer(
679
+ `subject_class("${this.#subjectClassName}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`
680
+ );
681
+ if (!removers) removers = [];
682
+
683
+ if (removers.length > 0) {
684
+ const actions = eval(removers[0].Remover);
685
+ if (value) {
686
+ if (Array.isArray(value)) {
687
+ await Promise.all(
688
+ value.map((v) =>
689
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
690
+ )
691
+ );
692
+ } else {
693
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
694
+ }
695
+ }
696
+ }
697
+ }
698
+
699
+ /**
700
+ * Saves the model instance to the perspective.
701
+ * Creates a new instance with the base expression and links it to the source.
702
+ *
703
+ * @param batchId - Optional batch ID for batch operations
704
+ * @throws Will throw if instance creation, linking, or updating fails
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * const recipe = new Recipe(perspective);
709
+ * recipe.name = "Spaghetti";
710
+ * recipe.ingredients = ["pasta", "tomato sauce"];
711
+ * await recipe.save();
712
+ *
713
+ * // Or with batch operations:
714
+ * const batchId = await perspective.createBatch();
715
+ * await recipe.save(batchId);
716
+ * await perspective.commitBatch(batchId);
717
+ * ```
718
+ */
719
+ async save(batchId?: string) {
720
+ // We use createSubject's initialValues to set properties (but not collections)
721
+ // We then later use innerUpdate to set collections
722
+
723
+ let batchCreatedHere = false;
724
+ if(!batchId) {
725
+ batchId = await this.perspective.createBatch()
726
+ batchCreatedHere = true;
727
+ }
728
+
729
+
730
+ // First filter out the properties that are not collections (arrays)
731
+ const initialValues = {};
732
+ for (const [key, value] of Object.entries(this)) {
733
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
734
+ initialValues[key] = value;
735
+ }
736
+ }
737
+
738
+ // Create the subject with the initial values
739
+ await this.perspective.createSubject(
740
+ this,
741
+ this.#baseExpression,
742
+ initialValues,
743
+ batchId
744
+ );
745
+
746
+ // Link the subject to the source
747
+ await this.#perspective.add(
748
+ new Link({ source: this.#source, predicate: "ad4m://has_child", target: this.baseExpression }),
749
+ 'shared',
750
+ batchId
751
+ );
752
+
753
+ // Set collections
754
+ await this.innerUpdate(false, batchId)
755
+
756
+ // If we got a batchId passed in, we let the caller decide when to commit.
757
+ // But then we can call getData() since the instance won't exist in the perspective
758
+ // until the bacht is committedl
759
+ if (batchCreatedHere) {
760
+ await this.perspective.commitBatch(batchId)
761
+ await this.getData();
762
+ }
763
+ }
764
+
765
+ private cleanCopy() {
766
+ const cleanCopy = {};
767
+ const props = Object.entries(this);
768
+ for (const [key, value] of props) {
769
+ if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
770
+ cleanCopy[key] = value;
771
+ }
772
+ }
773
+ return cleanCopy;
774
+ }
775
+
776
+ private async innerUpdate(setProperties: boolean = true, batchId?: string) {
777
+ this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
778
+
779
+ const entries = Object.entries(this);
780
+ for (const [key, value] of entries) {
781
+ if (value !== undefined && value !== null) {
782
+ if (value?.action) {
783
+ switch (value.action) {
784
+ case "setter":
785
+ await this.setCollectionSetter(key, value.value, batchId);
786
+ break;
787
+ case "adder":
788
+ await this.setCollectionAdder(key, value.value, batchId);
789
+ break;
790
+ case "remover":
791
+ await this.setCollectionRemover(key, value.value, batchId);
792
+ break;
793
+ default:
794
+ await this.setCollectionSetter(key, value.value, batchId);
795
+ break;
796
+ }
797
+ } else if (Array.isArray(value) && value.length > 0) {
798
+ await this.setCollectionSetter(key, value, batchId);
799
+ } else if (value !== undefined && value !== null && value !== "") {
800
+ if (setProperties) {
801
+ await this.setProperty(key, value, batchId);
802
+ }
803
+ }
804
+ }
805
+ }
806
+ }
807
+
808
+ /**
809
+ * Updates the model instance's properties and collections.
810
+ *
811
+ * @param batchId - Optional batch ID for batch operations
812
+ * @throws Will throw if property setting or collection updates fail
813
+ *
814
+ * @example
815
+ * ```typescript
816
+ * const recipe = await Recipe.findAll(perspective)[0];
817
+ * recipe.rating = 5;
818
+ * recipe.ingredients.push("garlic");
819
+ * await recipe.update();
820
+ *
821
+ * // Or with batch operations:
822
+ * const batchId = await perspective.createBatch();
823
+ * await recipe.update(batchId);
824
+ * await perspective.commitBatch(batchId);
825
+ * ```
826
+ */
827
+ async update(batchId?: string) {
828
+ await this.innerUpdate(true, batchId);
829
+ await this.getData();
830
+ }
831
+
832
+ /**
833
+ * Gets the model instance with all properties and collections populated.
834
+ *
835
+ * @returns The populated model instance
836
+ * @throws Will throw if data retrieval fails
837
+ *
838
+ * @example
839
+ * ```typescript
840
+ * const recipe = new Recipe(perspective, existingId);
841
+ * await recipe.get();
842
+ * console.log(recipe.name, recipe.ingredients);
843
+ * ```
844
+ */
845
+ async get() {
846
+ this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
847
+
848
+ return await this.getData();
849
+ }
850
+
851
+ /**
852
+ * Deletes the model instance from the perspective.
853
+ *
854
+ * @param batchId - Optional batch ID for batch operations
855
+ * @throws Will throw if removal fails
856
+ *
857
+ * @example
858
+ * ```typescript
859
+ * const recipe = await Recipe.findAll(perspective)[0];
860
+ * await recipe.delete();
861
+ *
862
+ * // Or with batch operations:
863
+ * const batchId = await perspective.createBatch();
864
+ * await recipe.delete(batchId);
865
+ * await perspective.commitBatch(batchId);
866
+ * ```
867
+ */
868
+ async delete(batchId?: string) {
869
+ await this.#perspective.removeSubject(this, this.#baseExpression, batchId);
870
+ }
871
+
872
+ /**
873
+ * Creates a query builder for fluent query construction.
874
+ *
875
+ * @param perspective - The perspective to query
876
+ * @param query - Optional initial query parameters
877
+ * @returns A new query builder instance
878
+ *
879
+ * @example
880
+ * ```typescript
881
+ * const recipes = await Recipe.query(perspective)
882
+ * .where({ category: "Dessert" })
883
+ * .order({ rating: "DESC" })
884
+ * .limit(5)
885
+ * .run();
886
+ *
887
+ * // With real-time updates
888
+ * await Recipe.query(perspective)
889
+ * .where({ status: "cooking" })
890
+ * .subscribe(recipes => {
891
+ * console.log("Currently cooking:", recipes);
892
+ * });
893
+ * ```
894
+ */
895
+ static query<T extends Ad4mModel>(
896
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
897
+ perspective: PerspectiveProxy,
898
+ query?: Query
899
+ ): ModelQueryBuilder<T> {
900
+ return new ModelQueryBuilder<T>(perspective, this as any, query);
901
+ }
902
+ }
903
+
904
+ /** Query builder for Ad4mModel queries.
905
+ * Allows building queries with a fluent interface and either running them once
906
+ * or subscribing to updates.
907
+ *
908
+ * @example
909
+ * ```typescript
910
+ * const builder = Recipe.query(perspective)
911
+ * .where({ category: "Dessert" })
912
+ * .order({ rating: "DESC" })
913
+ * .limit(10);
914
+ *
915
+ * // Run once
916
+ * const recipes = await builder.run();
917
+ *
918
+ * // Or subscribe to updates
919
+ * await builder.subscribe(recipes => {
920
+ * console.log("Updated recipes:", recipes);
921
+ * });
922
+ * ```
923
+ */
924
+ export class ModelQueryBuilder<T extends Ad4mModel> {
925
+ private perspective: PerspectiveProxy;
926
+ private queryParams: Query = {};
927
+ private modelClassName: string | null = null;
928
+ private ctor: typeof Ad4mModel;
929
+ private currentSubscription?: any;
930
+
931
+ constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
932
+ this.perspective = perspective;
933
+ this.ctor = ctor;
934
+ if (query) this.queryParams = query;
935
+ }
936
+
937
+ /**
938
+ * Disposes of the current subscription if one exists.
939
+ *
940
+ * This method:
941
+ * 1. Stops the keepalive signals to the subscription
942
+ * 2. Unsubscribes from GraphQL subscription updates
943
+ * 3. Notifies the backend to clean up subscription resources
944
+ * 4. Clears the subscription reference
945
+ *
946
+ * You should call this method when you're done with a subscription
947
+ * to prevent memory leaks and ensure proper cleanup.
948
+ */
949
+ dispose() {
950
+ if (this.currentSubscription) {
951
+ this.currentSubscription.dispose();
952
+ this.currentSubscription = undefined;
953
+ }
954
+ }
955
+
956
+ /**
957
+ * Adds where conditions to the query.
958
+ *
959
+ * @param conditions - The conditions to filter by
960
+ * @returns The query builder for chaining
961
+ *
962
+ * @example
963
+ * ```typescript
964
+ * .where({
965
+ * category: "Dessert",
966
+ * rating: { gt: 4 },
967
+ * tags: ["vegan", "quick"],
968
+ * published: true
969
+ * })
970
+ * ```
971
+ */
972
+ where(conditions: Where): ModelQueryBuilder<T> {
973
+ this.queryParams.where = conditions;
974
+ return this;
975
+ }
976
+
977
+ /**
978
+ * Sets the order for the query results.
979
+ *
980
+ * @param orderBy - The ordering criteria
981
+ * @returns The query builder for chaining
982
+ *
983
+ * @example
984
+ * ```typescript
985
+ * .order({ createdAt: "DESC" })
986
+ * ```
987
+ */
988
+ order(orderBy: Order): ModelQueryBuilder<T> {
989
+ this.queryParams.order = orderBy;
990
+ return this;
991
+ }
992
+
993
+ /**
994
+ * Sets the maximum number of results to return.
995
+ *
996
+ * @param limit - Maximum number of results
997
+ * @returns The query builder for chaining
998
+ *
999
+ * @example
1000
+ * ```typescript
1001
+ * .limit(10)
1002
+ * ```
1003
+ */
1004
+ limit(limit: number): ModelQueryBuilder<T> {
1005
+ this.queryParams.limit = limit;
1006
+ return this;
1007
+ }
1008
+
1009
+ /**
1010
+ * Sets the number of results to skip.
1011
+ *
1012
+ * @param offset - Number of results to skip
1013
+ * @returns The query builder for chaining
1014
+ *
1015
+ * @example
1016
+ * ```typescript
1017
+ * .offset(20) // Skip first 20 results
1018
+ * ```
1019
+ */
1020
+ offset(offset: number): ModelQueryBuilder<T> {
1021
+ this.queryParams.offset = offset;
1022
+ return this;
1023
+ }
1024
+
1025
+ /**
1026
+ * Sets the source filter for the query.
1027
+ *
1028
+ * @param source - The source to filter by
1029
+ * @returns The query builder for chaining
1030
+ *
1031
+ * @example
1032
+ * ```typescript
1033
+ * .source("ad4m://self")
1034
+ * ```
1035
+ */
1036
+ source(source: string): ModelQueryBuilder<T> {
1037
+ this.queryParams.source = source;
1038
+ return this;
1039
+ }
1040
+
1041
+ /**
1042
+ * Specifies which properties to include in the results.
1043
+ *
1044
+ * @param properties - Array of property names to include
1045
+ * @returns The query builder for chaining
1046
+ *
1047
+ * @example
1048
+ * ```typescript
1049
+ * .properties(["name", "description", "rating"])
1050
+ * ```
1051
+ */
1052
+ properties(properties: string[]): ModelQueryBuilder<T> {
1053
+ this.queryParams.properties = properties;
1054
+ return this;
1055
+ }
1056
+
1057
+ /**
1058
+ * Specifies which collections to include in the results.
1059
+ *
1060
+ * @param collections - Array of collection names to include
1061
+ * @returns The query builder for chaining
1062
+ *
1063
+ * @example
1064
+ * ```typescript
1065
+ * .collections(["ingredients", "steps"])
1066
+ * ```
1067
+ */
1068
+ collections(collections: string[]): ModelQueryBuilder<T> {
1069
+ this.queryParams.collections = collections;
1070
+ return this;
1071
+ }
1072
+
1073
+ overrideModelClassName(className: string): ModelQueryBuilder<T> {
1074
+ this.modelClassName = className;
1075
+ return this;
1076
+ }
1077
+
1078
+ /**
1079
+ * Executes the query once and returns the results.
1080
+ *
1081
+ * @returns Array of matching entities
1082
+ *
1083
+ * @example
1084
+ * ```typescript
1085
+ * const recipes = await Recipe.query(perspective)
1086
+ * .where({ category: "Dessert" })
1087
+ * .get();
1088
+ * ```
1089
+ */
1090
+ async get(): Promise<T[]> {
1091
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
1092
+ const result = await this.perspective.infer(query);
1093
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
1094
+ return results as T[];
1095
+ }
1096
+
1097
+ /**
1098
+ * Subscribes to the query and receives updates when results change.
1099
+ *
1100
+ * This method:
1101
+ * 1. Creates and initializes a Prolog query subscription
1102
+ * 2. Sets up the callback to process future updates
1103
+ * 3. Returns the initial results immediately
1104
+ *
1105
+ * Remember to call dispose() when you're done with the subscription
1106
+ * to clean up resources.
1107
+ *
1108
+ * @param callback - Function to call with updated results
1109
+ * @returns Initial results array
1110
+ *
1111
+ * @example
1112
+ * ```typescript
1113
+ * const builder = Recipe.query(perspective)
1114
+ * .where({ status: "cooking" });
1115
+ *
1116
+ * const initialRecipes = await builder.subscribe(recipes => {
1117
+ * console.log("Updated recipes:", recipes);
1118
+ * });
1119
+ *
1120
+ * // When done with subscription:
1121
+ * builder.dispose();
1122
+ * ```
1123
+ */
1124
+ async subscribe(callback: (results: T[]) => void): Promise<T[]> {
1125
+ // Clean up any existing subscription
1126
+ this.dispose();
1127
+
1128
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
1129
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
1130
+
1131
+ const processResults = async (result: AllInstancesResult) => {
1132
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
1133
+ callback(results as T[]);
1134
+ };
1135
+
1136
+ this.currentSubscription.onResult(processResults);
1137
+ const { results } = await this.ctor.instancesFromPrologResult(
1138
+ this.perspective,
1139
+ this.queryParams,
1140
+ this.currentSubscription.result
1141
+ );
1142
+ return results as T[];
1143
+ }
1144
+
1145
+ /**
1146
+ * Gets the total count of matching entities.
1147
+ *
1148
+ * @returns Total count
1149
+ *
1150
+ * @example
1151
+ * ```typescript
1152
+ * const totalDesserts = await Recipe.query(perspective)
1153
+ * .where({ category: "Dessert" })
1154
+ * .count();
1155
+ * ```
1156
+ */
1157
+ async count(): Promise<number> {
1158
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1159
+ const result = await this.perspective.infer(query);
1160
+ return result?.[0]?.TotalCount || 0;
1161
+ }
1162
+
1163
+ /**
1164
+ * Subscribes to count updates for matching entities.
1165
+ *
1166
+ * This method:
1167
+ * 1. Creates and initializes a Prolog query subscription for the count
1168
+ * 2. Sets up the callback to process future count updates
1169
+ * 3. Returns the initial count immediately
1170
+ *
1171
+ * Remember to call dispose() when you're done with the subscription
1172
+ * to clean up resources.
1173
+ *
1174
+ * @param callback - Function to call with updated count
1175
+ * @returns Initial count
1176
+ *
1177
+ * @example
1178
+ * ```typescript
1179
+ * const builder = Recipe.query(perspective)
1180
+ * .where({ status: "active" });
1181
+ *
1182
+ * const initialCount = await builder.countSubscribe(count => {
1183
+ * console.log("Active items:", count);
1184
+ * });
1185
+ *
1186
+ * // When done with subscription:
1187
+ * builder.dispose();
1188
+ * ```
1189
+ */
1190
+ async countSubscribe(callback: (count: number) => void): Promise<number> {
1191
+ // Clean up any existing subscription
1192
+ this.dispose();
1193
+
1194
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1195
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
1196
+
1197
+ const processResults = async (result: any) => {
1198
+ const newCount = result?.[0]?.TotalCount || 0;
1199
+ callback(newCount);
1200
+ };
1201
+
1202
+ this.currentSubscription.onResult(processResults);
1203
+ return this.currentSubscription.result?.[0]?.TotalCount || 0;
1204
+ }
1205
+
1206
+ /**
1207
+ * Gets a page of results with pagination metadata.
1208
+ *
1209
+ * @param pageSize - Number of items per page
1210
+ * @param pageNumber - Which page to retrieve (1-based)
1211
+ * @returns Paginated results with metadata
1212
+ *
1213
+ * @example
1214
+ * ```typescript
1215
+ * const page = await Recipe.query(perspective)
1216
+ * .where({ category: "Main" })
1217
+ * .paginate(10, 1);
1218
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1219
+ * ```
1220
+ */
1221
+ async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
1222
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1223
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1224
+ const result = await this.perspective.infer(prologQuery);
1225
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
1226
+ return { results, totalCount, pageSize, pageNumber };
1227
+ }
1228
+
1229
+ /**
1230
+ * Subscribes to paginated results updates.
1231
+ *
1232
+ * This method:
1233
+ * 1. Creates and initializes a Prolog query subscription for the paginated results
1234
+ * 2. Sets up the callback to process future page updates
1235
+ * 3. Returns the initial page immediately
1236
+ *
1237
+ * Remember to call dispose() when you're done with the subscription
1238
+ * to clean up resources.
1239
+ *
1240
+ * @param pageSize - Number of items per page
1241
+ * @param pageNumber - Which page to retrieve (1-based)
1242
+ * @param callback - Function to call with updated pagination results
1243
+ * @returns Initial pagination results
1244
+ *
1245
+ * @example
1246
+ * ```typescript
1247
+ * const builder = Recipe.query(perspective)
1248
+ * .where({ category: "Main" });
1249
+ *
1250
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1251
+ * console.log("Updated page:", page.results);
1252
+ * });
1253
+ *
1254
+ * // When done with subscription:
1255
+ * builder.dispose();
1256
+ * ```
1257
+ */
1258
+ async paginateSubscribe(
1259
+ pageSize: number,
1260
+ pageNumber: number,
1261
+ callback: (results: PaginationResult<T>) => void
1262
+ ): Promise<PaginationResult<T>> {
1263
+ // Clean up any existing subscription
1264
+ this.dispose();
1265
+
1266
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1267
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1268
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
1269
+
1270
+ const processResults = async (r: AllInstancesResult) => {
1271
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r)) as ResultsWithTotalCount<T>;
1272
+ callback({ results, totalCount, pageSize, pageNumber });
1273
+ };
1274
+
1275
+ this.currentSubscription.onResult(processResults);
1276
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
1277
+ return { results, totalCount, pageSize, pageNumber };
1278
+ }
1279
+ }