@coasys/ad4m 0.10.0 → 0.10.1-dev-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 (64) hide show
  1. package/lib/index.cjs +3785 -843
  2. package/lib/index.js +3777 -839
  3. package/lib/src/Ad4mClient.js +2 -1
  4. package/lib/src/Literal.js +4 -1
  5. package/lib/src/ai/AIClient.d.ts +8 -2
  6. package/lib/src/ai/AIClient.js +25 -14
  7. package/lib/src/ai/AIResolver.d.ts +25 -6
  8. package/lib/src/ai/AIResolver.js +102 -18
  9. package/lib/src/index.d.ts +4 -3
  10. package/lib/src/index.js +4 -3
  11. package/lib/src/model/Ad4mModel.d.ts +730 -0
  12. package/lib/src/model/Ad4mModel.js +1399 -0
  13. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  14. package/lib/src/{subject → model}/Subject.js +18 -18
  15. package/lib/src/model/decorators.d.ts +502 -0
  16. package/lib/src/model/decorators.js +683 -0
  17. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  18. package/lib/src/neighbourhood/NeighbourhoodClient.js +13 -10
  19. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  20. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  21. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  22. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +73 -0
  23. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  24. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  25. package/lib/src/perspectives/PerspectiveClient.d.ts +23 -11
  26. package/lib/src/perspectives/PerspectiveClient.js +147 -51
  27. package/lib/src/perspectives/PerspectiveProxy.d.ts +494 -54
  28. package/lib/src/perspectives/PerspectiveProxy.js +684 -67
  29. package/lib/src/perspectives/PerspectiveResolver.d.ts +24 -9
  30. package/lib/src/perspectives/PerspectiveResolver.js +151 -46
  31. package/lib/src/runtime/RuntimeClient.d.ts +8 -2
  32. package/lib/src/runtime/RuntimeClient.js +64 -0
  33. package/lib/src/runtime/RuntimeResolver.d.ts +27 -1
  34. package/lib/src/runtime/RuntimeResolver.js +138 -0
  35. package/lib/src/schema.gql +55 -16
  36. package/lib/src/typeDefs.js +55 -16
  37. package/package.json +4 -3
  38. package/src/Ad4mClient.test.ts +51 -19
  39. package/src/Ad4mClient.ts +3 -1
  40. package/src/Literal.ts +4 -1
  41. package/src/ai/AIClient.ts +35 -14
  42. package/src/ai/AIResolver.ts +78 -16
  43. package/src/index.ts +4 -3
  44. package/src/model/Ad4mModel.ts +1651 -0
  45. package/src/{subject → model}/Subject.ts +16 -16
  46. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  47. package/src/neighbourhood/NeighbourhoodClient.ts +13 -10
  48. package/src/neighbourhood/NeighbourhoodProxy.test.ts +100 -0
  49. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  50. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  51. package/src/perspectives/PerspectiveClient.ts +156 -51
  52. package/src/perspectives/PerspectiveProxy.ts +766 -82
  53. package/src/perspectives/PerspectiveResolver.ts +134 -23
  54. package/src/runtime/RuntimeClient.ts +71 -2
  55. package/src/runtime/RuntimeResolver.ts +91 -1
  56. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  57. package/lib/src/subject/SDNADecorators.js +0 -360
  58. package/lib/src/subject/SubjectEntity.d.ts +0 -102
  59. package/lib/src/subject/SubjectEntity.js +0 -267
  60. package/src/subject/SubjectEntity.ts +0 -315
  61. package/yarn-error.log +0 -90
  62. /package/lib/src/{subject → model}/util.d.ts +0 -0
  63. /package/lib/src/{subject → model}/util.js +0 -0
  64. /package/src/{subject → model}/util.ts +0 -0
