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

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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
@@ -58,16 +58,74 @@ type Where = {
58
58
  type Order = {
59
59
  [propertyName: string]: "ASC" | "DESC";
60
60
  };
61
+ /**
62
+ * Discriminated union for parent-scoped queries.
63
+ *
64
+ * **Model form** (preferred) — predicate auto-resolved from the parent model's
65
+ * relation metadata. Use `field` to disambiguate when the parent has multiple
66
+ * relations targeting the same child class.
67
+ *
68
+ * **Raw form** — explicit predicate string, no metadata lookup.
69
+ */
70
+ export type ParentScope = {
71
+ model: typeof Ad4mModel;
72
+ id: string;
73
+ field?: string;
74
+ } | {
75
+ id: string;
76
+ predicate: string;
77
+ };
78
+ /**
79
+ * Describes which relations to eager-load when querying.
80
+ *
81
+ * Each value is either:
82
+ * - `true` — hydrate the relation one level deep
83
+ * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * // One level deep
88
+ * { comments: true }
89
+ *
90
+ * // Sub-query: only the 5 most-recent comments
91
+ * { comments: { order: { createdAt: 'DESC' }, limit: 5 } }
92
+ *
93
+ * // Nested eager-load
94
+ * { comments: { include: { author: true } } }
95
+ * ```
96
+ */
97
+ export interface IncludeMap {
98
+ [relation: string]: boolean | RelationSubQuery;
99
+ }
61
100
  export type Query = {
62
- source?: string;
101
+ /** Filter to instances that are the target of a link from a given parent. */
102
+ parent?: ParentScope;
63
103
  properties?: string[];
64
- collections?: string[];
104
+ include?: IncludeMap;
65
105
  where?: Where;
66
106
  order?: Order;
67
107
  offset?: number;
68
108
  limit?: number;
69
109
  count?: boolean;
70
110
  };
111
+ /**
112
+ * Sub-query options for a specific relation inside an `IncludeMap`.
113
+ *
114
+ * Equivalent to `Query` without top-level scoping (`parent`) or `count`,
115
+ * since the result set is already constrained to the linked relation.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
120
+ * ```
121
+ */
122
+ export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
123
+ /**
124
+ * Options accepted by the instance `get()` method.
125
+ *
126
+ * A subset of `Query` — only hydration controls apply to a single known instance.
127
+ */
128
+ export type GetOptions = Pick<Query, 'include' | 'properties'>;
71
129
  export type AllInstancesResult = {
72
130
  AllInstances: Ad4mModel[];
73
131
  TotalCount?: number;
@@ -93,8 +151,8 @@ export interface PropertyMetadata {
93
151
  predicate: string;
94
152
  /** Whether the property is required */
95
153
  required: boolean;
96
- /** Whether the property is writable */
97
- writable: boolean;
154
+ /** Whether the property is read-only */
155
+ readOnly: boolean;
98
156
  /** Initial value if specified */
99
157
  initial?: string;
100
158
  /** Language for resolution (e.g., "literal") */
@@ -113,55 +171,51 @@ export interface PropertyMetadata {
113
171
  flag?: boolean;
114
172
  }
115
173
  /**
116
- * Metadata for a single collection extracted from decorators.
174
+ * Metadata for a single relation extracted from decorators.
117
175
  */
118
- export interface CollectionMetadata {
119
- /** The collection name */
176
+ export interface RelationMetadata {
177
+ /** The relation name */
120
178
  name: string;
121
179
  /** The predicate URI (through value) */
122
180
  predicate: string;
123
- /** Filter conditions */
124
- where?: {
125
- isInstance?: any;
126
- prologCondition?: string;
127
- condition?: string;
128
- };
129
181
  /** Custom SurrealQL getter code */
130
182
  getter?: string;
131
183
  /** Whether stored locally only */
132
184
  local?: boolean;
185
+ /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
186
+ direction?: 'forward' | 'reverse';
133
187
  }
134
188
  /**
135
189
  * Complete model metadata extracted from decorators.
136
190
  */
137
191
  export interface ModelMetadata {
138
- /** The model class name from @ModelOptions */
192
+ /** The model class name from @Model */
139
193
  className: string;
140
194
  /** Map of property name to metadata */
141
195
  properties: Record<string, PropertyMetadata>;
142
- /** Map of collection name to metadata */
143
- collections: Record<string, CollectionMetadata>;
196
+ /** Map of relation name to metadata */
197
+ relations: Record<string, RelationMetadata>;
144
198
  }
145
199
  /**
146
200
  * Base class for defining data models in AD4M.
147
201
  *
148
202
  * @description
149
203
  * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
150
- * Each model instance is represented as a subgraph in the perspective, with properties and collections
204
+ * Each model instance is represented as a subgraph in the perspective, with properties and relations
151
205
  * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
152
206
  * instances based on their properties and relationships.
153
207
  *
154
208
  * Key concepts:
155
209
  * - Each model instance has a unique base expression that serves as its identifier
156
210
  * - Properties are stored as links with predicates defined by the `through` option
157
- * - Collections represent one-to-many relationships as sets of links
211
+ * - Relations represent one-to-many relationships as sets of links
158
212
  * - Queries are translated to Prolog for efficient graph pattern matching
159
213
  * - Changes are tracked through the perspective's subscription system
160
214
  *
161
215
  * @example
162
216
  * ```typescript
163
217
  * // Define a recipe model
164
- * @ModelOptions({ name: "Recipe" })
218
+ * @Model({ name: "Recipe" })
165
219
  * class Recipe extends Ad4mModel {
166
220
  * // Required property with literal value
167
221
  * @Property({
@@ -189,15 +243,12 @@ export interface ModelMetadata {
189
243
  * })
190
244
  * averageRating: number = 0;
191
245
  *
192
- * // Collection of ingredients
193
- * @Collection({ through: "recipe://ingredient" })
194
- * ingredients: string[] = [];
246
+ * // Relation of ingredients
247
+ * @HasMany({ through: "recipe://ingredient" })
248
+ * ingredients: string[] = [];
195
249
  *
196
- * // Collection of comments that are instances of another model
197
- * @Collection({
198
- * through: "recipe://comment",
199
- * where: { isInstance: Comment }
200
- * })
250
+ * // Relation of comments linked to another model
251
+ * @HasMany(() => Comment, { through: "recipe://comment" })
201
252
  * comments: Comment[] = [];
202
253
  * }
203
254
  *
@@ -242,11 +293,33 @@ export interface ModelMetadata {
242
293
  * ```
243
294
  */
244
295
  export declare class Ad4mModel {
245
- #private;
296
+ private _baseExpression;
297
+ private _subjectClassName;
298
+ private _perspective;
299
+ private _snapshot;
246
300
  author: string;
247
301
  createdAt: any;
248
302
  updatedAt: any;
249
303
  private static classNamesByClass;
304
+ /**
305
+ * Generates the SDNA (Subject DNA) Prolog rules for this model class.
306
+ * Injected at class-definition time by the `@Model` decorator.
307
+ * Returns a default value on un-decorated base classes.
308
+ */
309
+ static generateSDNA(): {
310
+ sdna: string;
311
+ name: string;
312
+ };
313
+ /**
314
+ * Generates the SHACL shape graph for this model class.
315
+ * Injected at class-definition time by the `@Model` decorator.
316
+ * Returns `{ shape: null, name: '' }` on un-decorated base classes —
317
+ * the decorator's `parentSHACL?.shape?.nodeShapeUri` check handles this.
318
+ */
319
+ static generateSHACL(): {
320
+ shape: any;
321
+ name: string;
322
+ };
250
323
  static getClassName(perspective: PerspectiveProxy): Promise<string>;
251
324
  /**
252
325
  * Backwards compatibility alias for createdAt.
@@ -257,38 +330,38 @@ export declare class Ad4mModel {
257
330
  * Extracts metadata from decorators for query building.
258
331
  *
259
332
  * @description
260
- * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
333
+ * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)
261
334
  * and returns it in a structured format that's easier to work with for query builders
262
335
  * and other systems that need to introspect model structure.
263
336
  *
264
337
  * The metadata includes:
265
- * - Class name from @ModelOptions
338
+ * - Class name from @Model
266
339
  * - Property metadata (predicates, types, constraints, etc.)
267
- * - Collection metadata (predicates, filters, etc.)
340
+ * - Relation metadata (predicates, filters, etc.)
268
341
  *
269
342
  * For models created via `fromJSONSchema()`, this method will derive metadata from
270
- * the stored `__properties` and `__collections` structures that were populated during
271
- * the dynamic class creation. If these structures are empty but a JSON schema was
272
- * attached to the class, it can fall back to deriving metadata from that schema.
343
+ * the WeakMap registries that were populated during the dynamic class creation.
344
+ * If these structures are empty but a JSON schema was attached to the class,
345
+ * it can fall back to deriving metadata from that schema.
273
346
  *
274
- * @returns Structured metadata object containing className, properties, and collections
275
- * @throws Error if the class doesn't have @ModelOptions decorator
347
+ * @returns Structured metadata object containing className, properties, and relations
348
+ * @throws Error if the class doesn't have @Model decorator
276
349
  *
277
350
  * @example
278
351
  * ```typescript
279
- * @ModelOptions({ name: "Recipe" })
352
+ * @Model({ name: "Recipe" })
280
353
  * class Recipe extends Ad4mModel {
281
354
  * @Property({ through: "recipe://name", resolveLanguage: "literal" })
282
355
  * name: string = "";
283
356
  *
284
- * @Collection({ through: "recipe://ingredient" })
357
+ * @HasMany({ through: "recipe://ingredient" })
285
358
  * ingredients: string[] = [];
286
359
  * }
287
360
  *
288
361
  * const metadata = Recipe.getModelMetadata();
289
362
  * console.log(metadata.className); // "Recipe"
290
363
  * console.log(metadata.properties.name.predicate); // "recipe://name"
291
- * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
364
+ * console.log(metadata.relations.ingredients.predicate); // "recipe://ingredient"
292
365
  * ```
293
366
  */
294
367
  static getModelMetadata(): ModelMetadata;
@@ -296,7 +369,8 @@ export declare class Ad4mModel {
296
369
  * Constructs a new model instance.
297
370
  *
298
371
  * @param perspective - The perspective where this model will be stored
299
- * @param baseExpression - Optional unique identifier for this instance
372
+ * @param baseExpression - Optional expression URI for this instance.
373
+ * If omitted, a random Literal URL is generated.
300
374
  * @param source - Optional source expression this instance is linked to
301
375
  *
302
376
  * @example
@@ -305,15 +379,16 @@ export declare class Ad4mModel {
305
379
  * const recipe = new Recipe(perspective);
306
380
  *
307
381
  * // Create with specific base expression
308
- * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
309
- *
310
- * // Create with source link
311
- * const recipe = new Recipe(perspective, undefined, "cookbook://desserts");
382
+ * const recipe = new Recipe(perspective, "literal://...");
312
383
  * ```
313
384
  */
314
- constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string);
385
+ constructor(perspective: PerspectiveProxy, baseExpression?: string);
386
+ /**
387
+ * The unique identifier (expression URI) of this model instance.
388
+ */
389
+ get id(): string;
315
390
  /**
316
- * Gets the base expression of the subject.
391
+ * @deprecated Use `.id` instead. Will be removed in a future version.
317
392
  */
318
393
  get baseExpression(): string;
319
394
  /**
@@ -327,10 +402,10 @@ export declare class Ad4mModel {
327
402
  */
328
403
  private getPropertyMetadata;
329
404
  /**
330
- * Get collection metadata from decorator (Phase 1: Prolog-free refactor)
405
+ * Get relation options from decorator
331
406
  * @private
332
407
  */
333
- private getCollectionMetadata;
408
+ private getRelationOptions;
334
409
  /**
335
410
  * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
336
411
  * Replaces Prolog query: property_setter(C, key, Setter)
@@ -338,19 +413,126 @@ export declare class Ad4mModel {
338
413
  */
339
414
  private generatePropertySetterAction;
340
415
  /**
341
- * Generate collection action from metadata (Phase 1: Prolog-free refactor)
416
+ * Generate relation action from metadata (Phase 1: Prolog-free refactor)
342
417
  * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
343
418
  * @private
344
419
  */
345
- private generateCollectionAction;
420
+ private generateRelationAction;
421
+ /**
422
+ * Resolves a raw link target value into a hydrated property value.
423
+ *
424
+ * Handles, in order:
425
+ * 1. Non-literal expression resolution (`perspective.getExpression`)
426
+ * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
427
+ * 3. Primitive type coercion (string → number / boolean)
428
+ * 4. Transform function application
429
+ *
430
+ * @param target - The raw target string from the link
431
+ * @param propMeta - Property metadata from the decorator registry
432
+ * @param perspective - The perspective for expression resolution
433
+ * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
434
+ * @returns The resolved value
435
+ * @private
436
+ */
437
+ private static hydratePropertyValue;
438
+ /**
439
+ * Link shape accepted by `hydrateFromLinks`.
440
+ * Both `getData()` and `instancesFromSurrealResult()` produce this shape.
441
+ */
442
+ private static readonly _linkShape;
443
+ /**
444
+ * Hydrates an instance from an array of raw links.
445
+ *
446
+ * Processes properties (latest-wins semantics), relations
447
+ * (chronological accumulation), and timestamps/author in a single
448
+ * pass over the links array.
449
+ *
450
+ * @param instance - The blank model instance to populate
451
+ * @param links - Array of link objects (predicate, target, author?, timestamp?)
452
+ * @param metadata - Model metadata from `getModelMetadata()`
453
+ * @param perspective - The perspective for expression resolution
454
+ * @param requestedProperties - Optional sparse fieldset; when provided, only these
455
+ * property names are hydrated (relations are unaffected).
456
+ * Omit or pass `undefined` to hydrate all properties.
457
+ * @private
458
+ */
459
+ private static hydrateFromLinks;
346
460
  static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
461
+ /**
462
+ * Captures a shallow snapshot of the instance's current property and
463
+ * relation values. Called automatically after hydration (`get()`,
464
+ * query results). The snapshot is used by `isDirty()`,
465
+ * `changedFields()`, and by `update()` to skip unchanged fields.
466
+ * @private
467
+ */
468
+ /**
469
+ * Normalize a value for snapshot storage.
470
+ * Arrays of model instances are reduced to their `.id` strings so that
471
+ * dirty-tracking compares stable identifiers instead of object references.
472
+ */
473
+ private static normalizeValue;
474
+ /**
475
+ * @param includedRelations Controls which relation fields are recorded
476
+ * in the snapshot for dirty-tracking:
477
+ * • `undefined` (default) — snapshot ALL relations (used by `.get()`,
478
+ * `.create()`, `.save()` etc. where full hydration has occurred).
479
+ * • `IncludeMap` object (e.g. `{ views: true }`) — only snapshot the
480
+ * relations named in the map. Fields not listed are omitted from
481
+ * the snapshot so that `changedFields()` ignores them.
482
+ * • `null` / empty object — skip ALL relations (used by bare
483
+ * subscriptions that don't eagerly load relations).
484
+ */
485
+ private takeSnapshot;
486
+ /**
487
+ * Returns `true` if any tracked property or relation has changed
488
+ * since the last hydration (or since `takeSnapshot()` was last called).
489
+ *
490
+ * Always returns `true` if no snapshot exists (e.g. a freshly
491
+ * constructed instance that hasn't been fetched yet).
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * const recipe = await Recipe.create(perspective, { name: "Pasta" });
496
+ * recipe.isDirty(); // false — just hydrated
497
+ * recipe.name = "Risotto";
498
+ * recipe.isDirty(); // true
499
+ * ```
500
+ */
501
+ isDirty(): boolean;
502
+ /**
503
+ * Returns the names of properties/relations that differ from the
504
+ * snapshot taken at the last hydration.
505
+ *
506
+ * Returns **all** field names if no snapshot exists.
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * recipe.name = "New Name";
511
+ * recipe.changedFields(); // ["name"]
512
+ * ```
513
+ */
514
+ changedFields(): string[];
347
515
  private getData;
348
516
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
349
517
  /**
350
- * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
518
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
351
519
  * @private
352
520
  */
353
521
  private static evaluateCustomGettersForInstance;
522
+ /**
523
+ * Hydrates relation fields on instances according to the provided IncludeMap.
524
+ *
525
+ * For each relation listed in `includeMap`, the raw expression-URI strings
526
+ * stored on the instance are replaced with fully-hydrated model instances
527
+ * (fetched via the relation's `target()` class). Nested IncludeMaps are
528
+ * supported for multi-level eager loading.
529
+ *
530
+ * @param instances - The instances whose relations should be hydrated
531
+ * @param perspective - The perspective to fetch related instances from
532
+ * @param includeMap - Describes which relations to hydrate
533
+ * @private
534
+ */
535
+ private static hydrateRelations;
354
536
  /**
355
537
  * Generates a SurrealQL query from a Query object.
356
538
  *
@@ -362,18 +544,18 @@ export declare class Ad4mModel {
362
544
  *
363
545
  * The generated query uses a CTE (Common Table Expression) pattern:
364
546
  * 1. First, identify candidate base expressions by filtering links based on where conditions
365
- * 2. Then, for each candidate base, resolve properties and collections via subqueries
547
+ * 2. Then, for each candidate base, resolve properties and relations via subqueries
366
548
  * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
367
549
  *
368
550
  * Key architectural notes:
369
551
  * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
370
552
  * - No SDNA knowledge at the database level
371
553
  * - Properties are resolved via subqueries that look for links with specific predicates
372
- * - Collections are similar but return multiple values instead of one
554
+ * - Relations are similar but return multiple values instead of one
373
555
  * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
374
556
  *
375
557
  * @param perspective - The perspective to query (used for metadata extraction)
376
- * @param query - Query parameters (where, order, limit, offset, properties, collections)
558
+ * @param query - Query parameters (where, order, limit, offset, properties, relations)
377
559
  * @returns Complete SurrealQL query string ready for execution
378
560
  *
379
561
  * @example
@@ -440,21 +622,21 @@ export declare class Ad4mModel {
440
622
  * Builds the SELECT fields for SurrealQL queries.
441
623
  *
442
624
  * @description
443
- * Generates the field list for the SELECT clause, resolving properties and collections
625
+ * Generates the field list for the SELECT clause, resolving properties and relations
444
626
  * via subqueries. Each property is fetched with a subquery that finds the link with the
445
- * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
627
+ * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
446
628
  *
447
629
  * Field types:
448
630
  * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
449
- * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
631
+ * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
450
632
  * - Author/Timestamp: Always included to provide metadata about each instance
451
633
  *
452
- * If properties or collections arrays are provided, only those fields are included.
453
- * Otherwise, all properties/collections from metadata are included.
634
+ * If properties or relations arrays are provided, only those fields are included.
635
+ * Otherwise, all properties/relations from metadata are included.
454
636
  *
455
- * @param metadata - Model metadata containing property and collection predicates
637
+ * @param metadata - Model metadata containing property and relation predicates
456
638
  * @param properties - Optional array of property names to include (default: all)
457
- * @param collections - Optional array of collection names to include (default: all)
639
+ * @param relations - Optional array of relation names to include (default: all)
458
640
  * @returns Comma-separated SELECT field list
459
641
  *
460
642
  * @private
@@ -527,6 +709,27 @@ export declare class Ad4mModel {
527
709
  * ```
528
710
  */
529
711
  static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T[]>;
712
+ /**
713
+ * Finds the first instance matching the query, or `null` if none exists.
714
+ *
715
+ * Equivalent to `findAll` with `limit: 1` — only one instance is hydrated.
716
+ *
717
+ * @param perspective - The perspective to search in
718
+ * @param query - Optional query parameters to filter results
719
+ * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
720
+ * @returns The first matching instance, or `null`
721
+ *
722
+ * @example
723
+ * ```typescript
724
+ * const recipe = await Recipe.findOne(perspective, {
725
+ * where: { name: "Pasta" }
726
+ * });
727
+ * if (recipe) {
728
+ * console.log(recipe.name);
729
+ * }
730
+ * ```
731
+ */
732
+ static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T | null>;
530
733
  /**
531
734
  * Gets all instances with count of total matches without offset & limit applied.
532
735
  *
@@ -602,55 +805,47 @@ export declare class Ad4mModel {
602
805
  */
603
806
  static count(perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): any;
604
807
  private setProperty;
605
- private setCollectionSetter;
606
- private setCollectionAdder;
607
- private setCollectionRemover;
808
+ /** Resolve a relation argument to a plain string ID. Accepts either a raw
809
+ * string ID or an Ad4mModel instance (in which case `.id` is used). */
810
+ private resolveRelationId;
811
+ private setRelationValues;
812
+ private addRelationValue;
813
+ private removeRelationValue;
608
814
  /**
609
815
  * Saves the model instance to the perspective.
610
- * Creates a new instance with the base expression and links it to the source.
816
+ *
817
+ * **New instances** (no snapshot yet): creates the subject via
818
+ * `createSubject` with initial scalar values, then sets relations
819
+ * via `innerUpdate`.
820
+ *
821
+ * **Existing instances** (snapshot present, i.e. fetched via `get()`
822
+ * or a query): updates only dirty fields via `innerUpdate`, then
823
+ * refreshes from the perspective.
611
824
  *
612
825
  * @param batchId - Optional batch ID for batch operations
613
826
  * @throws Will throw if instance creation, linking, or updating fails
614
827
  *
615
828
  * @example
616
829
  * ```typescript
830
+ * // Create
617
831
  * const recipe = new Recipe(perspective);
618
832
  * recipe.name = "Spaghetti";
619
- * recipe.ingredients = ["pasta", "tomato sauce"];
620
833
  * await recipe.save();
621
834
  *
622
- * // Or with batch operations:
623
- * const batchId = await perspective.createBatch();
624
- * await recipe.save(batchId);
625
- * await perspective.commitBatch(batchId);
835
+ * // Update
836
+ * recipe.rating = 10;
837
+ * await recipe.save();
626
838
  * ```
627
839
  */
628
840
  save(batchId?: string): Promise<void>;
629
841
  private cleanCopy;
630
842
  private innerUpdate;
631
843
  /**
632
- * Updates the model instance's properties and collections.
633
- *
634
- * @param batchId - Optional batch ID for batch operations
635
- * @throws Will throw if property setting or collection updates fail
636
- *
637
- * @example
638
- * ```typescript
639
- * const recipe = await Recipe.findAll(perspective)[0];
640
- * recipe.rating = 5;
641
- * recipe.ingredients.push("garlic");
642
- * await recipe.update();
643
- *
644
- * // Or with batch operations:
645
- * const batchId = await perspective.createBatch();
646
- * await recipe.update(batchId);
647
- * await perspective.commitBatch(batchId);
648
- * ```
649
- */
650
- update(batchId?: string): Promise<void>;
651
- /**
652
- * Gets the model instance with all properties and collections populated.
844
+ * Gets the model instance with all properties and relations populated.
653
845
  *
846
+ * @param optsOrInclude - Optional hydration options. Accepts two forms:
847
+ * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`
848
+ * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)
654
849
  * @returns The populated model instance
655
850
  * @throws Will throw if data retrieval fails
656
851
  *
@@ -659,9 +854,15 @@ export declare class Ad4mModel {
659
854
  * const recipe = new Recipe(perspective, existingId);
660
855
  * await recipe.get();
661
856
  * console.log(recipe.name, recipe.ingredients);
857
+ *
858
+ * // Shorthand — pass IncludeMap directly:
859
+ * await recipe.get({ ingredients: true });
860
+ *
861
+ * // Full options — includes sparse fieldset:
862
+ * await recipe.get({ include: { ingredients: true }, properties: ['name'] });
662
863
  * ```
663
864
  */
664
- get(): Promise<this>;
865
+ get(optsOrInclude?: GetOptions | IncludeMap): Promise<this>;
665
866
  /**
666
867
  * Deletes the model instance from the perspective.
667
868
  *
@@ -680,6 +881,140 @@ export declare class Ad4mModel {
680
881
  * ```
681
882
  */
682
883
  delete(batchId?: string): Promise<void>;
884
+ /**
885
+ * Options for `Ad4mModel.create()`.
886
+ */
887
+ static readonly CreateOptions: undefined;
888
+ /**
889
+ * Creates and saves a new model instance in one step.
890
+ *
891
+ * @param perspective - The perspective to create the instance in
892
+ * @param data - Property values to assign before saving
893
+ * @param options - Optional settings:
894
+ * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
895
+ * be used to create an incoming link from the parent to the new instance.
896
+ * - `batchId` — an existing batch id; when provided the link write and
897
+ * `save()` are added to the batch instead of committed immediately.
898
+ * @returns The saved model instance
899
+ *
900
+ * @example
901
+ * ```typescript
902
+ * // Simple create
903
+ * const recipe = await Recipe.create(perspective, {
904
+ * name: "Spaghetti",
905
+ * rating: 5,
906
+ * });
907
+ *
908
+ * // Create under a parent (link auto-created)
909
+ * const comment = await Comment.create(perspective, { text: "Great!" }, {
910
+ * parent: { model: Post, id: postId },
911
+ * });
912
+ *
913
+ * // Create inside a transaction
914
+ * await Ad4mModel.transaction(perspective, async (tx) => {
915
+ * await Recipe.create(perspective, { name: "Pasta" }, { batchId: tx.batchId });
916
+ * });
917
+ * ```
918
+ */
919
+ static create<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, data?: Record<string, any>, options?: {
920
+ parent?: ParentScope;
921
+ batchId?: string;
922
+ }): Promise<T>;
923
+ /**
924
+ * Updates an existing model instance identified by `id`.
925
+ *
926
+ * Fetches the instance, applies the provided changes, calls `save()`,
927
+ * and returns the refreshed instance.
928
+ *
929
+ * @param perspective - The perspective containing the instance
930
+ * @param id - The expression URI of the instance to update
931
+ * @param data - Property values to merge before saving
932
+ * @returns The updated model instance
933
+ *
934
+ * @example
935
+ * ```typescript
936
+ * const recipe = await Recipe.update(perspective, recipeId, {
937
+ * rating: 10,
938
+ * });
939
+ * ```
940
+ */
941
+ static update<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, id: string, data: Record<string, any>): Promise<T>;
942
+ /**
943
+ * Deletes an existing model instance identified by `id`.
944
+ *
945
+ * Also cleans up any incoming links that point to this instance.
946
+ *
947
+ * @param perspective - The perspective containing the instance
948
+ * @param id - The expression URI of the instance to delete
949
+ *
950
+ * @example
951
+ * ```typescript
952
+ * await Recipe.delete(perspective, recipeId);
953
+ * ```
954
+ *
955
+ * @deprecated Use the name `delete` — `remove` is preserved as an alias.
956
+ */
957
+ static remove(this: typeof Ad4mModel & (new (...args: any[]) => Ad4mModel), perspective: PerspectiveProxy, id: string): Promise<void>;
958
+ /**
959
+ * Deletes an existing model instance identified by `id`.
960
+ *
961
+ * Also cleans up any incoming links that point to this instance.
962
+ *
963
+ * @param perspective - The perspective containing the instance
964
+ * @param id - The expression URI of the instance to delete
965
+ *
966
+ * @example
967
+ * ```typescript
968
+ * await Recipe.delete(perspective, recipeId);
969
+ * ```
970
+ */
971
+ static delete(this: typeof Ad4mModel & (new (...args: any[]) => Ad4mModel), perspective: PerspectiveProxy, id: string): Promise<void>;
972
+ /**
973
+ * Registers this model's SHACL schema on the given perspective.
974
+ *
975
+ * This ensures the perspective knows about the model's shape
976
+ * (properties, relations, constraints) so instances can be
977
+ * created, queried, and validated.
978
+ *
979
+ * @param perspective - The perspective to register the model on
980
+ *
981
+ * @example
982
+ * ```typescript
983
+ * await Recipe.register(perspective);
984
+ * // Now you can create / query Recipe instances on this perspective
985
+ * ```
986
+ */
987
+ static register(this: typeof Ad4mModel, perspective: PerspectiveProxy): Promise<void>;
988
+ /**
989
+ * Executes a set of model operations inside a single batch (transaction).
990
+ *
991
+ * All `save`, `update`, and `delete` calls made via the provided `batchId`
992
+ * are buffered and flushed atomically when the callback completes.
993
+ * If the callback throws, the batch is **not** committed, preventing
994
+ * partial writes.
995
+ *
996
+ * @param perspective - The perspective to operate on
997
+ * @param fn - Async callback that receives a `TransactionContext` object.
998
+ * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,
999
+ * `delete(tx.batchId)`, etc.
1000
+ * @returns The value returned by `fn`
1001
+ *
1002
+ * @example
1003
+ * ```typescript
1004
+ * await Ad4mModel.transaction(perspective, async (tx) => {
1005
+ * const recipe = new Recipe(perspective);
1006
+ * recipe.name = "Spaghetti";
1007
+ * await recipe.save(tx.batchId);
1008
+ *
1009
+ * const old = await Recipe.query(perspective).where({ name: "Stale" }).run();
1010
+ * for (const r of old) await r.delete(tx.batchId);
1011
+ * });
1012
+ * // All changes committed atomically here
1013
+ * ```
1014
+ */
1015
+ static transaction<R = void>(perspective: PerspectiveProxy, fn: (tx: {
1016
+ batchId: string;
1017
+ }) => Promise<R>): Promise<R>;
683
1018
  /**
684
1019
  * Creates a query builder for fluent query construction.
685
1020
  *
@@ -868,17 +1203,50 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
868
1203
  */
869
1204
  offset(offset: number): ModelQueryBuilder<T>;
870
1205
  /**
871
- * Sets the source filter for the query.
872
- *
873
- * @param source - The source to filter by
1206
+ * Scopes the query to instances linked from a parent.
1207
+ *
1208
+ * The predicate is resolved in order of precedence:
1209
+ * 1. **Instance only** — the parent's constructor is used as the model
1210
+ * class; its relation metadata is scanned for a relation whose
1211
+ * `target()` matches the queried model class.
1212
+ * 2. **Instance + options with `field`** — direct field-name lookup on
1213
+ * the parent model's relation metadata (disambiguates when a parent
1214
+ * has multiple relations targeting the same child class).
1215
+ * 3. **String id + model class** — same metadata scan (or field lookup if
1216
+ * options include `field`).
1217
+ * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
1218
+ *
1219
+ * Passing a plain string id with no second argument throws because the
1220
+ * predicate cannot be resolved without a model class.
1221
+ *
1222
+ * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
1223
+ * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
1224
+ * @param options - Optional settings: `field` for direct relation-name lookup
874
1225
  * @returns The query builder for chaining
875
1226
  *
876
1227
  * @example
877
1228
  * ```typescript
878
- * .source("ad4m://self")
1229
+ * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
1230
+ * Recipe.query(perspective).parent(cookbook).get();
1231
+ *
1232
+ * // Instance + field — disambiguate when parent has multiple relations to same child
1233
+ * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
1234
+ *
1235
+ * // String id + model class
1236
+ * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
1237
+ *
1238
+ * // String id + model class + field
1239
+ * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
1240
+ *
1241
+ * // String id + raw predicate (escape hatch)
1242
+ * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
879
1243
  * ```
880
1244
  */
881
- source(source: string): ModelQueryBuilder<T>;
1245
+ parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
1246
+ field: string;
1247
+ }, options?: {
1248
+ field?: string;
1249
+ }): ModelQueryBuilder<T>;
882
1250
  /**
883
1251
  * Specifies which properties to include in the results.
884
1252
  *
@@ -892,17 +1260,32 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
892
1260
  */
893
1261
  properties(properties: string[]): ModelQueryBuilder<T>;
894
1262
  /**
895
- * Specifies which collections to include in the results.
1263
+ * Specifies which relations to eager-load (hydrate into model instances).
1264
+ *
1265
+ * Without `include`, relation fields contain raw expression URIs (strings).
1266
+ * With `include`, the URIs are resolved into fully-hydrated model instances
1267
+ * using the `target` class declared in the relation decorator.
896
1268
  *
897
- * @param collections - Array of collection names to include
1269
+ * Supports nested includes for multi-level eager loading.
1270
+ *
1271
+ * @param map - An IncludeMap describing which relations to hydrate
898
1272
  * @returns The query builder for chaining
899
1273
  *
900
1274
  * @example
901
1275
  * ```typescript
902
- * .collections(["ingredients", "steps"])
1276
+ * // Hydrate comments one level deep
1277
+ * const recipes = await Recipe.query(perspective)
1278
+ * .include({ comments: true })
1279
+ * .run();
1280
+ * // recipe.comments is now Comment[] (model instances), not string[]
1281
+ *
1282
+ * // Nested: hydrate comments AND each comment's author
1283
+ * const recipes = await Recipe.query(perspective)
1284
+ * .include({ comments: { author: true } })
1285
+ * .run();
903
1286
  * ```
904
1287
  */
905
- collections(collections: string[]): ModelQueryBuilder<T>;
1288
+ include(map: IncludeMap): ModelQueryBuilder<T>;
906
1289
  overrideModelClassName(className: string): ModelQueryBuilder<T>;
907
1290
  /**
908
1291
  * Enables or disables SurrealDB query path.
@@ -943,6 +1326,21 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
943
1326
  * ```
944
1327
  */
945
1328
  get(): Promise<T[]>;
1329
+ /**
1330
+ * Returns the first matching instance, or `null` if none match.
1331
+ *
1332
+ * Internally sets `limit: 1` and delegates to `get()`.
1333
+ *
1334
+ * @returns The first matching instance, or `null`
1335
+ *
1336
+ * @example
1337
+ * ```typescript
1338
+ * const recipe = await Recipe.query(perspective)
1339
+ * .where({ name: "Pasta" })
1340
+ * .first();
1341
+ * ```
1342
+ */
1343
+ first(): Promise<T | null>;
946
1344
  /**
947
1345
  * Subscribes to the query and receives updates when results change.
948
1346
  *
@@ -1071,4 +1469,33 @@ export declare class ModelQueryBuilder<T extends Ad4mModel> {
1071
1469
  */
1072
1470
  paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
1073
1471
  }
1472
+ /**
1473
+ * Generate Prolog predicate facts from a model class's decorator metadata.
1474
+ *
1475
+ * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
1476
+ * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
1477
+ * Prolog clauses that can be prepended to any `perspective.infer()` call.
1478
+ *
1479
+ * The generated predicates are:
1480
+ * - **Instance recognizer** — `modelName(X)` — matches instances of the model
1481
+ * - **Property getters** — `modelName_propName(X, Value)` — one per property
1482
+ * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
1483
+ *
1484
+ * @example
1485
+ * ```typescript
1486
+ * import { generatePrologFacts } from '@coasys/ad4m';
1487
+ *
1488
+ * const facts = generatePrologFacts(Poll);
1489
+ * const result = await perspective.infer(\`
1490
+ * \${facts}
1491
+ * recent_popular_poll(X) :-
1492
+ * poll(X),
1493
+ * poll_vote_count(X, N), N > 10.
1494
+ * \`);
1495
+ * ```
1496
+ *
1497
+ * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
1498
+ * @returns A multi-line Prolog string ready for use with `perspective.infer()`
1499
+ */
1500
+ export declare function generatePrologFacts(ModelClass: typeof Ad4mModel): string;
1074
1501
  export {};