@coasys/ad4m 0.12.0-rc1-dev.2 → 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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6872 -5886
  3. package/lib/index.js +6868 -5874
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3737 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4361 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -0,0 +1,1438 @@
1
+ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
+ import { PropertyOptions } from "./decorators";
3
+ interface JSONSchemaProperty {
4
+ type: string | string[];
5
+ items?: JSONSchemaProperty;
6
+ properties?: {
7
+ [key: string]: JSONSchemaProperty;
8
+ };
9
+ required?: string[];
10
+ "x-ad4m"?: {
11
+ through?: string;
12
+ resolveLanguage?: string;
13
+ local?: boolean;
14
+ writable?: boolean;
15
+ initial?: string;
16
+ };
17
+ }
18
+ interface JSONSchema {
19
+ $schema?: string;
20
+ title?: string;
21
+ $id?: string;
22
+ type?: string;
23
+ properties?: {
24
+ [key: string]: JSONSchemaProperty;
25
+ };
26
+ required?: string[];
27
+ "x-ad4m"?: {
28
+ namespace?: string;
29
+ className?: string;
30
+ };
31
+ }
32
+ interface JSONSchemaToModelOptions {
33
+ name: string;
34
+ namespace?: string;
35
+ predicateTemplate?: string;
36
+ predicateGenerator?: (title: string, property: string) => string;
37
+ propertyMapping?: Record<string, string>;
38
+ resolveLanguage?: string;
39
+ local?: boolean;
40
+ propertyOptions?: Record<string, Partial<PropertyOptions>>;
41
+ }
42
+ type ValueTuple = [name: string, value: any, resolve?: boolean];
43
+ type WhereOps = {
44
+ not: string | number | boolean | string[] | number[];
45
+ between: [number, number];
46
+ lt: number;
47
+ lte: number;
48
+ gt: number;
49
+ gte: number;
50
+ contains: string | number;
51
+ };
52
+ type WhereCondition = string | number | boolean | string[] | number[] | {
53
+ [K in keyof WhereOps]?: WhereOps[K];
54
+ };
55
+ type Where = {
56
+ [propertyName: string]: WhereCondition;
57
+ };
58
+ type Order = {
59
+ [propertyName: string]: "ASC" | "DESC";
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
+ }
100
+ export type Query = {
101
+ /** Filter to instances that are the target of a link from a given parent. */
102
+ parent?: ParentScope;
103
+ properties?: string[];
104
+ include?: IncludeMap;
105
+ where?: Where;
106
+ order?: Order;
107
+ offset?: number;
108
+ limit?: number;
109
+ count?: boolean;
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'>;
129
+ export type AllInstancesResult = {
130
+ AllInstances: Ad4mModel[];
131
+ TotalCount?: number;
132
+ isInit?: boolean;
133
+ };
134
+ export type ResultsWithTotalCount<T> = {
135
+ results: T[];
136
+ totalCount?: number;
137
+ };
138
+ export type PaginationResult<T> = {
139
+ results: T[];
140
+ totalCount?: number;
141
+ pageSize: number;
142
+ pageNumber: number;
143
+ };
144
+ /**
145
+ * Metadata for a single property extracted from decorators.
146
+ */
147
+ export interface PropertyMetadata {
148
+ /** The property name */
149
+ name: string;
150
+ /** The predicate URI (through value) */
151
+ predicate: string;
152
+ /** Whether the property is required */
153
+ required: boolean;
154
+ /** Whether the property is read-only */
155
+ readOnly: boolean;
156
+ /** Initial value if specified */
157
+ initial?: string;
158
+ /** Language for resolution (e.g., "literal") */
159
+ resolveLanguage?: string;
160
+ /** Custom Prolog getter code */
161
+ prologGetter?: string;
162
+ /** Custom Prolog setter code */
163
+ prologSetter?: string;
164
+ /** Custom SurrealQL getter code */
165
+ getter?: string;
166
+ /** Whether stored locally only */
167
+ local?: boolean;
168
+ /** Transform function */
169
+ transform?: (value: any) => any;
170
+ /** Whether this is a flag property */
171
+ flag?: boolean;
172
+ }
173
+ /**
174
+ * Metadata for a single relation (collection) extracted from decorators.
175
+ */
176
+ export interface RelationMetadata {
177
+ /** The relation name */
178
+ name: string;
179
+ /** The predicate URI (through value) */
180
+ predicate: string;
181
+ /** Custom SurrealQL getter code */
182
+ getter?: string;
183
+ /** Whether stored locally only */
184
+ local?: boolean;
185
+ }
186
+ /** @deprecated Use RelationMetadata */
187
+ export type CollectionMetadata = RelationMetadata;
188
+ /**
189
+ * Complete model metadata extracted from decorators.
190
+ */
191
+ export interface ModelMetadata {
192
+ /** The model class name from @Model */
193
+ className: string;
194
+ /** Map of property name to metadata */
195
+ properties: Record<string, PropertyMetadata>;
196
+ /** Map of relation name to metadata */
197
+ relations: Record<string, RelationMetadata>;
198
+ /** @deprecated Use relations */
199
+ collections: Record<string, RelationMetadata>;
200
+ }
201
+ /**
202
+ * Base class for defining data models in AD4M.
203
+ *
204
+ * @description
205
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
206
+ * Each model instance is represented as a subgraph in the perspective, with properties and collections
207
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
208
+ * instances based on their properties and relationships.
209
+ *
210
+ * Key concepts:
211
+ * - Each model instance has a unique base expression that serves as its identifier
212
+ * - Properties are stored as links with predicates defined by the `through` option
213
+ * - Collections represent one-to-many relationships as sets of links
214
+ * - Queries are translated to Prolog for efficient graph pattern matching
215
+ * - Changes are tracked through the perspective's subscription system
216
+ *
217
+ * @example
218
+ * ```typescript
219
+ * // Define a recipe model
220
+ * @Model({ name: "Recipe" })
221
+ * class Recipe extends Ad4mModel {
222
+ * // Required property with literal value
223
+ * @Property({
224
+ * through: "recipe://name",
225
+ * resolveLanguage: "literal"
226
+ * })
227
+ * name: string = "";
228
+ *
229
+ * // Optional property with custom initial value
230
+ * @Optional({
231
+ * through: "recipe://status",
232
+ * initial: "recipe://draft"
233
+ * })
234
+ * status: string = "";
235
+ *
236
+ * // Read-only computed property
237
+ * @ReadOnly({
238
+ * through: "recipe://rating",
239
+ * getter: `
240
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
241
+ * sum_list(Ratings, Sum),
242
+ * length(Ratings, Count),
243
+ * Value is Sum / Count
244
+ * `
245
+ * })
246
+ * averageRating: number = 0;
247
+ *
248
+ * // Collection of ingredients
249
+ * @Collection({ through: "recipe://ingredient" })
250
+ * ingredients: string[] = [];
251
+ *
252
+ * // Collection of comments linked to another model
253
+ * @HasMany(() => Comment, { through: "recipe://comment" })
254
+ * comments: Comment[] = [];
255
+ * }
256
+ *
257
+ * // Create and save a new recipe
258
+ * const recipe = new Recipe(perspective);
259
+ * recipe.name = "Chocolate Cake";
260
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
261
+ * await recipe.save();
262
+ *
263
+ * // Query recipes in different ways
264
+ * // Get all recipes
265
+ * const allRecipes = await Recipe.findAll(perspective);
266
+ *
267
+ * // Find recipes with specific criteria
268
+ * const desserts = await Recipe.findAll(perspective, {
269
+ * where: {
270
+ * status: "recipe://published",
271
+ * averageRating: { gt: 4 }
272
+ * },
273
+ * order: { name: "ASC" },
274
+ * limit: 10
275
+ * });
276
+ *
277
+ * // Use the fluent query builder
278
+ * const popularRecipes = await Recipe.query(perspective)
279
+ * .where({ averageRating: { gt: 4.5 } })
280
+ * .order({ averageRating: "DESC" })
281
+ * .limit(5)
282
+ * .get();
283
+ *
284
+ * // Subscribe to real-time updates
285
+ * await Recipe.query(perspective)
286
+ * .where({ status: "recipe://cooking" })
287
+ * .subscribe(recipes => {
288
+ * console.log("Currently being cooked:", recipes);
289
+ * });
290
+ *
291
+ * // Paginate results
292
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
293
+ * .where({ status: "recipe://published" })
294
+ * .paginate(10, 1);
295
+ * ```
296
+ */
297
+ export declare class Ad4mModel {
298
+ private _id;
299
+ private _subjectClassName;
300
+ private _perspective;
301
+ private _snapshot;
302
+ author: string;
303
+ createdAt: any;
304
+ updatedAt: any;
305
+ private static classNamesByClass;
306
+ static getClassName(perspective: PerspectiveProxy): Promise<string>;
307
+ /**
308
+ * Backwards compatibility alias for createdAt.
309
+ * @deprecated Use createdAt instead. This will be removed in a future version.
310
+ */
311
+ get timestamp(): any;
312
+ /**
313
+ * Extracts metadata from decorators for query building.
314
+ *
315
+ * @description
316
+ * This method reads the metadata stored by decorators (@Property, @Collection, etc.)
317
+ * and returns it in a structured format that's easier to work with for query builders
318
+ * and other systems that need to introspect model structure.
319
+ *
320
+ * The metadata includes:
321
+ * - Class name from @Model
322
+ * - Property metadata (predicates, types, constraints, etc.)
323
+ * - Collection metadata (predicates, filters, etc.)
324
+ *
325
+ * For models created via `fromJSONSchema()`, this method will derive metadata from
326
+ * the WeakMap registries that were populated during the dynamic class creation.
327
+ * If these structures are empty but a JSON schema was attached to the class,
328
+ * it can fall back to deriving metadata from that schema.
329
+ *
330
+ * @returns Structured metadata object containing className, properties, and collections
331
+ * @throws Error if the class doesn't have @Model decorator
332
+ *
333
+ * @example
334
+ * ```typescript
335
+ * @Model({ name: "Recipe" })
336
+ * class Recipe extends Ad4mModel {
337
+ * @Property({ through: "recipe://name", resolveLanguage: "literal" })
338
+ * name: string = "";
339
+ *
340
+ * @Collection({ through: "recipe://ingredient" })
341
+ * ingredients: string[] = [];
342
+ * }
343
+ *
344
+ * const metadata = Recipe.getModelMetadata();
345
+ * console.log(metadata.className); // "Recipe"
346
+ * console.log(metadata.properties.name.predicate); // "recipe://name"
347
+ * console.log(metadata.collections.ingredients.predicate); // "recipe://ingredient"
348
+ * ```
349
+ */
350
+ static getModelMetadata(): ModelMetadata;
351
+ /**
352
+ * Constructs a new model instance.
353
+ *
354
+ * @param perspective - The perspective where this model will be stored
355
+ * @param id - Optional unique identifier (expression URI) for this instance.
356
+ * If omitted, a random Literal URL is generated.
357
+ * @param source - Optional source expression this instance is linked to
358
+ *
359
+ * @example
360
+ * ```typescript
361
+ * // Create a new recipe with auto-generated id
362
+ * const recipe = new Recipe(perspective);
363
+ *
364
+ * // Create with specific id
365
+ * const recipe = new Recipe(perspective, "recipe://chocolate-cake");
366
+ * ```
367
+ */
368
+ constructor(perspective: PerspectiveProxy, id?: string);
369
+ /**
370
+ * The unique identifier (expression URI) of this model instance.
371
+ */
372
+ get id(): string;
373
+ /**
374
+ * @deprecated Use `.id` instead. Will be removed in a future version.
375
+ */
376
+ get baseExpression(): string;
377
+ /**
378
+ * Protected getter for the perspective.
379
+ * Allows subclasses to access the perspective while keeping it private from external code.
380
+ */
381
+ protected get perspective(): PerspectiveProxy;
382
+ /**
383
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
384
+ * @private
385
+ */
386
+ private getPropertyMetadata;
387
+ /**
388
+ * Get relation (collection) options from decorator
389
+ * @private
390
+ */
391
+ private getRelationOptions;
392
+ /**
393
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
394
+ * Replaces Prolog query: property_setter(C, key, Setter)
395
+ * @private
396
+ */
397
+ private generatePropertySetterAction;
398
+ /**
399
+ * Generate collection action from metadata (Phase 1: Prolog-free refactor)
400
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
401
+ * @private
402
+ */
403
+ private generateRelationAction;
404
+ /**
405
+ * Resolves a raw link target value into a hydrated property value.
406
+ *
407
+ * Handles, in order:
408
+ * 1. Non-literal expression resolution (`perspective.getExpression`)
409
+ * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
410
+ * 3. Primitive type coercion (string → number / boolean)
411
+ * 4. Transform function application
412
+ *
413
+ * @param target - The raw target string from the link
414
+ * @param propMeta - Property metadata from the decorator registry
415
+ * @param perspective - The perspective for expression resolution
416
+ * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
417
+ * @returns The resolved value
418
+ * @private
419
+ */
420
+ private static hydratePropertyValue;
421
+ /**
422
+ * Link shape accepted by `hydrateFromLinks`.
423
+ * Both `getData()` and `instancesFromSurrealResult()` produce this shape.
424
+ */
425
+ private static readonly _linkShape;
426
+ /**
427
+ * Hydrates an instance from an array of raw links.
428
+ *
429
+ * Processes properties (latest-wins semantics), collections
430
+ * (chronological accumulation), and timestamps/author in a single
431
+ * pass over the links array.
432
+ *
433
+ * @param instance - The blank model instance to populate
434
+ * @param links - Array of link objects (predicate, target, author?, timestamp?)
435
+ * @param metadata - Model metadata from `getModelMetadata()`
436
+ * @param perspective - The perspective for expression resolution
437
+ * @param requestedProperties - Optional sparse fieldset; when provided, only these
438
+ * property names are hydrated (collections are unaffected).
439
+ * Omit or pass `undefined` to hydrate all properties.
440
+ * @private
441
+ */
442
+ private static hydrateFromLinks;
443
+ static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
444
+ /**
445
+ * Captures a shallow snapshot of the instance's current property and
446
+ * collection values. Called automatically after hydration (`get()`,
447
+ * query results). The snapshot is used by `isDirty()`,
448
+ * `changedFields()`, and by `update()` to skip unchanged fields.
449
+ * @private
450
+ */
451
+ private takeSnapshot;
452
+ /**
453
+ * Returns `true` if any tracked property or collection has changed
454
+ * since the last hydration (or since `takeSnapshot()` was last called).
455
+ *
456
+ * Always returns `true` if no snapshot exists (e.g. a freshly
457
+ * constructed instance that hasn't been fetched yet).
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * const recipe = await Recipe.create(perspective, { name: "Pasta" });
462
+ * recipe.isDirty(); // false — just hydrated
463
+ * recipe.name = "Risotto";
464
+ * recipe.isDirty(); // true
465
+ * ```
466
+ */
467
+ isDirty(): boolean;
468
+ /**
469
+ * Returns the names of properties/collections that differ from the
470
+ * snapshot taken at the last hydration.
471
+ *
472
+ * Returns **all** field names if no snapshot exists.
473
+ *
474
+ * @example
475
+ * ```typescript
476
+ * recipe.name = "New Name";
477
+ * recipe.changedFields(); // ["name"]
478
+ * ```
479
+ */
480
+ changedFields(): string[];
481
+ private getData;
482
+ static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
483
+ /**
484
+ * Evaluates custom SurrealQL getters for properties and collections on a specific instance.
485
+ * @private
486
+ */
487
+ private static evaluateCustomGettersForInstance;
488
+ /**
489
+ * Hydrates relation fields on instances according to the provided IncludeMap.
490
+ *
491
+ * For each relation listed in `includeMap`, the raw expression-URI strings
492
+ * stored on the instance are replaced with fully-hydrated model instances
493
+ * (fetched via the relation's `target()` class). Nested IncludeMaps are
494
+ * supported for multi-level eager loading.
495
+ *
496
+ * @param instances - The instances whose relations should be hydrated
497
+ * @param perspective - The perspective to fetch related instances from
498
+ * @param includeMap - Describes which relations to hydrate
499
+ * @private
500
+ */
501
+ private static hydrateRelations;
502
+ /**
503
+ * Generates a SurrealQL query from a Query object.
504
+ *
505
+ * @description
506
+ * This method translates high-level query parameters into a SurrealQL query string
507
+ * that can be executed against the SurrealDB backend. Unlike Prolog queries which
508
+ * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
509
+ * stored in SurrealDB.
510
+ *
511
+ * The generated query uses a CTE (Common Table Expression) pattern:
512
+ * 1. First, identify candidate base expressions by filtering links based on where conditions
513
+ * 2. Then, for each candidate base, resolve properties and collections via subqueries
514
+ * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
515
+ *
516
+ * Key architectural notes:
517
+ * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
518
+ * - No SDNA knowledge at the database level
519
+ * - Properties are resolved via subqueries that look for links with specific predicates
520
+ * - Collections are similar but return multiple values instead of one
521
+ * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
522
+ *
523
+ * @param perspective - The perspective to query (used for metadata extraction)
524
+ * @param query - Query parameters (where, order, limit, offset, properties, collections)
525
+ * @returns Complete SurrealQL query string ready for execution
526
+ *
527
+ * @example
528
+ * ```typescript
529
+ * const query = Recipe.queryToSurrealQL(perspective, {
530
+ * where: { name: "Pasta", rating: { gt: 4 } },
531
+ * order: { timestamp: "DESC" },
532
+ * limit: 10
533
+ * });
534
+ * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
535
+ * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
536
+ * ```
537
+ */
538
+ static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
539
+ /**
540
+ * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
541
+ *
542
+ * @description
543
+ * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
544
+ * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
545
+ *
546
+ * Handles several condition types:
547
+ * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
548
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
549
+ * - NOT operators: Use `NOT` prefix
550
+ * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
551
+ * - Special fields: base uses `uri` directly, author/timestamp handled post-query
552
+ *
553
+ * @param metadata - Model metadata containing property predicates
554
+ * @param where - Where conditions from the query
555
+ * @returns Graph traversal WHERE clause filters, or empty string if no conditions
556
+ *
557
+ * @private
558
+ */
559
+ private static buildGraphTraversalWhereClause;
560
+ /**
561
+ * Builds the WHERE clause for SurrealQL queries.
562
+ *
563
+ * @description
564
+ * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
565
+ * For each property filter, generates a subquery that checks for links with the appropriate
566
+ * predicate and target value.
567
+ *
568
+ * Handles several condition types:
569
+ * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
570
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
571
+ * - Operators: `{ rating: { gt: 4 } }` → target > '4'
572
+ * - gt, gte, lt, lte: comparison operators
573
+ * - not: negation (single value or array)
574
+ * - between: range check
575
+ * - contains: substring/element check (uses SurrealQL CONTAINS)
576
+ * - Special fields: base, author, timestamp are accessed directly, not via subqueries
577
+ *
578
+ * All conditions are joined with AND.
579
+ *
580
+ * @param metadata - Model metadata containing property predicates
581
+ * @param where - Where conditions from the query
582
+ * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
583
+ *
584
+ * @private
585
+ */
586
+ private static buildSurrealWhereClause;
587
+ /**
588
+ * Builds the SELECT fields for SurrealQL queries.
589
+ *
590
+ * @description
591
+ * Generates the field list for the SELECT clause, resolving properties and collections
592
+ * via subqueries. Each property is fetched with a subquery that finds the link with the
593
+ * appropriate predicate and returns its target. Collections are similar but don't use LIMIT 1.
594
+ *
595
+ * Field types:
596
+ * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
597
+ * - Collections: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS collName`
598
+ * - Author/Timestamp: Always included to provide metadata about each instance
599
+ *
600
+ * If properties or collections arrays are provided, only those fields are included.
601
+ * Otherwise, all properties/collections from metadata are included.
602
+ *
603
+ * @param metadata - Model metadata containing property and collection predicates
604
+ * @param properties - Optional array of property names to include (default: all)
605
+ * @param collections - Optional array of collection names to include (default: all)
606
+ * @returns Comma-separated SELECT field list
607
+ *
608
+ * @private
609
+ */
610
+ private static buildSurrealSelectFields;
611
+ /**
612
+ * Builds the SELECT fields for SurrealQL queries using aggregation functions.
613
+ * Compatible with GROUP BY source queries.
614
+ *
615
+ * @private
616
+ */
617
+ private static buildSurrealSelectFieldsWithAggregation;
618
+ /**
619
+ * Formats a value for use in SurrealQL queries.
620
+ *
621
+ * @description
622
+ * Handles different value types:
623
+ * - Strings: Wrapped in single quotes with backslash-escaped special characters
624
+ * - Numbers/booleans: Converted to string
625
+ * - Arrays: Recursively formatted and wrapped in brackets
626
+ *
627
+ * @param value - The value to format
628
+ * @returns Formatted value string ready for SurrealQL
629
+ *
630
+ * @private
631
+ */
632
+ private static formatSurrealValue;
633
+ static instancesFromPrologResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: AllInstancesResult): Promise<ResultsWithTotalCount<T>>;
634
+ /**
635
+ * Converts SurrealDB query results to Ad4mModel instances.
636
+ *
637
+ * @param perspective - The perspective context
638
+ * @param query - The query parameters used
639
+ * @param result - Array of result objects from SurrealDB
640
+ * @returns Promise resolving to results with total count
641
+ *
642
+ * @internal
643
+ */
644
+ static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[]): Promise<ResultsWithTotalCount<T>>;
645
+ /**
646
+ * Checks if a value matches a condition (for post-query filtering).
647
+ * @private
648
+ */
649
+ private static matchesCondition;
650
+ /**
651
+ * Gets all instances of the model in the perspective that match the query params.
652
+ *
653
+ * @param perspective - The perspective to search in
654
+ * @param query - Optional query parameters to filter results
655
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
656
+ * @returns Array of matching models
657
+ *
658
+ * @example
659
+ * ```typescript
660
+ * // Get all recipes (uses SurrealDB by default)
661
+ * const allRecipes = await Recipe.findAll(perspective);
662
+ *
663
+ * // Get recipes with specific criteria (uses SurrealDB)
664
+ * const recipes = await Recipe.findAll(perspective, {
665
+ * where: {
666
+ * name: "Pasta",
667
+ * rating: { gt: 4 }
668
+ * },
669
+ * order: { createdAt: "DESC" },
670
+ * limit: 10
671
+ * });
672
+ *
673
+ * // Explicitly use Prolog (legacy, for backward compatibility)
674
+ * const recipesProlog = await Recipe.findAll(perspective, {}, false);
675
+ * ```
676
+ */
677
+ static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T[]>;
678
+ /**
679
+ * Finds the first instance matching the query, or `null` if none exists.
680
+ *
681
+ * Equivalent to `findAll` with `limit: 1` — only one instance is hydrated.
682
+ *
683
+ * @param perspective - The perspective to search in
684
+ * @param query - Optional query parameters to filter results
685
+ * @param useSurrealDB - Whether to use SurrealDB (default: true) or Prolog (legacy)
686
+ * @returns The first matching instance, or `null`
687
+ *
688
+ * @example
689
+ * ```typescript
690
+ * const recipe = await Recipe.findOne(perspective, {
691
+ * where: { name: "Pasta" }
692
+ * });
693
+ * if (recipe) {
694
+ * console.log(recipe.name);
695
+ * }
696
+ * ```
697
+ */
698
+ static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T | null>;
699
+ /**
700
+ * Gets all instances with count of total matches without offset & limit applied.
701
+ *
702
+ * @param perspective - The perspective to search in
703
+ * @param query - Optional query parameters to filter results
704
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
705
+ * @returns Object containing results array and total count
706
+ *
707
+ * @example
708
+ * ```typescript
709
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
710
+ * where: { category: "Dessert" },
711
+ * limit: 10
712
+ * });
713
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
714
+ *
715
+ * // Use Prolog explicitly (legacy)
716
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
717
+ * ```
718
+ */
719
+ static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<ResultsWithTotalCount<T>>;
720
+ /**
721
+ * Helper function for pagination with explicit page size and number.
722
+ *
723
+ * @param perspective - The perspective to search in
724
+ * @param pageSize - Number of items per page
725
+ * @param pageNumber - Which page to retrieve (1-based)
726
+ * @param query - Optional additional query parameters
727
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
728
+ * @returns Paginated results with metadata
729
+ *
730
+ * @example
731
+ * ```typescript
732
+ * const page = await Recipe.paginate(perspective, 10, 1, {
733
+ * where: { category: "Main Course" }
734
+ * });
735
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
736
+ *
737
+ * // Use Prolog explicitly (legacy)
738
+ * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
739
+ * ```
740
+ */
741
+ static paginate<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Query, useSurrealDB?: boolean): Promise<PaginationResult<T>>;
742
+ static countQueryToProlog(perspective: PerspectiveProxy, query?: Query, modelClassName?: string | null): Promise<string>;
743
+ /**
744
+ * Generates a SurrealQL COUNT query for the model.
745
+ *
746
+ * @param perspective - The perspective context
747
+ * @param query - Query parameters to filter the count
748
+ * @returns SurrealQL COUNT query string
749
+ *
750
+ * @private
751
+ */
752
+ static countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
753
+ /**
754
+ * Gets a count of all matching instances.
755
+ *
756
+ * @param perspective - The perspective to search in
757
+ * @param query - Optional query parameters to filter results
758
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
759
+ * @returns Total count of matching entities
760
+ *
761
+ * @example
762
+ * ```typescript
763
+ * const totalRecipes = await Recipe.count(perspective);
764
+ * const activeRecipes = await Recipe.count(perspective, {
765
+ * where: { status: "active" }
766
+ * });
767
+ *
768
+ * // Use Prolog explicitly (legacy)
769
+ * const countProlog = await Recipe.count(perspective, {}, false);
770
+ * ```
771
+ */
772
+ static count(perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): any;
773
+ private setProperty;
774
+ /** Resolve a relation argument to a plain string ID. Accepts either a raw
775
+ * string ID or an Ad4mModel instance (in which case `.id` is used). */
776
+ private resolveRelationId;
777
+ private setRelationValues;
778
+ private addRelationValue;
779
+ private removeRelationValue;
780
+ /**
781
+ * Saves the model instance to the perspective.
782
+ *
783
+ * **New instances** (no snapshot yet): creates the subject via
784
+ * `createSubject` with initial scalar values, then sets collections
785
+ * via `innerUpdate`.
786
+ *
787
+ * **Existing instances** (snapshot present, i.e. fetched via `get()`
788
+ * or a query): updates only dirty fields via `innerUpdate`, then
789
+ * refreshes from the perspective.
790
+ *
791
+ * @param batchId - Optional batch ID for batch operations
792
+ * @throws Will throw if instance creation, linking, or updating fails
793
+ *
794
+ * @example
795
+ * ```typescript
796
+ * // Create
797
+ * const recipe = new Recipe(perspective);
798
+ * recipe.name = "Spaghetti";
799
+ * await recipe.save();
800
+ *
801
+ * // Update
802
+ * recipe.rating = 10;
803
+ * await recipe.save();
804
+ * ```
805
+ */
806
+ save(batchId?: string): Promise<void>;
807
+ private cleanCopy;
808
+ private innerUpdate;
809
+ /**
810
+ * Gets the model instance with all properties and collections populated.
811
+ *
812
+ * @param optsOrInclude - Optional hydration options. Accepts two forms:
813
+ * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`
814
+ * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)
815
+ * @returns The populated model instance
816
+ * @throws Will throw if data retrieval fails
817
+ *
818
+ * @example
819
+ * ```typescript
820
+ * const recipe = new Recipe(perspective, existingId);
821
+ * await recipe.get();
822
+ * console.log(recipe.name, recipe.ingredients);
823
+ *
824
+ * // Shorthand — pass IncludeMap directly:
825
+ * await recipe.get({ ingredients: true });
826
+ *
827
+ * // Full options — includes sparse fieldset:
828
+ * await recipe.get({ include: { ingredients: true }, properties: ['name'] });
829
+ * ```
830
+ */
831
+ get(optsOrInclude?: GetOptions | IncludeMap): Promise<this>;
832
+ /**
833
+ * Deletes the model instance from the perspective.
834
+ *
835
+ * @param batchId - Optional batch ID for batch operations
836
+ * @throws Will throw if removal fails
837
+ *
838
+ * @example
839
+ * ```typescript
840
+ * const recipe = await Recipe.findAll(perspective)[0];
841
+ * await recipe.delete();
842
+ *
843
+ * // Or with batch operations:
844
+ * const batchId = await perspective.createBatch();
845
+ * await recipe.delete(batchId);
846
+ * await perspective.commitBatch(batchId);
847
+ * ```
848
+ */
849
+ delete(batchId?: string): Promise<void>;
850
+ /**
851
+ * Options for `Ad4mModel.create()`.
852
+ */
853
+ static readonly CreateOptions: undefined;
854
+ /**
855
+ * Creates and saves a new model instance in one step.
856
+ *
857
+ * @param perspective - The perspective to create the instance in
858
+ * @param data - Property values to assign before saving
859
+ * @param options - Optional settings:
860
+ * - `parent` — a `ParentScope` (model form or raw form) whose `id` will
861
+ * be used to create an incoming link from the parent to the new instance.
862
+ * - `batchId` — an existing batch id; when provided the link write and
863
+ * `save()` are added to the batch instead of committed immediately.
864
+ * @returns The saved model instance
865
+ *
866
+ * @example
867
+ * ```typescript
868
+ * // Simple create
869
+ * const recipe = await Recipe.create(perspective, {
870
+ * name: "Spaghetti",
871
+ * rating: 5,
872
+ * });
873
+ *
874
+ * // Create under a parent (link auto-created)
875
+ * const comment = await Comment.create(perspective, { text: "Great!" }, {
876
+ * parent: { model: Post, id: postId },
877
+ * });
878
+ *
879
+ * // Create inside a transaction
880
+ * await Ad4mModel.transaction(perspective, async (tx) => {
881
+ * await Recipe.create(perspective, { name: "Pasta" }, { batchId: tx.batchId });
882
+ * });
883
+ * ```
884
+ */
885
+ static create<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, data?: Record<string, any>, options?: {
886
+ parent?: ParentScope;
887
+ batchId?: string;
888
+ }): Promise<T>;
889
+ /**
890
+ * Updates an existing model instance identified by `id`.
891
+ *
892
+ * Fetches the instance, applies the provided changes, calls `save()`,
893
+ * and returns the refreshed instance.
894
+ *
895
+ * @param perspective - The perspective containing the instance
896
+ * @param id - The expression URI of the instance to update
897
+ * @param data - Property values to merge before saving
898
+ * @returns The updated model instance
899
+ *
900
+ * @example
901
+ * ```typescript
902
+ * const recipe = await Recipe.update(perspective, recipeId, {
903
+ * rating: 10,
904
+ * });
905
+ * ```
906
+ */
907
+ static update<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, id: string, data: Record<string, any>): Promise<T>;
908
+ /**
909
+ * Deletes an existing model instance identified by `id`.
910
+ *
911
+ * Also cleans up any incoming links that point to this instance.
912
+ *
913
+ * @param perspective - The perspective containing the instance
914
+ * @param id - The expression URI of the instance to delete
915
+ *
916
+ * @example
917
+ * ```typescript
918
+ * await Recipe.delete(perspective, recipeId);
919
+ * ```
920
+ *
921
+ * @deprecated Use the name `delete` — `remove` is preserved as an alias.
922
+ */
923
+ static remove(this: typeof Ad4mModel & (new (...args: any[]) => Ad4mModel), perspective: PerspectiveProxy, id: string): Promise<void>;
924
+ /**
925
+ * Deletes an existing model instance identified by `id`.
926
+ *
927
+ * Also cleans up any incoming links that point to this instance.
928
+ *
929
+ * @param perspective - The perspective containing the instance
930
+ * @param id - The expression URI of the instance to delete
931
+ *
932
+ * @example
933
+ * ```typescript
934
+ * await Recipe.delete(perspective, recipeId);
935
+ * ```
936
+ */
937
+ static delete(this: typeof Ad4mModel & (new (...args: any[]) => Ad4mModel), perspective: PerspectiveProxy, id: string): Promise<void>;
938
+ /**
939
+ * Registers this model's SHACL schema on the given perspective.
940
+ *
941
+ * This ensures the perspective knows about the model's shape
942
+ * (properties, relations, constraints) so instances can be
943
+ * created, queried, and validated.
944
+ *
945
+ * @param perspective - The perspective to register the model on
946
+ *
947
+ * @example
948
+ * ```typescript
949
+ * await Recipe.register(perspective);
950
+ * // Now you can create / query Recipe instances on this perspective
951
+ * ```
952
+ */
953
+ static register(this: typeof Ad4mModel, perspective: PerspectiveProxy): Promise<void>;
954
+ /**
955
+ * Executes a set of model operations inside a single batch (transaction).
956
+ *
957
+ * All `save`, `update`, and `delete` calls made via the provided `batchId`
958
+ * are buffered and flushed atomically when the callback completes.
959
+ * If the callback throws, the batch is **not** committed, preventing
960
+ * partial writes.
961
+ *
962
+ * @param perspective - The perspective to operate on
963
+ * @param fn - Async callback that receives a `TransactionContext` object.
964
+ * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,
965
+ * `delete(tx.batchId)`, etc.
966
+ * @returns The value returned by `fn`
967
+ *
968
+ * @example
969
+ * ```typescript
970
+ * await Ad4mModel.transaction(perspective, async (tx) => {
971
+ * const recipe = new Recipe(perspective);
972
+ * recipe.name = "Spaghetti";
973
+ * await recipe.save(tx.batchId);
974
+ *
975
+ * const old = await Recipe.query(perspective).where({ name: "Stale" }).run();
976
+ * for (const r of old) await r.delete(tx.batchId);
977
+ * });
978
+ * // All changes committed atomically here
979
+ * ```
980
+ */
981
+ static transaction<R = void>(perspective: PerspectiveProxy, fn: (tx: {
982
+ batchId: string;
983
+ }) => Promise<R>): Promise<R>;
984
+ /**
985
+ * Creates a query builder for fluent query construction.
986
+ *
987
+ * @param perspective - The perspective to query
988
+ * @param query - Optional initial query parameters
989
+ * @returns A new query builder instance
990
+ *
991
+ * @example
992
+ * ```typescript
993
+ * const recipes = await Recipe.query(perspective)
994
+ * .where({ category: "Dessert" })
995
+ * .order({ rating: "DESC" })
996
+ * .limit(5)
997
+ * .run();
998
+ *
999
+ * // With real-time updates
1000
+ * await Recipe.query(perspective)
1001
+ * .where({ status: "cooking" })
1002
+ * .subscribe(recipes => {
1003
+ * console.log("Currently cooking:", recipes);
1004
+ * });
1005
+ * ```
1006
+ */
1007
+ static query<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): ModelQueryBuilder<T>;
1008
+ /**
1009
+ * Creates an Ad4mModel class from a JSON Schema definition.
1010
+ *
1011
+ * @description
1012
+ * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
1013
+ * enabling integration with systems that use JSON Schema for type definitions.
1014
+ *
1015
+ * The method follows a cascading approach for determining predicates:
1016
+ * 1. Explicit configuration in options parameter (highest precedence)
1017
+ * 2. x-ad4m metadata in the JSON Schema
1018
+ * 3. Inference from schema title and property names
1019
+ * 4. Error if no namespace can be determined
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * // With explicit configuration
1024
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
1025
+ * name: "Person",
1026
+ * namespace: "person://",
1027
+ * resolveLanguage: "literal"
1028
+ * });
1029
+ *
1030
+ * // With property mapping
1031
+ * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
1032
+ * name: "Contact",
1033
+ * namespace: "contact://",
1034
+ * propertyMapping: {
1035
+ * "name": "foaf://name",
1036
+ * "email": "foaf://mbox"
1037
+ * }
1038
+ * });
1039
+ *
1040
+ * // With x-ad4m metadata in schema
1041
+ * const schema = {
1042
+ * "title": "Product",
1043
+ * "x-ad4m": { "namespace": "product://" },
1044
+ * "properties": {
1045
+ * "name": {
1046
+ * "type": "string",
1047
+ * "x-ad4m": { "through": "product://title" }
1048
+ * }
1049
+ * }
1050
+ * };
1051
+ * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
1052
+ * ```
1053
+ *
1054
+ * @param schema - JSON Schema definition
1055
+ * @param options - Configuration options
1056
+ * @returns Generated Ad4mModel subclass
1057
+ * @throws Error when namespace cannot be inferred
1058
+ */
1059
+ static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1060
+ /**
1061
+ * Determines the namespace for predicates using cascading precedence
1062
+ */
1063
+ private static determineNamespace;
1064
+ /**
1065
+ * Determines the predicate for a specific property using cascading precedence
1066
+ */
1067
+ private static determinePredicate;
1068
+ /**
1069
+ * Gets property-specific options using cascading precedence
1070
+ */
1071
+ private static getPropertyOption;
1072
+ /**
1073
+ * Gets default value for a JSON Schema type
1074
+ */
1075
+ private static getDefaultValueForType;
1076
+ }
1077
+ /** Query builder for Ad4mModel queries.
1078
+ * Allows building queries with a fluent interface and either running them once
1079
+ * or subscribing to updates.
1080
+ *
1081
+ * @example
1082
+ * ```typescript
1083
+ * const builder = Recipe.query(perspective)
1084
+ * .where({ category: "Dessert" })
1085
+ * .order({ rating: "DESC" })
1086
+ * .limit(10);
1087
+ *
1088
+ * // Run once
1089
+ * const recipes = await builder.run();
1090
+ *
1091
+ * // Or subscribe to updates
1092
+ * await builder.subscribe(recipes => {
1093
+ * console.log("Updated recipes:", recipes);
1094
+ * });
1095
+ * ```
1096
+ */
1097
+ export declare class ModelQueryBuilder<T extends Ad4mModel> {
1098
+ private perspective;
1099
+ private queryParams;
1100
+ private modelClassName;
1101
+ private ctor;
1102
+ private currentSubscription?;
1103
+ private useSurrealDBFlag;
1104
+ constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query);
1105
+ /**
1106
+ * Disposes of the current subscription if one exists.
1107
+ *
1108
+ * This method:
1109
+ * 1. Stops the keepalive signals to the subscription
1110
+ * 2. Unsubscribes from GraphQL subscription updates
1111
+ * 3. Notifies the backend to clean up subscription resources
1112
+ * 4. Clears the subscription reference
1113
+ *
1114
+ * You should call this method when you're done with a subscription
1115
+ * to prevent memory leaks and ensure proper cleanup.
1116
+ */
1117
+ dispose(): void;
1118
+ /**
1119
+ * Adds where conditions to the query.
1120
+ *
1121
+ * @param conditions - The conditions to filter by
1122
+ * @returns The query builder for chaining
1123
+ *
1124
+ * @example
1125
+ * ```typescript
1126
+ * .where({
1127
+ * category: "Dessert",
1128
+ * rating: { gt: 4 },
1129
+ * tags: ["vegan", "quick"],
1130
+ * published: true
1131
+ * })
1132
+ * ```
1133
+ */
1134
+ where(conditions: Where): ModelQueryBuilder<T>;
1135
+ /**
1136
+ * Sets the order for the query results.
1137
+ *
1138
+ * @param orderBy - The ordering criteria
1139
+ * @returns The query builder for chaining
1140
+ *
1141
+ * @example
1142
+ * ```typescript
1143
+ * .order({ createdAt: "DESC" })
1144
+ * ```
1145
+ */
1146
+ order(orderBy: Order): ModelQueryBuilder<T>;
1147
+ /**
1148
+ * Sets the maximum number of results to return.
1149
+ *
1150
+ * @param limit - Maximum number of results
1151
+ * @returns The query builder for chaining
1152
+ *
1153
+ * @example
1154
+ * ```typescript
1155
+ * .limit(10)
1156
+ * ```
1157
+ */
1158
+ limit(limit: number): ModelQueryBuilder<T>;
1159
+ /**
1160
+ * Sets the number of results to skip.
1161
+ *
1162
+ * @param offset - Number of results to skip
1163
+ * @returns The query builder for chaining
1164
+ *
1165
+ * @example
1166
+ * ```typescript
1167
+ * .offset(20) // Skip first 20 results
1168
+ * ```
1169
+ */
1170
+ offset(offset: number): ModelQueryBuilder<T>;
1171
+ /**
1172
+ * Scopes the query to instances linked from a parent.
1173
+ *
1174
+ * The predicate is resolved in order of precedence:
1175
+ * 1. **Instance only** — the parent's constructor is used as the model
1176
+ * class; its relation metadata is scanned for a relation whose
1177
+ * `target()` matches the queried model class.
1178
+ * 2. **Instance + options with `field`** — direct field-name lookup on
1179
+ * the parent model's relation metadata (disambiguates when a parent
1180
+ * has multiple relations targeting the same child class).
1181
+ * 3. **String id + model class** — same metadata scan (or field lookup if
1182
+ * options include `field`).
1183
+ * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
1184
+ *
1185
+ * Passing a plain string id with no second argument throws because the
1186
+ * predicate cannot be resolved without a model class.
1187
+ *
1188
+ * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
1189
+ * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
1190
+ * @param options - Optional settings: `field` for direct relation-name lookup
1191
+ * @returns The query builder for chaining
1192
+ *
1193
+ * @example
1194
+ * ```typescript
1195
+ * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
1196
+ * Recipe.query(perspective).parent(cookbook).get();
1197
+ *
1198
+ * // Instance + field — disambiguate when parent has multiple relations to same child
1199
+ * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
1200
+ *
1201
+ * // String id + model class
1202
+ * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
1203
+ *
1204
+ * // String id + model class + field
1205
+ * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
1206
+ *
1207
+ * // String id + raw predicate (escape hatch)
1208
+ * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
1209
+ * ```
1210
+ */
1211
+ parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
1212
+ field: string;
1213
+ }, options?: {
1214
+ field?: string;
1215
+ }): ModelQueryBuilder<T>;
1216
+ /**
1217
+ * Specifies which properties to include in the results.
1218
+ *
1219
+ * @param properties - Array of property names to include
1220
+ * @returns The query builder for chaining
1221
+ *
1222
+ * @example
1223
+ * ```typescript
1224
+ * .properties(["name", "description", "rating"])
1225
+ * ```
1226
+ */
1227
+ properties(properties: string[]): ModelQueryBuilder<T>;
1228
+ /**
1229
+ * Specifies which relations to eager-load (hydrate into model instances).
1230
+ *
1231
+ * Without `include`, relation fields contain raw expression URIs (strings).
1232
+ * With `include`, the URIs are resolved into fully-hydrated model instances
1233
+ * using the `target` class declared in the relation decorator.
1234
+ *
1235
+ * Supports nested includes for multi-level eager loading.
1236
+ *
1237
+ * @param map - An IncludeMap describing which relations to hydrate
1238
+ * @returns The query builder for chaining
1239
+ *
1240
+ * @example
1241
+ * ```typescript
1242
+ * // Hydrate comments one level deep
1243
+ * const recipes = await Recipe.query(perspective)
1244
+ * .include({ comments: true })
1245
+ * .run();
1246
+ * // recipe.comments is now Comment[] (model instances), not string[]
1247
+ *
1248
+ * // Nested: hydrate comments AND each comment's author
1249
+ * const recipes = await Recipe.query(perspective)
1250
+ * .include({ comments: { author: true } })
1251
+ * .run();
1252
+ * ```
1253
+ */
1254
+ include(map: IncludeMap): ModelQueryBuilder<T>;
1255
+ overrideModelClassName(className: string): ModelQueryBuilder<T>;
1256
+ /**
1257
+ * Enables or disables SurrealDB query path.
1258
+ *
1259
+ * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1260
+ * @returns The query builder for chaining
1261
+ *
1262
+ * @example
1263
+ * ```typescript
1264
+ * // Use SurrealDB (default)
1265
+ * const recipes = await Recipe.query(perspective)
1266
+ * .where({ category: "Dessert" })
1267
+ * .useSurrealDB(true)
1268
+ * .get();
1269
+ *
1270
+ * // Use Prolog (legacy)
1271
+ * const recipesProlog = await Recipe.query(perspective)
1272
+ * .where({ category: "Dessert" })
1273
+ * .useSurrealDB(false)
1274
+ * .get();
1275
+ * ```
1276
+ *
1277
+ * @remarks
1278
+ * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
1279
+ * if useSurrealDB(true) is set (default).
1280
+ */
1281
+ useSurrealDB(enabled?: boolean): ModelQueryBuilder<T>;
1282
+ /**
1283
+ * Executes the query once and returns the results.
1284
+ *
1285
+ * @returns Array of matching entities
1286
+ *
1287
+ * @example
1288
+ * ```typescript
1289
+ * const recipes = await Recipe.query(perspective)
1290
+ * .where({ category: "Dessert" })
1291
+ * .get();
1292
+ * ```
1293
+ */
1294
+ get(): Promise<T[]>;
1295
+ /**
1296
+ * Returns the first matching instance, or `null` if none match.
1297
+ *
1298
+ * Internally sets `limit: 1` and delegates to `get()`.
1299
+ *
1300
+ * @returns The first matching instance, or `null`
1301
+ *
1302
+ * @example
1303
+ * ```typescript
1304
+ * const recipe = await Recipe.query(perspective)
1305
+ * .where({ name: "Pasta" })
1306
+ * .first();
1307
+ * ```
1308
+ */
1309
+ first(): Promise<T | null>;
1310
+ /**
1311
+ * Subscribes to the query and receives updates when results change.
1312
+ *
1313
+ * This method:
1314
+ * 1. Creates and initializes a SurrealDB live query subscription (default)
1315
+ * 2. Sets up the callback to process future updates
1316
+ * 3. Returns the initial results immediately
1317
+ *
1318
+ * Remember to call dispose() when you're done with the subscription
1319
+ * to clean up resources.
1320
+ *
1321
+ * @param callback - Function to call with updated results
1322
+ * @returns Initial results array
1323
+ *
1324
+ * @example
1325
+ * ```typescript
1326
+ * const builder = Recipe.query(perspective)
1327
+ * .where({ status: "cooking" });
1328
+ *
1329
+ * const initialRecipes = await builder.subscribe(recipes => {
1330
+ * console.log("Updated recipes:", recipes);
1331
+ * });
1332
+ *
1333
+ * // When done with subscription:
1334
+ * builder.dispose();
1335
+ * ```
1336
+ *
1337
+ * @remarks
1338
+ * By default, this uses SurrealDB live queries for real-time updates.
1339
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1340
+ */
1341
+ subscribe(callback: (results: T[]) => void): Promise<T[]>;
1342
+ /**
1343
+ * Gets the total count of matching entities.
1344
+ *
1345
+ * @returns Total count
1346
+ *
1347
+ * @example
1348
+ * ```typescript
1349
+ * const totalDesserts = await Recipe.query(perspective)
1350
+ * .where({ category: "Dessert" })
1351
+ * .count();
1352
+ * ```
1353
+ */
1354
+ count(): Promise<number>;
1355
+ /**
1356
+ * Subscribes to count updates for matching entities.
1357
+ *
1358
+ * This method:
1359
+ * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
1360
+ * 2. Sets up the callback to process future count updates
1361
+ * 3. Returns the initial count immediately
1362
+ *
1363
+ * Remember to call dispose() when you're done with the subscription
1364
+ * to clean up resources.
1365
+ *
1366
+ * @param callback - Function to call with updated count
1367
+ * @returns Initial count
1368
+ *
1369
+ * @example
1370
+ * ```typescript
1371
+ * const builder = Recipe.query(perspective)
1372
+ * .where({ status: "active" });
1373
+ *
1374
+ * const initialCount = await builder.countSubscribe(count => {
1375
+ * console.log("Active items:", count);
1376
+ * });
1377
+ *
1378
+ * // When done with subscription:
1379
+ * builder.dispose();
1380
+ * ```
1381
+ *
1382
+ * @remarks
1383
+ * By default, this uses SurrealDB live queries for real-time updates.
1384
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1385
+ */
1386
+ countSubscribe(callback: (count: number) => void): Promise<number>;
1387
+ /**
1388
+ * Gets a page of results with pagination metadata.
1389
+ *
1390
+ * @param pageSize - Number of items per page
1391
+ * @param pageNumber - Which page to retrieve (1-based)
1392
+ * @returns Paginated results with metadata
1393
+ *
1394
+ * @example
1395
+ * ```typescript
1396
+ * const page = await Recipe.query(perspective)
1397
+ * .where({ category: "Main" })
1398
+ * .paginate(10, 1);
1399
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1400
+ * ```
1401
+ */
1402
+ paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
1403
+ /**
1404
+ * Subscribes to paginated results updates.
1405
+ *
1406
+ * This method:
1407
+ * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
1408
+ * 2. Sets up the callback to process future page updates
1409
+ * 3. Returns the initial page immediately
1410
+ *
1411
+ * Remember to call dispose() when you're done with the subscription
1412
+ * to clean up resources.
1413
+ *
1414
+ * @param pageSize - Number of items per page
1415
+ * @param pageNumber - Which page to retrieve (1-based)
1416
+ * @param callback - Function to call with updated pagination results
1417
+ * @returns Initial pagination results
1418
+ *
1419
+ * @example
1420
+ * ```typescript
1421
+ * const builder = Recipe.query(perspective)
1422
+ * .where({ category: "Main" });
1423
+ *
1424
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1425
+ * console.log("Updated page:", page.results);
1426
+ * });
1427
+ *
1428
+ * // When done with subscription:
1429
+ * builder.dispose();
1430
+ * ```
1431
+ *
1432
+ * @remarks
1433
+ * By default, this uses SurrealDB live queries for real-time updates.
1434
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1435
+ */
1436
+ paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
1437
+ }
1438
+ export {};