@@ -0,0 +1,1651 @@
1
+ import { Literal } from "../Literal";
2
+ import { Link } from "../links/Links";
3
+ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
+ import { makeRandomPrologAtom, PropertyOptions, CollectionOptions, ModelOptions } from "./decorators";
5
+ import { singularToPlural, pluralToSingular, propertyNameToSetterName, collectionToAdderName, collectionToRemoverName, collectionToSetterName } from "./util";
6
+
7
+ // JSON Schema type definitions
8
+ interface JSONSchemaProperty {
9
+ type: string | string[];
10
+ items?: JSONSchemaProperty;
11
+ properties?: { [key: string]: JSONSchemaProperty };
12
+ required?: string[];
13
+ "x-ad4m"?: {
14
+ through?: string;
15
+ resolveLanguage?: string;
16
+ local?: boolean;
17
+ writable?: boolean;
18
+ initial?: string;
19
+ };
20
+ }
21
+
22
+ interface JSONSchema {
23
+ $schema?: string;
24
+ title?: string;
25
+ $id?: string;
26
+ type?: string;
27
+ properties?: { [key: string]: JSONSchemaProperty };
28
+ required?: string[];
29
+ "x-ad4m"?: {
30
+ namespace?: string;
31
+ className?: string;
32
+ };
33
+ }
34
+
35
+ interface JSONSchemaToModelOptions {
36
+ name: string;
37
+ namespace?: string;
38
+ predicateTemplate?: string;
39
+ predicateGenerator?: (title: string, property: string) => string;
40
+ propertyMapping?: Record<string, string>;
41
+ resolveLanguage?: string;
42
+ local?: boolean;
43
+ propertyOptions?: Record<string, Partial<PropertyOptions>>;
44
+ }
45
+
46
+ type ValueTuple = [name: string, value: any, resolve?: boolean];
47
+ type WhereOps = {
48
+ not: string | number | boolean | string[] | number[];
49
+ between: [number, number];
50
+ lt: number; // less than
51
+ lte: number; // less than or equal to
52
+ gt: number; // greater than
53
+ gte: number; // greater than or equal to
54
+ };
55
+ type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
56
+ type Where = { [propertyName: string]: WhereCondition };
57
+ type Order = { [propertyName: string]: "ASC" | "DESC" };
58
+
59
+ export type Query = {
60
+ source?: string;
61
+ properties?: string[];
62
+ collections?: string[]; // replace with include: Query[]
63
+ where?: Where;
64
+ order?: Order;
65
+ offset?: number;
66
+ limit?: number;
67
+ count?: boolean;
68
+ };
69
+
70
+ export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
71
+ export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
72
+ export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
73
+
74
+ function capitalize(word: string): string {
75
+ return word.charAt(0).toUpperCase() + word.slice(1);
76
+ }
77
+
78
+ function buildSourceQuery(source?: string): string {
79
+ // Constrains the query to instances that have the provided source
80
+ if (!source) return "";
81
+ return `triple("${source}", "ad4m://has_child", Base)`;
82
+ }
83
+
84
+ // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
85
+ function buildAuthorAndTimestampQuery(): string {
86
+ // Gets the author and timestamp of a Ad4mModel instance (based on the first link mentioning the base)
87
+ return `
88
+ findall(
89
+ [T, A],
90
+ link(Base, _, _, T, A),
91
+ AllLinks
92
+ ),
93
+ sort(AllLinks, SortedLinks),
94
+ SortedLinks = [[Timestamp, Author]|_]
95
+ `;
96
+ }
97
+
98
+ function buildPropertiesQuery(properties?: string[]): string {
99
+ // Gets the name, value, and resolve boolean for all (or some) properties on a Ad4mModel instance
100
+ // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
101
+ // an Expression in JSON literal, or the direct literal value if it is a simple literal
102
+ // If no properties are provided, all are included
103
+ return `
104
+ findall([PropertyName, PropertyValue, Resolve], (
105
+ % Constrain to specified properties if provided
106
+ ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
107
+ resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
108
+ ), Properties)
109
+ `;
110
+ }
111
+
112
+ function buildCollectionsQuery(collections?: string[]): string {
113
+ // Gets the name and array of values for all (or some) collections on a Ad4mModel instance
114
+ // If no collections are provided, all are included
115
+ return `
116
+ findall([CollectionName, CollectionValues], (
117
+ % Constrain to specified collections if provided
118
+ ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
119
+
120
+ collection(SubjectClass, CollectionName),
121
+ collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
122
+ ), Collections)
123
+ `;
124
+ }
125
+
126
+ function buildWhereQuery(where: Where = {}): string {
127
+ // Constrains the query to instances that match the provided where conditions
128
+
129
+ function formatValue(value) {
130
+ // Wrap strings in quotes
131
+ return typeof value === "string" ? `"${value}"` : value;
132
+ }
133
+
134
+ return (Object.entries(where) as [string, WhereCondition][])
135
+ .map(([key, value]) => {
136
+ const isSpecial = ["base", "author", "timestamp"].includes(key);
137
+ const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
138
+ // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
139
+ const field = capitalize(key);
140
+
141
+ // Handle direct array values (for IN conditions)
142
+ if (Array.isArray(value)) {
143
+ const formattedValues = value.map((v) => formatValue(v)).join(", ");
144
+ if (isSpecial) return `member(${field}, [${formattedValues}])`;
145
+ else return `${getter}, member(Value${key}, [${formattedValues}])`;
146
+ }
147
+
148
+ // Handle operation object
149
+ if (typeof value === "object" && value !== null) {
150
+ const { not, between, lt, lte, gt, gte } = value;
151
+
152
+ // Handle NOT operation
153
+ if (not !== undefined) {
154
+ if (Array.isArray(not)) {
155
+ // NOT IN array
156
+ const formattedValues = not.map((v) => formatValue(v)).join(", ");
157
+ if (isSpecial) return `\\+ member(${field}, [${formattedValues}])`;
158
+ else return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
159
+ } else {
160
+ // NOT EQUAL
161
+ if (isSpecial) return `${field} \\= ${formatValue(not)}`;
162
+ else return `${getter}, Value${key} \\= ${formatValue(not)}`;
163
+ }
164
+ }
165
+
166
+ // Handle BETWEEN
167
+ if (between !== undefined && Array.isArray(between) && between.length === 2) {
168
+ if (isSpecial) return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
169
+ else return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
170
+ }
171
+
172
+ // Handle lt, lte, gt, & gte operations
173
+ const operators = [
174
+ { value: lt, symbol: "<" }, // LESS THAN
175
+ { value: lte, symbol: "=<" }, // LESS THAN OR EQUAL TO
176
+ { value: gt, symbol: ">" }, // GREATER THAN
177
+ { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
178
+ ];
179
+
180
+ for (const { value, symbol } of operators) {
181
+ if (value !== undefined)
182
+ return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
183
+ }
184
+ }
185
+
186
+ // Default to direct equality
187
+ if (isSpecial) return `${field} = ${formatValue(value)}`;
188
+ else return `${getter}, Value${key} = ${formatValue(value)}`;
189
+ })
190
+ .join(", ");
191
+ }
192
+
193
+ function buildCountQuery(count?: boolean): string {
194
+ return count ? "length(UnsortedInstances, TotalCount)" : "";
195
+ }
196
+
197
+ function buildOrderQuery(order?: Order): string {
198
+ if (!order) return "SortedInstances = UnsortedInstances";
199
+ const [propertyName, direction] = Object.entries(order)[0];
200
+ return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
201
+ }
202
+
203
+ function buildOffsetQuery(offset?: number): string {
204
+ if (!offset || offset < 0) return "InstancesWithOffset = SortedInstances";
205
+ return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
206
+ }
207
+
208
+ function buildLimitQuery(limit?: number): string {
209
+ if (!limit || limit < 0) return "AllInstances = InstancesWithOffset";
210
+ return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
211
+ }
212
+
213
+ /**
214
+ * Base class for defining data models in AD4M.
215
+ *
216
+ * @description
217
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
218
+ * Each model instance is represented as a subgraph in the perspective, with properties and collections
219
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
220
+ * instances based on their properties and relationships.
221
+ *
222
+ * Key concepts:
223
+ * - Each model instance has a unique base expression that serves as its identifier
224
+ * - Properties are stored as links with predicates defined by the `through` option
225
+ * - Collections represent one-to-many relationships as sets of links
226
+ * - Queries are translated to Prolog for efficient graph pattern matching
227
+ * - Changes are tracked through the perspective's subscription system
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * // Define a recipe model
232
+ * @ModelOptions({ name: "Recipe" })
233
+ * class Recipe extends Ad4mModel {
234
+ * // Required property with literal value
235
+ * @Property({
236
+ * through: "recipe://name",
237
+ * resolveLanguage: "literal"
238
+ * })
239
+ * name: string = "";
240
+ *
241
+ * // Optional property with custom initial value
242
+ * @Optional({
243
+ * through: "recipe://status",
244
+ * initial: "recipe://draft"
245
+ * })
246
+ * status: string = "";
247
+ *
248
+ * // Read-only computed property
249
+ * @ReadOnly({
250
+ * through: "recipe://rating",
251
+ * getter: `
252
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
253
+ * sum_list(Ratings, Sum),
254
+ * length(Ratings, Count),
255
+ * Value is Sum / Count
256
+ * `
257
+ * })
258
+ * averageRating: number = 0;
259
+ *
260
+ * // Collection of ingredients
261
+ * @Collection({ through: "recipe://ingredient" })
262
+ * ingredients: string[] = [];
263
+ *
264
+ * // Collection of comments that are instances of another model
265
+ * @Collection({
266
+ * through: "recipe://comment",
267
+ * where: { isInstance: Comment }
268
+ * })
269
+ * comments: Comment[] = [];
270
+ * }
271
+ *
272
+ * // Create and save a new recipe
273
+ * const recipe = new Recipe(perspective);
274
+ * recipe.name = "Chocolate Cake";
275
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
276
+ * await recipe.save();
277
+ *
278
+ * // Query recipes in different ways
279
+ * // Get all recipes
280
+ * const allRecipes = await Recipe.findAll(perspective);
281
+ *
282
+ * // Find recipes with specific criteria
283
+ * const desserts = await Recipe.findAll(perspective, {
284
+ * where: {
285
+ * status: "recipe://published",
286
+ * averageRating: { gt: 4 }
287
+ * },
288
+ * order: { name: "ASC" },
289
+ * limit: 10
290
+ * });
291
+ *
292
+ * // Use the fluent query builder
293
+ * const popularRecipes = await Recipe.query(perspective)
294
+ * .where({ averageRating: { gt: 4.5 } })
295
+ * .order({ averageRating: "DESC" })
296
+ * .limit(5)
297
+ * .get();
298
+ *
299
+ * // Subscribe to real-time updates
300
+ * await Recipe.query(perspective)
301
+ * .where({ status: "recipe://cooking" })
302
+ * .subscribe(recipes => {
303
+ * console.log("Currently being cooked:", recipes);
304
+ * });
305
+ *
306
+ * // Paginate results
307
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
308
+ * .where({ status: "recipe://published" })
309
+ * .paginate(10, 1);
310
+ * ```
311
+ */
312
+ export class Ad4mModel {
313
+ #baseExpression: string;
314
+ #subjectClassName: string;
315
+ #source: string;
316
+ #perspective: PerspectiveProxy;
317
+ author: string;
318
+ timestamp: string;
319
+
320
+ private static classNamesByClass = new WeakMap<typeof Ad4mModel, { [perspectiveId: string]: string }>();
321
+
322
+ static async getClassName(perspective: PerspectiveProxy) {
323
+ // Check if this is the Ad4mModel class itself or a subclass
324
+ const isBaseClass = this === Ad4mModel;
325
+
326
+ // For the base Ad4mModel class, we can't use the cache
327
+ if (isBaseClass) {
328
+ return await perspective.stringOrTemplateObjectToSubjectClassName(this);
329
+ }
330
+
331
+ // Get or create the cache for this class
332
+ let classCache = this.classNamesByClass.get(this);
333
+ if (!classCache) {
334
+ classCache = {};
335
+ this.classNamesByClass.set(this, classCache);
336
+ }
337
+
338
+ // Get or create the cached name for this perspective
339
+ const perspectiveID = perspective.uuid;
340
+ if (!classCache[perspectiveID]) {
341
+ classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
342
+ }
343
+
344
+ return classCache[perspectiveID];
345
+ }
346
+
347
+ /**
348
+ * Constructs a new model instance.
349
+ *
350
+ * @param perspective - The perspective where this model will be stored
351
+ * @param baseExpression - Optional unique identifier for this instance
352
+ * @param source - Optional source expression this instance is linked to
353
+ *
354
+ * @example
355
+ * ```typescript
356
+ * // Create a new recipe with auto-generated base expression
357
+ * const recipe = new Recipe(perspective);
358
+ *
359
+ * // Create with specific base expression
360
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
361
+ *
362
+ * // Create with source link
363
+ * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
364
+ * ```
365
+ */
366
+ constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string) {
367
+ this.#baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl();
368
+ this.#perspective = perspective;
369
+ this.#source = source || "ad4m://self";
370
+ }
371
+
372
+ /**
373
+ * Gets the base expression of the subject.
374
+ */
375
+ get baseExpression() {
376
+ return this.#baseExpression;
377
+ }
378
+
379
+ /**
380
+ * Protected getter for the perspective.
381
+ * Allows subclasses to access the perspective while keeping it private from external code.
382
+ */
383
+ protected get perspective(): PerspectiveProxy {
384
+ return this.#perspective;
385
+ }
386
+
387
+ public static async assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]) {
388
+ // Map properties to object
389
+ const propsObject = Object.fromEntries(
390
+ await Promise.all(
391
+ values.map(async ([name, value, resolve]) => {
392
+ let finalValue = value;
393
+
394
+ // Handle UTF-8 byte sequences from Prolog URL decoding
395
+ if (!resolve && typeof value === 'string') {
396
+ // Only attempt reconstruction if the string looks like a byte string (all code points <= 0xFF)
397
+ // and contains at least one high byte (>= 0x80). This avoids mangling valid Unicode.
398
+ const codePoints = Array.from(value, ch => ch.codePointAt(0)!);
399
+ const looksByteString = codePoints.every(cp => cp <= 0xFF);
400
+ const hasHighByte = codePoints.some(cp => cp >= 0x80);
401
+ if (looksByteString && hasHighByte) {
402
+ try {
403
+ const bytes = Uint8Array.from(codePoints);
404
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
405
+ if (decoded !== value) finalValue = decoded;
406
+ } catch (error) {
407
+ // If UTF-8 conversion fails, keep the original value
408
+ console.warn(`UTF-8 byte reconstruction failed for property "${name}"`, { value, error });
409
+ }
410
+ }
411
+ }
412
+
413
+ // Resolve the value if necessary
414
+ if (resolve) {
415
+ let resolvedExpression = await perspective.getExpression(value);
416
+ if (resolvedExpression) {
417
+ try {
418
+ // Attempt to parse the data as JSON
419
+ finalValue = JSON.parse(resolvedExpression.data);
420
+ } catch (error) {
421
+ // If parsing fails, keep the original data
422
+ finalValue = resolvedExpression.data;
423
+ }
424
+ }
425
+ }
426
+ // Apply transform function if it exists
427
+ const transform = instance["__properties"]?.[name]?.transform;
428
+ if (transform && typeof transform === "function") {
429
+ finalValue = transform(finalValue);
430
+ }
431
+ return [name, finalValue];
432
+ })
433
+ )
434
+ );
435
+ // Assign properties to instance
436
+ Object.assign(instance, propsObject);
437
+ }
438
+
439
+ private async getData() {
440
+ // Builds an object with the author, timestamp, all properties, & all collections on the Ad4mModel and saves it to the instance
441
+ const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
442
+ const fullQuery = `
443
+ Base = "${this.#baseExpression}",
444
+ subject_class("${this.#subjectClassName}", SubjectClass),
445
+ ${subQueries.join(", ")}
446
+ `;
447
+
448
+ const result = await this.#perspective.infer(fullQuery);
449
+ if (result?.[0]) {
450
+ const { Properties, Collections, Timestamp, Author } = result?.[0];
451
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
452
+ await Ad4mModel.assignValuesToInstance(this.#perspective, this, values);
453
+ }
454
+
455
+ return this;
456
+ }
457
+
458
+ // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
459
+ public static async queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null) {
460
+ const { source, properties, collections, where, order, offset, limit, count } = query;
461
+ const className = modelClassName || (await this.getClassName(perspective));
462
+
463
+ const instanceQueries = [
464
+ buildAuthorAndTimestampQuery(),
465
+ buildSourceQuery(source),
466
+ buildPropertiesQuery(properties),
467
+ buildCollectionsQuery(collections),
468
+ buildWhereQuery(where),
469
+ ];
470
+
471
+ const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
472
+
473
+ const fullQuery = `
474
+ findall([Base, Properties, Collections, Timestamp, Author], (
475
+ subject_class("${className}", SubjectClass),
476
+ instance(SubjectClass, Base),
477
+ ${instanceQueries.filter((q) => q).join(", ")}
478
+ ), UnsortedInstances),
479
+ ${resultSetQueries.filter((q) => q).join(", ")}
480
+ `;
481
+
482
+ return fullQuery;
483
+ }
484
+
485
+ public static async instancesFromPrologResult<T extends Ad4mModel>(
486
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
487
+ perspective: PerspectiveProxy,
488
+ query: Query,
489
+ result: AllInstancesResult
490
+ ): Promise<ResultsWithTotalCount<T>> {
491
+ if (!result?.[0]?.AllInstances) return { results: [], totalCount: 0 };
492
+ // Map results to instances
493
+ const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
494
+ const allInstances = await Promise.all(
495
+ result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
496
+ try {
497
+ const instance = new this(perspective, Base) as any;
498
+ // Remove unrequested attributes from instance
499
+ if (requestedAttribtes.length) {
500
+ Object.keys(instance).forEach((key) => {
501
+ if (!requestedAttribtes.includes(key)) delete instance[key];
502
+ });
503
+ }
504
+ // Collect values to assign to instance
505
+ const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
506
+ await Ad4mModel.assignValuesToInstance(perspective, instance, values);
507
+
508
+ return instance;
509
+ } catch (error) {
510
+ console.error(`Failed to process instance ${Base}:`, error);
511
+ // Return null for failed instances - we'll filter these out below
512
+ return null;
513
+ }
514
+ })
515
+ );
516
+ return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
517
+ }
518
+
519
+ /**
520
+ * Gets all instances of the model in the perspective that match the query params.
521
+ *
522
+ * @param perspective - The perspective to search in
523
+ * @param query - Optional query parameters to filter results
524
+ * @returns Array of matching models
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * // Get all recipes
529
+ * const allRecipes = await Recipe.findAll(perspective);
530
+ *
531
+ * // Get recipes with specific criteria
532
+ * const recipes = await Recipe.findAll(perspective, {
533
+ * where: {
534
+ * name: "Pasta",
535
+ * rating: { gt: 4 }
536
+ * },
537
+ * order: { createdAt: "DESC" },
538
+ * limit: 10
539
+ * });
540
+ * ```
541
+ */
542
+ static async findAll<T extends Ad4mModel>(
543
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
544
+ perspective: PerspectiveProxy,
545
+ query: Query = {}
546
+ ): Promise<T[]> {
547
+ const prologQuery = await this.queryToProlog(perspective, query);
548
+ const result = await perspective.infer(prologQuery);
549
+ const { results } = await this.instancesFromPrologResult(perspective, query, result);
550
+ return results;
551
+ }
552
+
553
+ /**
554
+ * Gets all instances with count of total matches without offset & limit applied.
555
+ *
556
+ * @param perspective - The perspective to search in
557
+ * @param query - Optional query parameters to filter results
558
+ * @returns Object containing results array and total count
559
+ *
560
+ * @example
561
+ * ```typescript
562
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
563
+ * where: { category: "Dessert" },
564
+ * limit: 10
565
+ * });
566
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
567
+ * ```
568
+ */
569
+ static async findAllAndCount<T extends Ad4mModel>(
570
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
571
+ perspective: PerspectiveProxy,
572
+ query: Query = {}
573
+ ): Promise<ResultsWithTotalCount<T>> {
574
+ const prologQuery = await this.queryToProlog(perspective, query);
575
+ const result = await perspective.infer(prologQuery);
576
+ return await this.instancesFromPrologResult(perspective, query, result);
577
+ }
578
+
579
+ /**
580
+ * Helper function for pagination with explicit page size and number.
581
+ *
582
+ * @param perspective - The perspective to search in
583
+ * @param pageSize - Number of items per page
584
+ * @param pageNumber - Which page to retrieve (1-based)
585
+ * @param query - Optional additional query parameters
586
+ * @returns Paginated results with metadata
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * const page = await Recipe.paginate(perspective, 10, 1, {
591
+ * where: { category: "Main Course" }
592
+ * });
593
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
594
+ * ```
595
+ */
596
+ static async paginate<T extends Ad4mModel>(
597
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
598
+ perspective: PerspectiveProxy,
599
+ pageSize: number,
600
+ pageNumber: number,
601
+ query?: Query
602
+ ): Promise<PaginationResult<T>> {
603
+ const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
604
+ const prologQuery = await this.queryToProlog(perspective, paginationQuery);
605
+ const result = await perspective.infer(prologQuery);
606
+ const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
607
+ return { results, totalCount, pageSize, pageNumber };
608
+ }
609
+
610
+ static async countQueryToProlog(perspective: PerspectiveProxy, query: Query = {}, modelClassName?: string | null) {
611
+ const { source, where } = query;
612
+ const className = modelClassName || (await this.getClassName(perspective));
613
+ const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
614
+ const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
615
+
616
+ const fullQuery = `
617
+ findall([Base, Properties, Collections, Timestamp, Author], (
618
+ subject_class("${className}", SubjectClass),
619
+ instance(SubjectClass, Base),
620
+ ${instanceQueries.filter((q) => q).join(", ")}
621
+ ), UnsortedInstances),
622
+ ${resultSetQueries.filter((q) => q).join(", ")}
623
+ `;
624
+
625
+ return fullQuery;
626
+ }
627
+
628
+ /**
629
+ * Gets a count of all matching instances.
630
+ *
631
+ * @param perspective - The perspective to search in
632
+ * @param query - Optional query parameters to filter results
633
+ * @returns Total count of matching entities
634
+ *
635
+ * @example
636
+ * ```typescript
637
+ * const totalRecipes = await Recipe.count(perspective);
638
+ * const activeRecipes = await Recipe.count(perspective, {
639
+ * where: { status: "active" }
640
+ * });
641
+ * ```
642
+ */
643
+ static async count(perspective: PerspectiveProxy, query: Query = {}) {
644
+ const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
645
+
646
+ return result?.[0]?.TotalCount || 0;
647
+ }
648
+
649
+ private async setProperty(key: string, value: any, batchId?: string) {
650
+ const setters = await this.#perspective.infer(
651
+ `subject_class("${this.#subjectClassName}", C), property_setter(C, "${key}", Setter)`
652
+ );
653
+ if (setters && setters.length > 0) {
654
+ const actions = eval(setters[0].Setter);
655
+ const resolveLanguageResults = await this.#perspective.infer(
656
+ `subject_class("${this.#subjectClassName}", C), property_resolve_language(C, "${key}", Language)`
657
+ );
658
+ let resolveLanguage;
659
+ if (resolveLanguageResults && resolveLanguageResults.length > 0) {
660
+ resolveLanguage = resolveLanguageResults[0].Language;
661
+ }
662
+
663
+ if (resolveLanguage) {
664
+ value = await this.#perspective.createExpression(value, resolveLanguage);
665
+ }
666
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
667
+ }
668
+ }
669
+
670
+ private async setCollectionSetter(key: string, value: any, batchId?: string) {
671
+ let collectionSetters = await this.#perspective.infer(
672
+ `subject_class("${this.#subjectClassName}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`
673
+ );
674
+ if (!collectionSetters) collectionSetters = [];
675
+
676
+ if (collectionSetters.length > 0) {
677
+ const actions = eval(collectionSetters[0].Setter);
678
+
679
+ if (value) {
680
+ if (Array.isArray(value)) {
681
+ await this.#perspective.executeAction(
682
+ actions,
683
+ this.#baseExpression,
684
+ value.map((v) => ({ name: "value", value: v })),
685
+ batchId
686
+ );
687
+ } else {
688
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
689
+ }
690
+ }
691
+ }
692
+ }
693
+
694
+ private async setCollectionAdder(key: string, value: any, batchId?: string) {
695
+ let adders = await this.#perspective.infer(
696
+ `subject_class("${this.#subjectClassName}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`
697
+ );
698
+ if (!adders) adders = [];
699
+
700
+ if (adders.length > 0) {
701
+ const actions = eval(adders[0].Adder);
702
+ if (value) {
703
+ if (Array.isArray(value)) {
704
+ await Promise.all(
705
+ value.map((v) =>
706
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
707
+ )
708
+ );
709
+ } else {
710
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
711
+ }
712
+ }
713
+ }
714
+ }
715
+
716
+ private async setCollectionRemover(key: string, value: any, batchId?: string) {
717
+ let removers = await this.#perspective.infer(
718
+ `subject_class("${this.#subjectClassName}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`
719
+ );
720
+ if (!removers) removers = [];
721
+
722
+ if (removers.length > 0) {
723
+ const actions = eval(removers[0].Remover);
724
+ if (value) {
725
+ if (Array.isArray(value)) {
726
+ await Promise.all(
727
+ value.map((v) =>
728
+ this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }], batchId)
729
+ )
730
+ );
731
+ } else {
732
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }], batchId);
733
+ }
734
+ }
735
+ }
736
+ }
737
+
738
+ /**
739
+ * Saves the model instance to the perspective.
740
+ * Creates a new instance with the base expression and links it to the source.
741
+ *
742
+ * @param batchId - Optional batch ID for batch operations
743
+ * @throws Will throw if instance creation, linking, or updating fails
744
+ *
745
+ * @example
746
+ * ```typescript
747
+ * const recipe = new Recipe(perspective);
748
+ * recipe.name = "Spaghetti";
749
+ * recipe.ingredients = ["pasta", "tomato sauce"];
750
+ * await recipe.save();
751
+ *
752
+ * // Or with batch operations:
753
+ * const batchId = await perspective.createBatch();
754
+ * await recipe.save(batchId);
755
+ * await perspective.commitBatch(batchId);
756
+ * ```
757
+ */
758
+ async save(batchId?: string) {
759
+ // We use createSubject's initialValues to set properties (but not collections)
760
+ // We then later use innerUpdate to set collections
761
+
762
+ let batchCreatedHere = false;
763
+ if(!batchId) {
764
+ batchId = await this.perspective.createBatch()
765
+ batchCreatedHere = true;
766
+ }
767
+
768
+
769
+ // First filter out the properties that are not collections (arrays)
770
+ const initialValues = {};
771
+ for (const [key, value] of Object.entries(this)) {
772
+ if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
773
+ initialValues[key] = value;
774
+ }
775
+ }
776
+
777
+ // Create the subject with the initial values
778
+ await this.perspective.createSubject(
779
+ this,
780
+ this.#baseExpression,
781
+ initialValues,
782
+ batchId
783
+ );
784
+
785
+ // Link the subject to the source
786
+ await this.#perspective.add(
787
+ new Link({ source: this.#source, predicate: "ad4m://has_child", target: this.baseExpression }),
788
+ 'shared',
789
+ batchId
790
+ );
791
+
792
+ // Set collections
793
+ await this.innerUpdate(false, batchId)
794
+
795
+ // If we got a batchId passed in, we let the caller decide when to commit.
796
+ // But then we can call getData() since the instance won't exist in the perspective
797
+ // until the bacht is committedl
798
+ if (batchCreatedHere) {
799
+ await this.perspective.commitBatch(batchId)
800
+ await this.getData();
801
+ }
802
+ }
803
+
804
+ private cleanCopy() {
805
+ const cleanCopy = {};
806
+ const props = Object.entries(this);
807
+ for (const [key, value] of props) {
808
+ if (value !== undefined && value !== null && key !== "author" && key !== "timestamp") {
809
+ cleanCopy[key] = value;
810
+ }
811
+ }
812
+ return cleanCopy;
813
+ }
814
+
815
+ private async innerUpdate(setProperties: boolean = true, batchId?: string) {
816
+ this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
817
+
818
+ const entries = Object.entries(this);
819
+ for (const [key, value] of entries) {
820
+ if (value !== undefined && value !== null) {
821
+ if (value?.action) {
822
+ switch (value.action) {
823
+ case "setter":
824
+ await this.setCollectionSetter(key, value.value, batchId);
825
+ break;
826
+ case "adder":
827
+ await this.setCollectionAdder(key, value.value, batchId);
828
+ break;
829
+ case "remover":
830
+ await this.setCollectionRemover(key, value.value, batchId);
831
+ break;
832
+ default:
833
+ await this.setCollectionSetter(key, value.value, batchId);
834
+ break;
835
+ }
836
+ } else if (Array.isArray(value) && value.length > 0) {
837
+ await this.setCollectionSetter(key, value, batchId);
838
+ } else if (value !== undefined && value !== null && value !== "") {
839
+ if (setProperties) {
840
+ await this.setProperty(key, value, batchId);
841
+ }
842
+ }
843
+ }
844
+ }
845
+ }
846
+
847
+ /**
848
+ * Updates the model instance's properties and collections.
849
+ *
850
+ * @param batchId - Optional batch ID for batch operations
851
+ * @throws Will throw if property setting or collection updates fail
852
+ *
853
+ * @example
854
+ * ```typescript
855
+ * const recipe = await Recipe.findAll(perspective)[0];
856
+ * recipe.rating = 5;
857
+ * recipe.ingredients.push("garlic");
858
+ * await recipe.update();
859
+ *
860
+ * // Or with batch operations:
861
+ * const batchId = await perspective.createBatch();
862
+ * await recipe.update(batchId);
863
+ * await perspective.commitBatch(batchId);
864
+ * ```
865
+ */
866
+ async update(batchId?: string) {
867
+ await this.innerUpdate(true, batchId);
868
+ await this.getData();
869
+ }
870
+
871
+ /**
872
+ * Gets the model instance with all properties and collections populated.
873
+ *
874
+ * @returns The populated model instance
875
+ * @throws Will throw if data retrieval fails
876
+ *
877
+ * @example
878
+ * ```typescript
879
+ * const recipe = new Recipe(perspective, existingId);
880
+ * await recipe.get();
881
+ * console.log(recipe.name, recipe.ingredients);
882
+ * ```
883
+ */
884
+ async get() {
885
+ this.#subjectClassName = await this.#perspective.stringOrTemplateObjectToSubjectClassName(this.cleanCopy());
886
+
887
+ return await this.getData();
888
+ }
889
+
890
+ /**
891
+ * Deletes the model instance from the perspective.
892
+ *
893
+ * @param batchId - Optional batch ID for batch operations
894
+ * @throws Will throw if removal fails
895
+ *
896
+ * @example
897
+ * ```typescript
898
+ * const recipe = await Recipe.findAll(perspective)[0];
899
+ * await recipe.delete();
900
+ *
901
+ * // Or with batch operations:
902
+ * const batchId = await perspective.createBatch();
903
+ * await recipe.delete(batchId);
904
+ * await perspective.commitBatch(batchId);
905
+ * ```
906
+ */
907
+ async delete(batchId?: string) {
908
+ await this.#perspective.removeSubject(this, this.#baseExpression, batchId);
909
+ }
910
+
911
+ /**
912
+ * Creates a query builder for fluent query construction.
913
+ *
914
+ * @param perspective - The perspective to query
915
+ * @param query - Optional initial query parameters
916
+ * @returns A new query builder instance
917
+ *
918
+ * @example
919
+ * ```typescript
920
+ * const recipes = await Recipe.query(perspective)
921
+ * .where({ category: "Dessert" })
922
+ * .order({ rating: "DESC" })
923
+ * .limit(5)
924
+ * .run();
925
+ *
926
+ * // With real-time updates
927
+ * await Recipe.query(perspective)
928
+ * .where({ status: "cooking" })
929
+ * .subscribe(recipes => {
930
+ * console.log("Currently cooking:", recipes);
931
+ * });
932
+ * ```
933
+ */
934
+ static query<T extends Ad4mModel>(
935
+ this: typeof Ad4mModel & (new (...args: any[]) => T),
936
+ perspective: PerspectiveProxy,
937
+ query?: Query
938
+ ): ModelQueryBuilder<T> {
939
+ return new ModelQueryBuilder<T>(perspective, this as any, query);
940
+ }
941
+
942
+ /**
943
+ * Creates an Ad4mModel class from a JSON Schema definition.
944
+ *
945
+ * @description
946
+ * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
947
+ * enabling integration with systems that use JSON Schema for type definitions.
948
+ *
949
+ * The method follows a cascading approach for determining predicates:
950
+ * 1. Explicit configuration in options parameter (highest precedence)
951
+ * 2. x-ad4m metadata in the JSON Schema
952
+ * 3. Inference from schema title and property names
953
+ * 4. Error if no namespace can be determined
954
+ *
955
+ * @example
956
+ * ```typescript
957
+ * // With explicit configuration
958
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
959
+ * name: "Person",
960
+ * namespace: "person://",
961
+ * resolveLanguage: "literal"
962
+ * });
963
+ *
964
+ * // With property mapping
965
+ * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
966
+ * name: "Contact",
967
+ * namespace: "contact://",
968
+ * propertyMapping: {
969
+ * "name": "foaf://name",
970
+ * "email": "foaf://mbox"
971
+ * }
972
+ * });
973
+ *
974
+ * // With x-ad4m metadata in schema
975
+ * const schema = {
976
+ * "title": "Product",
977
+ * "x-ad4m": { "namespace": "product://" },
978
+ * "properties": {
979
+ * "name": {
980
+ * "type": "string",
981
+ * "x-ad4m": { "through": "product://title" }
982
+ * }
983
+ * }
984
+ * };
985
+ * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
986
+ * ```
987
+ *
988
+ * @param schema - JSON Schema definition
989
+ * @param options - Configuration options
990
+ * @returns Generated Ad4mModel subclass
991
+ * @throws Error when namespace cannot be inferred
992
+ */
993
+ static fromJSONSchema(
994
+ schema: JSONSchema,
995
+ options: JSONSchemaToModelOptions
996
+ ): typeof Ad4mModel {
997
+ // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
998
+ if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
999
+ 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").');
1000
+ }
1001
+ // Determine namespace with cascading precedence
1002
+ const namespace = this.determineNamespace(schema, options);
1003
+
1004
+ // Create the dynamic class
1005
+ const DynamicModelClass = class extends Ad4mModel {};
1006
+
1007
+ // Set up class metadata
1008
+ Object.defineProperty(DynamicModelClass, 'name', { value: options.name });
1009
+ (DynamicModelClass as any).className = options.name;
1010
+ (DynamicModelClass.prototype as any).className = options.name;
1011
+
1012
+ // Generate properties and collections metadata
1013
+ const properties: any = {};
1014
+ const collections: any = {};
1015
+
1016
+ if (schema.properties) {
1017
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
1018
+ const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
1019
+ const isRequired = schema.required?.includes(propertyName) || false;
1020
+ const isArray = propertySchema.type === 'array';
1021
+
1022
+ if (isArray) {
1023
+ // Handle arrays as collections
1024
+ // Store the singular form as the collection key since SDNA generation expects singular
1025
+ collections[propertyName] = {
1026
+ through: predicate,
1027
+ local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
1028
+ };
1029
+
1030
+ // Define the property on prototype
1031
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
1032
+ configurable: true,
1033
+ writable: true,
1034
+ value: []
1035
+ });
1036
+
1037
+ // Add collection methods
1038
+ const adderName = `add${capitalize(propertyName)}`;
1039
+ const removerName = `remove${capitalize(propertyName)}`;
1040
+ const setterName = `setCollection${capitalize(propertyName)}`;
1041
+
1042
+ (DynamicModelClass.prototype as any)[adderName] = function() {
1043
+ // Placeholder function for SDNA generation
1044
+ };
1045
+ (DynamicModelClass.prototype as any)[removerName] = function() {
1046
+ // Placeholder function for SDNA generation
1047
+ };
1048
+ (DynamicModelClass.prototype as any)[setterName] = function() {
1049
+ // Placeholder function for SDNA generation
1050
+ };
1051
+
1052
+ } else {
1053
+ // Handle regular properties
1054
+ let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
1055
+ // If no specific resolveLanguage for this property, use the global one
1056
+ if (!resolveLanguage && options.resolveLanguage) {
1057
+ resolveLanguage = options.resolveLanguage;
1058
+ }
1059
+ const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
1060
+ const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
1061
+ let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
1062
+
1063
+ // Handle nested objects by serializing to JSON
1064
+ if (propertySchema.type === 'object' && !resolveLanguage) {
1065
+ resolveLanguage = 'literal';
1066
+ console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
1067
+ }
1068
+
1069
+ // Ensure numeric properties use literal language for correct typing
1070
+ if ((resolveLanguage === undefined || resolveLanguage === null) && (propertySchema.type === 'number' || propertySchema.type === 'integer')) {
1071
+ resolveLanguage = 'literal';
1072
+ }
1073
+
1074
+ // If property is required, ensure it has an initial value
1075
+ if (isRequired && !initial) {
1076
+ if (propertySchema.type === 'object') {
1077
+ initial = 'literal://json:{}';
1078
+ } else {
1079
+ initial = "ad4m://undefined";
1080
+ }
1081
+ }
1082
+
1083
+ properties[propertyName] = {
1084
+ through: predicate,
1085
+ required: isRequired,
1086
+ writable: writable,
1087
+ ...(resolveLanguage && { resolveLanguage }),
1088
+ ...(local !== undefined && { local }),
1089
+ ...(initial && { initial })
1090
+ };
1091
+
1092
+ // Define the property on prototype
1093
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
1094
+ configurable: true,
1095
+ writable: true,
1096
+ value: this.getDefaultValueForType(propertySchema.type as string)
1097
+ });
1098
+
1099
+ // Add setter function if writable
1100
+ if (writable) {
1101
+ const setterName = propertyNameToSetterName(propertyName);
1102
+ (DynamicModelClass.prototype as any)[setterName] = function() {
1103
+ // This is a placeholder function that the SDNA generation looks for
1104
+ // The actual setter logic is handled by the Ad4mModel base class
1105
+ };
1106
+ }
1107
+ }
1108
+ }
1109
+ }
1110
+
1111
+ // Validate that at least one property has an initial value (needed for valid SDNA constructor)
1112
+ // Collections don't create constructor actions, only properties with initial values do
1113
+ const hasPropertyWithInitial = Object.values(properties).some((prop: any) => prop.initial);
1114
+
1115
+ if (!hasPropertyWithInitial) {
1116
+ // If no properties have initial values, add a type identifier automatically
1117
+ const typeProperty = `ad4m://type`;
1118
+ const typeValue = `${namespace.replace('://', '')}://instance`;
1119
+
1120
+ properties['__ad4m_type'] = {
1121
+ through: typeProperty,
1122
+ required: true,
1123
+ writable: false,
1124
+ initial: typeValue,
1125
+ flag: true
1126
+ };
1127
+
1128
+ // Add the type property to the prototype
1129
+ Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
1130
+ configurable: true,
1131
+ writable: false,
1132
+ value: typeValue
1133
+ });
1134
+
1135
+ console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
1136
+ }
1137
+
1138
+ // Attach metadata to prototype
1139
+ (DynamicModelClass.prototype as any).__properties = properties;
1140
+ (DynamicModelClass.prototype as any).__collections = collections;
1141
+
1142
+ // Apply the ModelOptions decorator to set up the generateSDNA method
1143
+ const ModelOptionsDecorator = ModelOptions({ name: options.name });
1144
+ ModelOptionsDecorator(DynamicModelClass);
1145
+
1146
+ return DynamicModelClass as typeof Ad4mModel;
1147
+ }
1148
+
1149
+ /**
1150
+ * Determines the namespace for predicates using cascading precedence
1151
+ */
1152
+ private static determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string {
1153
+ // 1. Explicit namespace in options (highest precedence)
1154
+ if (options.namespace) {
1155
+ return options.namespace;
1156
+ }
1157
+
1158
+ // 2. x-ad4m metadata in schema
1159
+ if (schema["x-ad4m"]?.namespace) {
1160
+ return schema["x-ad4m"].namespace;
1161
+ }
1162
+
1163
+ // 3. Infer from schema title
1164
+ if (schema.title) {
1165
+ return `${schema.title.toLowerCase()}://`;
1166
+ }
1167
+
1168
+ // 4. Try to extract from $id if it's a URL
1169
+ if (schema.$id) {
1170
+ try {
1171
+ const url = new URL(schema.$id);
1172
+ const pathParts = url.pathname.split('/').filter(p => p);
1173
+ if (pathParts.length > 0) {
1174
+ const lastPart = pathParts[pathParts.length - 1];
1175
+ const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
1176
+ return `${baseName.toLowerCase()}://`;
1177
+ }
1178
+ } catch {
1179
+ // If $id is not a valid URL, continue to error
1180
+ }
1181
+ }
1182
+
1183
+ // 5. Error if no namespace can be determined
1184
+ throw new Error(
1185
+ `Cannot infer namespace for JSON Schema. Please provide one of:
1186
+ - options.namespace
1187
+ - schema["x-ad4m"].namespace
1188
+ - schema.title
1189
+ - valid schema.$id`
1190
+ );
1191
+ }
1192
+
1193
+ /**
1194
+ * Determines the predicate for a specific property using cascading precedence
1195
+ */
1196
+ private static determinePredicate(
1197
+ schema: JSONSchema,
1198
+ propertyName: string,
1199
+ propertySchema: JSONSchemaProperty,
1200
+ namespace: string,
1201
+ options: JSONSchemaToModelOptions
1202
+ ): string {
1203
+ // 1. Explicit property mapping (highest precedence)
1204
+ if (options.propertyMapping?.[propertyName]) {
1205
+ return options.propertyMapping[propertyName];
1206
+ }
1207
+
1208
+ // 2. x-ad4m metadata in property schema
1209
+ if (propertySchema["x-ad4m"]?.through) {
1210
+ return propertySchema["x-ad4m"].through;
1211
+ }
1212
+
1213
+ // 3. Generate from namespace + property name
1214
+ if (options.predicateTemplate) {
1215
+ return options.predicateTemplate
1216
+ .replace('${namespace}', namespace.replace('://', ''))
1217
+ .replace('${title}', schema.title || '')
1218
+ .replace('${property}', propertyName);
1219
+ }
1220
+
1221
+ // 4. Custom predicate generator
1222
+ if (options.predicateGenerator) {
1223
+ return options.predicateGenerator(schema.title || '', propertyName);
1224
+ }
1225
+
1226
+ // 5. Default: namespace + property name
1227
+ const cleanNamespace = namespace.endsWith('://') ? namespace.slice(0, -3) : namespace;
1228
+ return `${cleanNamespace}://${propertyName}`;
1229
+ }
1230
+
1231
+ /**
1232
+ * Gets property-specific options using cascading precedence
1233
+ */
1234
+ private static getPropertyOption(
1235
+ propertyName: string,
1236
+ propertySchema: JSONSchemaProperty,
1237
+ options: JSONSchemaToModelOptions,
1238
+ optionName: keyof PropertyOptions,
1239
+ defaultValue?: any
1240
+ ): any {
1241
+ // 1. Property-specific options
1242
+ if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
1243
+ return options.propertyOptions[propertyName][optionName];
1244
+ }
1245
+
1246
+ // 2. x-ad4m metadata in property
1247
+ if (propertySchema["x-ad4m"]?.[optionName as keyof JSONSchemaProperty["x-ad4m"]] !== undefined) {
1248
+ return propertySchema["x-ad4m"][optionName as keyof JSONSchemaProperty["x-ad4m"]];
1249
+ }
1250
+
1251
+ // 3. Global option
1252
+ if (options[optionName as keyof JSONSchemaToModelOptions] !== undefined) {
1253
+ return options[optionName as keyof JSONSchemaToModelOptions];
1254
+ }
1255
+
1256
+ // 4. Default value
1257
+ return defaultValue;
1258
+ }
1259
+
1260
+ /**
1261
+ * Gets default value for a JSON Schema type
1262
+ */
1263
+ private static getDefaultValueForType(type: string): any {
1264
+ switch (type) {
1265
+ case 'string': return '';
1266
+ case 'number': return 0;
1267
+ case 'integer': return 0;
1268
+ case 'boolean': return false;
1269
+ case 'array': return [];
1270
+ case 'object': return {};
1271
+ default: return '';
1272
+ }
1273
+ }
1274
+ }
1275
+
1276
+ /** Query builder for Ad4mModel queries.
1277
+ * Allows building queries with a fluent interface and either running them once
1278
+ * or subscribing to updates.
1279
+ *
1280
+ * @example
1281
+ * ```typescript
1282
+ * const builder = Recipe.query(perspective)
1283
+ * .where({ category: "Dessert" })
1284
+ * .order({ rating: "DESC" })
1285
+ * .limit(10);
1286
+ *
1287
+ * // Run once
1288
+ * const recipes = await builder.run();
1289
+ *
1290
+ * // Or subscribe to updates
1291
+ * await builder.subscribe(recipes => {
1292
+ * console.log("Updated recipes:", recipes);
1293
+ * });
1294
+ * ```
1295
+ */
1296
+ export class ModelQueryBuilder<T extends Ad4mModel> {
1297
+ private perspective: PerspectiveProxy;
1298
+ private queryParams: Query = {};
1299
+ private modelClassName: string | null = null;
1300
+ private ctor: typeof Ad4mModel;
1301
+ private currentSubscription?: any;
1302
+
1303
+ constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query) {
1304
+ this.perspective = perspective;
1305
+ this.ctor = ctor;
1306
+ if (query) this.queryParams = query;
1307
+ }
1308
+
1309
+ /**
1310
+ * Disposes of the current subscription if one exists.
1311
+ *
1312
+ * This method:
1313
+ * 1. Stops the keepalive signals to the subscription
1314
+ * 2. Unsubscribes from GraphQL subscription updates
1315
+ * 3. Notifies the backend to clean up subscription resources
1316
+ * 4. Clears the subscription reference
1317
+ *
1318
+ * You should call this method when you're done with a subscription
1319
+ * to prevent memory leaks and ensure proper cleanup.
1320
+ */
1321
+ dispose() {
1322
+ if (this.currentSubscription) {
1323
+ this.currentSubscription.dispose();
1324
+ this.currentSubscription = undefined;
1325
+ }
1326
+ }
1327
+
1328
+ /**
1329
+ * Adds where conditions to the query.
1330
+ *
1331
+ * @param conditions - The conditions to filter by
1332
+ * @returns The query builder for chaining
1333
+ *
1334
+ * @example
1335
+ * ```typescript
1336
+ * .where({
1337
+ * category: "Dessert",
1338
+ * rating: { gt: 4 },
1339
+ * tags: ["vegan", "quick"],
1340
+ * published: true
1341
+ * })
1342
+ * ```
1343
+ */
1344
+ where(conditions: Where): ModelQueryBuilder<T> {
1345
+ this.queryParams.where = conditions;
1346
+ return this;
1347
+ }
1348
+
1349
+ /**
1350
+ * Sets the order for the query results.
1351
+ *
1352
+ * @param orderBy - The ordering criteria
1353
+ * @returns The query builder for chaining
1354
+ *
1355
+ * @example
1356
+ * ```typescript
1357
+ * .order({ createdAt: "DESC" })
1358
+ * ```
1359
+ */
1360
+ order(orderBy: Order): ModelQueryBuilder<T> {
1361
+ this.queryParams.order = orderBy;
1362
+ return this;
1363
+ }
1364
+
1365
+ /**
1366
+ * Sets the maximum number of results to return.
1367
+ *
1368
+ * @param limit - Maximum number of results
1369
+ * @returns The query builder for chaining
1370
+ *
1371
+ * @example
1372
+ * ```typescript
1373
+ * .limit(10)
1374
+ * ```
1375
+ */
1376
+ limit(limit: number): ModelQueryBuilder<T> {
1377
+ this.queryParams.limit = limit;
1378
+ return this;
1379
+ }
1380
+
1381
+ /**
1382
+ * Sets the number of results to skip.
1383
+ *
1384
+ * @param offset - Number of results to skip
1385
+ * @returns The query builder for chaining
1386
+ *
1387
+ * @example
1388
+ * ```typescript
1389
+ * .offset(20) // Skip first 20 results
1390
+ * ```
1391
+ */
1392
+ offset(offset: number): ModelQueryBuilder<T> {
1393
+ this.queryParams.offset = offset;
1394
+ return this;
1395
+ }
1396
+
1397
+ /**
1398
+ * Sets the source filter for the query.
1399
+ *
1400
+ * @param source - The source to filter by
1401
+ * @returns The query builder for chaining
1402
+ *
1403
+ * @example
1404
+ * ```typescript
1405
+ * .source("ad4m://self")
1406
+ * ```
1407
+ */
1408
+ source(source: string): ModelQueryBuilder<T> {
1409
+ this.queryParams.source = source;
1410
+ return this;
1411
+ }
1412
+
1413
+ /**
1414
+ * Specifies which properties to include in the results.
1415
+ *
1416
+ * @param properties - Array of property names to include
1417
+ * @returns The query builder for chaining
1418
+ *
1419
+ * @example
1420
+ * ```typescript
1421
+ * .properties(["name", "description", "rating"])
1422
+ * ```
1423
+ */
1424
+ properties(properties: string[]): ModelQueryBuilder<T> {
1425
+ this.queryParams.properties = properties;
1426
+ return this;
1427
+ }
1428
+
1429
+ /**
1430
+ * Specifies which collections to include in the results.
1431
+ *
1432
+ * @param collections - Array of collection names to include
1433
+ * @returns The query builder for chaining
1434
+ *
1435
+ * @example
1436
+ * ```typescript
1437
+ * .collections(["ingredients", "steps"])
1438
+ * ```
1439
+ */
1440
+ collections(collections: string[]): ModelQueryBuilder<T> {
1441
+ this.queryParams.collections = collections;
1442
+ return this;
1443
+ }
1444
+
1445
+ overrideModelClassName(className: string): ModelQueryBuilder<T> {
1446
+ this.modelClassName = className;
1447
+ return this;
1448
+ }
1449
+
1450
+ /**
1451
+ * Executes the query once and returns the results.
1452
+ *
1453
+ * @returns Array of matching entities
1454
+ *
1455
+ * @example
1456
+ * ```typescript
1457
+ * const recipes = await Recipe.query(perspective)
1458
+ * .where({ category: "Dessert" })
1459
+ * .get();
1460
+ * ```
1461
+ */
1462
+ async get(): Promise<T[]> {
1463
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
1464
+ const result = await this.perspective.infer(query);
1465
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
1466
+ return results as T[];
1467
+ }
1468
+
1469
+ /**
1470
+ * Subscribes to the query and receives updates when results change.
1471
+ *
1472
+ * This method:
1473
+ * 1. Creates and initializes a Prolog query subscription
1474
+ * 2. Sets up the callback to process future updates
1475
+ * 3. Returns the initial results immediately
1476
+ *
1477
+ * Remember to call dispose() when you're done with the subscription
1478
+ * to clean up resources.
1479
+ *
1480
+ * @param callback - Function to call with updated results
1481
+ * @returns Initial results array
1482
+ *
1483
+ * @example
1484
+ * ```typescript
1485
+ * const builder = Recipe.query(perspective)
1486
+ * .where({ status: "cooking" });
1487
+ *
1488
+ * const initialRecipes = await builder.subscribe(recipes => {
1489
+ * console.log("Updated recipes:", recipes);
1490
+ * });
1491
+ *
1492
+ * // When done with subscription:
1493
+ * builder.dispose();
1494
+ * ```
1495
+ */
1496
+ async subscribe(callback: (results: T[]) => void): Promise<T[]> {
1497
+ // Clean up any existing subscription
1498
+ this.dispose();
1499
+
1500
+ const query = await this.ctor.queryToProlog(this.perspective, this.queryParams, this.modelClassName);
1501
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
1502
+
1503
+ const processResults = async (result: AllInstancesResult) => {
1504
+ const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
1505
+ callback(results as T[]);
1506
+ };
1507
+
1508
+ this.currentSubscription.onResult(processResults);
1509
+ const { results } = await this.ctor.instancesFromPrologResult(
1510
+ this.perspective,
1511
+ this.queryParams,
1512
+ this.currentSubscription.result
1513
+ );
1514
+ return results as T[];
1515
+ }
1516
+
1517
+ /**
1518
+ * Gets the total count of matching entities.
1519
+ *
1520
+ * @returns Total count
1521
+ *
1522
+ * @example
1523
+ * ```typescript
1524
+ * const totalDesserts = await Recipe.query(perspective)
1525
+ * .where({ category: "Dessert" })
1526
+ * .count();
1527
+ * ```
1528
+ */
1529
+ async count(): Promise<number> {
1530
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1531
+ const result = await this.perspective.infer(query);
1532
+ return result?.[0]?.TotalCount || 0;
1533
+ }
1534
+
1535
+ /**
1536
+ * Subscribes to count updates for matching entities.
1537
+ *
1538
+ * This method:
1539
+ * 1. Creates and initializes a Prolog query subscription for the count
1540
+ * 2. Sets up the callback to process future count updates
1541
+ * 3. Returns the initial count immediately
1542
+ *
1543
+ * Remember to call dispose() when you're done with the subscription
1544
+ * to clean up resources.
1545
+ *
1546
+ * @param callback - Function to call with updated count
1547
+ * @returns Initial count
1548
+ *
1549
+ * @example
1550
+ * ```typescript
1551
+ * const builder = Recipe.query(perspective)
1552
+ * .where({ status: "active" });
1553
+ *
1554
+ * const initialCount = await builder.countSubscribe(count => {
1555
+ * console.log("Active items:", count);
1556
+ * });
1557
+ *
1558
+ * // When done with subscription:
1559
+ * builder.dispose();
1560
+ * ```
1561
+ */
1562
+ async countSubscribe(callback: (count: number) => void): Promise<number> {
1563
+ // Clean up any existing subscription
1564
+ this.dispose();
1565
+
1566
+ const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams, this.modelClassName);
1567
+ this.currentSubscription = await this.perspective.subscribeInfer(query);
1568
+
1569
+ const processResults = async (result: any) => {
1570
+ const newCount = result?.[0]?.TotalCount || 0;
1571
+ callback(newCount);
1572
+ };
1573
+
1574
+ this.currentSubscription.onResult(processResults);
1575
+ return this.currentSubscription.result?.[0]?.TotalCount || 0;
1576
+ }
1577
+
1578
+ /**
1579
+ * Gets a page of results with pagination metadata.
1580
+ *
1581
+ * @param pageSize - Number of items per page
1582
+ * @param pageNumber - Which page to retrieve (1-based)
1583
+ * @returns Paginated results with metadata
1584
+ *
1585
+ * @example
1586
+ * ```typescript
1587
+ * const page = await Recipe.query(perspective)
1588
+ * .where({ category: "Main" })
1589
+ * .paginate(10, 1);
1590
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1591
+ * ```
1592
+ */
1593
+ async paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>> {
1594
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1595
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1596
+ const result = await this.perspective.infer(prologQuery);
1597
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result)) as ResultsWithTotalCount<T>;
1598
+ return { results, totalCount, pageSize, pageNumber };
1599
+ }
1600
+
1601
+ /**
1602
+ * Subscribes to paginated results updates.
1603
+ *
1604
+ * This method:
1605
+ * 1. Creates and initializes a Prolog query subscription for the paginated results
1606
+ * 2. Sets up the callback to process future page updates
1607
+ * 3. Returns the initial page immediately
1608
+ *
1609
+ * Remember to call dispose() when you're done with the subscription
1610
+ * to clean up resources.
1611
+ *
1612
+ * @param pageSize - Number of items per page
1613
+ * @param pageNumber - Which page to retrieve (1-based)
1614
+ * @param callback - Function to call with updated pagination results
1615
+ * @returns Initial pagination results
1616
+ *
1617
+ * @example
1618
+ * ```typescript
1619
+ * const builder = Recipe.query(perspective)
1620
+ * .where({ category: "Main" });
1621
+ *
1622
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1623
+ * console.log("Updated page:", page.results);
1624
+ * });
1625
+ *
1626
+ * // When done with subscription:
1627
+ * builder.dispose();
1628
+ * ```
1629
+ */
1630
+ async paginateSubscribe(
1631
+ pageSize: number,
1632
+ pageNumber: number,
1633
+ callback: (results: PaginationResult<T>) => void
1634
+ ): Promise<PaginationResult<T>> {
1635
+ // Clean up any existing subscription
1636
+ this.dispose();
1637
+
1638
+ const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1639
+ const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery, this.modelClassName);
1640
+ this.currentSubscription = await this.perspective.subscribeInfer(prologQuery);
1641
+
1642
+ const processResults = async (r: AllInstancesResult) => {
1643
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r)) as ResultsWithTotalCount<T>;
1644
+ callback({ results, totalCount, pageSize, pageNumber });
1645
+ };
1646
+
1647
+ this.currentSubscription.onResult(processResults);
1648
+ const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, this.currentSubscription.result)) as ResultsWithTotalCount<T>;
1649
+ return { results, totalCount, pageSize, pageNumber };
1650
+ }
1651
+ }