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

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 +6893 -5884
  3. package/lib/index.js +6889 -5872
  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 +3760 -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 +4386 -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
@@ -1,217 +1,851 @@
1
1
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- import { SHACLShape } from "../shacl/SHACLShape";
3
- export { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
4
- export type { MutationContext } from "./mutation";
5
- export type { Query, Where, Order, WhereCondition, AllInstancesResult, ResultsWithTotalCount, PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata, IncludeMap, SubscribeOptions, Subscription, ParentQuery, ParentQueryByPredicate, ParentQueryByModel, } from "./types";
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
+ };
6
61
  /**
7
- * Options for linking a newly created instance to an existing parent node.
8
- * Pass as the third argument to `Model.create()`.
62
+ * Discriminated union for parent-scoped queries.
9
63
  *
10
- * @example
11
- * // Field inferred — only one @HasMany on Channel points to Poll
12
- * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId } })
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.
13
67
  *
14
- * // Field explicit — needed when multiple @HasMany on the parent point to the same type
15
- * await Poll.create(perspective, { title }, { parent: { model: Channel, id: channelId, field: 'featuredPolls' } })
68
+ * **Raw form** — explicit predicate string, no metadata lookup.
16
69
  */
17
- export type ParentOptions = {
18
- /** The parent model class (must have a `@HasMany` pointing to this child type). */
70
+ export type ParentScope = {
19
71
  model: typeof Ad4mModel;
20
- /** The ID of the parent instance. */
21
72
  id: string;
22
- /**
23
- * The `@HasMany` field on the parent whose predicate is used for the link.
24
- * Optional when exactly one `@HasMany` on the parent points to this child type.
25
- */
26
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;
27
143
  };
28
- import type { Query, ResultsWithTotalCount, PaginationResult, ModelMetadata, IncludeMap, SubscribeOptions, Subscription } from "./types";
29
- import type { JSONSchema, JSONSchemaToModelOptions } from "./schema/fromJSONSchema";
30
- export type { JSONSchema, JSONSchemaToModelOptions, JSONSchemaProperty, } from "./schema/fromJSONSchema";
31
- import { ModelQueryBuilder } from "./query/ModelQueryBuilder";
32
- export { ModelQueryBuilder };
33
- export { buildSurrealQuery, buildSurrealCountQuery, formatSurrealValue, matchesCondition, buildGraphTraversalWhereClause, } from "./query/surrealCompiler";
34
- export { hydrateInstanceFromLinks, evaluateCustomGetters, normalizeTimestamp, } from "./query/hydration";
35
- export type { RawLink } from "./query/hydration";
36
- export type { TransactionContext } from "./transaction";
37
144
  /**
38
- * Base class for all AD4M data models.
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 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
+ /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
186
+ direction?: 'forward' | 'reverse';
187
+ }
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
+ }
199
+ /**
200
+ * Base class for defining data models in AD4M.
201
+ *
202
+ * @description
203
+ * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.
204
+ * Each model instance is represented as a subgraph in the perspective, with properties and relations
205
+ * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter
206
+ * instances based on their properties and relationships.
207
+ *
208
+ * Key concepts:
209
+ * - Each model instance has a unique base expression that serves as its identifier
210
+ * - Properties are stored as links with predicates defined by the `through` option
211
+ * - Relations represent one-to-many relationships as sets of links
212
+ * - Queries are translated to Prolog for efficient graph pattern matching
213
+ * - Changes are tracked through the perspective's subscription system
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * // Define a recipe model
218
+ * @Model({ name: "Recipe" })
219
+ * class Recipe extends Ad4mModel {
220
+ * // Required property with literal value
221
+ * @Property({
222
+ * through: "recipe://name",
223
+ * resolveLanguage: "literal"
224
+ * })
225
+ * name: string = "";
226
+ *
227
+ * // Optional property with custom initial value
228
+ * @Optional({
229
+ * through: "recipe://status",
230
+ * initial: "recipe://draft"
231
+ * })
232
+ * status: string = "";
233
+ *
234
+ * // Read-only computed property
235
+ * @ReadOnly({
236
+ * through: "recipe://rating",
237
+ * getter: `
238
+ * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
239
+ * sum_list(Ratings, Sum),
240
+ * length(Ratings, Count),
241
+ * Value is Sum / Count
242
+ * `
243
+ * })
244
+ * averageRating: number = 0;
245
+ *
246
+ * // Relation of ingredients
247
+ * @HasMany({ through: "recipe://ingredient" })
248
+ * ingredients: string[] = [];
249
+ *
250
+ * // Relation of comments linked to another model
251
+ * @HasMany(() => Comment, { through: "recipe://comment" })
252
+ * comments: Comment[] = [];
253
+ * }
254
+ *
255
+ * // Create and save a new recipe
256
+ * const recipe = new Recipe(perspective);
257
+ * recipe.name = "Chocolate Cake";
258
+ * recipe.ingredients = ["flour", "sugar", "cocoa"];
259
+ * await recipe.save();
260
+ *
261
+ * // Query recipes in different ways
262
+ * // Get all recipes
263
+ * const allRecipes = await Recipe.findAll(perspective);
264
+ *
265
+ * // Find recipes with specific criteria
266
+ * const desserts = await Recipe.findAll(perspective, {
267
+ * where: {
268
+ * status: "recipe://published",
269
+ * averageRating: { gt: 4 }
270
+ * },
271
+ * order: { name: "ASC" },
272
+ * limit: 10
273
+ * });
274
+ *
275
+ * // Use the fluent query builder
276
+ * const popularRecipes = await Recipe.query(perspective)
277
+ * .where({ averageRating: { gt: 4.5 } })
278
+ * .order({ averageRating: "DESC" })
279
+ * .limit(5)
280
+ * .get();
39
281
  *
40
- * Instances are subgraphs in a {@link PerspectiveProxy}; properties and relations
41
- * map to typed links. Decorators (`@Property`, `@HasMany`, etc.) declare the schema;
42
- * query helpers (`findAll`, `query`, `subscribe`) run SurrealQL against the
43
- * perspective's local graph engine.
282
+ * // Subscribe to real-time updates
283
+ * await Recipe.query(perspective)
284
+ * .where({ status: "recipe://cooking" })
285
+ * .subscribe(recipes => {
286
+ * console.log("Currently being cooked:", recipes);
287
+ * });
44
288
  *
45
- * See [README.md](./README.md) for a full worked example and decorator reference.
289
+ * // Paginate results
290
+ * const { results, totalCount, pageNumber } = await Recipe.query(perspective)
291
+ * .where({ status: "recipe://published" })
292
+ * .paginate(10, 1);
293
+ * ```
46
294
  */
47
295
  export declare class Ad4mModel {
48
- private _id;
296
+ private _baseExpression;
297
+ private _subjectClassName;
49
298
  private _perspective;
50
- /** Tracks whether save() has ever been called on this instance (even in an uncommitted batch). */
51
- private _savedOnce;
299
+ private _snapshot;
52
300
  author: string;
53
301
  createdAt: any;
54
302
  updatedAt: any;
55
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
+ };
56
323
  static getClassName(perspective: PerspectiveProxy): Promise<string>;
57
324
  /**
58
325
  * Backwards compatibility alias for createdAt.
59
326
  * @deprecated Use createdAt instead. This will be removed in a future version.
60
327
  */
61
328
  get timestamp(): any;
62
- /** Returns the class name, property predicates, and relation predicates from decorators. */
63
- static getModelMetadata(): ModelMetadata;
64
329
  /**
65
- * Installs the SHACL/SDNA subject class in `perspective` (idempotent).
330
+ * Extracts metadata from decorators for query building.
66
331
  *
67
- * @example `await Promise.all([Post, Comment, Tag].map(M => M.register(perspective)));`
68
- */
69
- static register(perspective: PerspectiveProxy): Promise<void>;
70
- /**
71
- * One-shot factory: constructs, assigns `data`, saves, and returns the new instance.
332
+ * @description
333
+ * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)
334
+ * and returns it in a structured format that's easier to work with for query builders
335
+ * and other systems that need to introspect model structure.
336
+ *
337
+ * The metadata includes:
338
+ * - Class name from @Model
339
+ * - Property metadata (predicates, types, constraints, etc.)
340
+ * - Relation metadata (predicates, filters, etc.)
341
+ *
342
+ * For models created via `fromJSONSchema()`, this method will derive metadata from
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.
346
+ *
347
+ * @returns Structured metadata object containing className, properties, and relations
348
+ * @throws Error if the class doesn't have @Model decorator
72
349
  *
73
350
  * @example
74
351
  * ```typescript
75
- * const post = await Post.create(perspective, { title: 'Hello', body: 'World' });
352
+ * @Model({ name: "Recipe" })
353
+ * class Recipe extends Ad4mModel {
354
+ * @Property({ through: "recipe://name", resolveLanguage: "literal" })
355
+ * name: string = "";
356
+ *
357
+ * @HasMany({ through: "recipe://ingredient" })
358
+ * ingredients: string[] = [];
359
+ * }
360
+ *
361
+ * const metadata = Recipe.getModelMetadata();
362
+ * console.log(metadata.className); // "Recipe"
363
+ * console.log(metadata.properties.name.predicate); // "recipe://name"
364
+ * console.log(metadata.relations.ingredients.predicate); // "recipe://ingredient"
76
365
  * ```
77
366
  */
78
- static create<T extends Ad4mModel>(this: new (perspective: PerspectiveProxy) => T, perspective: PerspectiveProxy, data: Partial<Omit<T, keyof Ad4mModel>>, options?: {
79
- parent?: ParentOptions;
80
- batchId?: string;
81
- }): Promise<T>;
367
+ static getModelMetadata(): ModelMetadata;
82
368
  /**
83
- * Fetches the instance, merges `data` into it, then saves.
369
+ * Constructs a new model instance.
370
+ *
371
+ * @param perspective - The perspective where this model will be stored
372
+ * @param baseExpression - Optional expression URI for this instance.
373
+ * If omitted, a random Literal URL is generated.
374
+ * @param source - Optional source expression this instance is linked to
84
375
  *
85
- * This is a convenience alternative to the three-step pattern:
376
+ * @example
86
377
  * ```typescript
87
- * // Before
88
- * const instance = new Vote(perspective, id);
89
- * instance.score = newScore;
90
- * await instance.save();
378
+ * // Create a new recipe with auto-generated base expression
379
+ * const recipe = new Recipe(perspective);
91
380
  *
92
- * // After
93
- * await Vote.update(perspective, id, { score: newScore });
381
+ * // Create with specific base expression
382
+ * const recipe = new Recipe(perspective, "literal://...");
94
383
  * ```
384
+ */
385
+ constructor(perspective: PerspectiveProxy, baseExpression?: string);
386
+ /**
387
+ * The unique identifier (expression URI) of this model instance.
388
+ */
389
+ get id(): string;
390
+ /**
391
+ * @deprecated Use `.id` instead. Will be removed in a future version.
392
+ */
393
+ get baseExpression(): string;
394
+ /**
395
+ * Protected getter for the perspective.
396
+ * Allows subclasses to access the perspective while keeping it private from external code.
397
+ */
398
+ protected get perspective(): PerspectiveProxy;
399
+ /**
400
+ * Get property metadata from decorator (Phase 1: Prolog-free refactor)
401
+ * @private
402
+ */
403
+ private getPropertyMetadata;
404
+ /**
405
+ * Get relation options from decorator
406
+ * @private
407
+ */
408
+ private getRelationOptions;
409
+ /**
410
+ * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
411
+ * Replaces Prolog query: property_setter(C, key, Setter)
412
+ * @private
413
+ */
414
+ private generatePropertySetterAction;
415
+ /**
416
+ * Generate relation action from metadata (Phase 1: Prolog-free refactor)
417
+ * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
418
+ * @private
419
+ */
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
95
429
  *
96
- * @param data - Partial set of properties to merge into the stored instance.
97
- * @param batchId - Optional batch identifier for grouping writes.
98
- * @returns The updated instance with all fields populated.
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.
99
441
  */
100
- static update<T extends Ad4mModel>(this: (new (perspective: PerspectiveProxy, id: string) => T) & typeof Ad4mModel, perspective: PerspectiveProxy, id: string, data: Partial<Omit<T, keyof Ad4mModel>>, batchId?: string): Promise<T>;
442
+ private static readonly _linkShape;
101
443
  /**
102
- * Deletes the instance with the given `id` from the perspective.
444
+ * Hydrates an instance from an array of raw links.
103
445
  *
104
- * This is a convenience alternative to:
105
- * ```typescript
106
- * // Before
107
- * const instance = new Poll(perspective, id);
108
- * await instance.delete();
446
+ * Processes properties (latest-wins semantics), relations
447
+ * (chronological accumulation), and timestamps/author in a single
448
+ * pass over the links array.
109
449
  *
110
- * // After
111
- * await Poll.delete(perspective, id);
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;
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
112
499
  * ```
500
+ */
501
+ isDirty(): boolean;
502
+ /**
503
+ * Returns the names of properties/relations that differ from the
504
+ * snapshot taken at the last hydration.
113
505
  *
114
- * @param batchId - Optional batch identifier for grouping removals.
506
+ * Returns **all** field names if no snapshot exists.
507
+ *
508
+ * @example
509
+ * ```typescript
510
+ * recipe.name = "New Name";
511
+ * recipe.changedFields(); // ["name"]
512
+ * ```
115
513
  */
116
- static delete(perspective: PerspectiveProxy, id: string, batchId?: string): Promise<void>;
514
+ changedFields(): string[];
515
+ private getData;
516
+ static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
117
517
  /**
118
- * Generates the SHACL shape for this model class.
119
- * Attached dynamically by the `@Model` decorator.
518
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
519
+ * @private
120
520
  */
121
- static generateSHACL(): {
122
- shape: SHACLShape;
123
- name: string;
124
- };
125
- /** @param id - Auto-generated from a random literal if omitted. */
126
- constructor(perspective: PerspectiveProxy, id?: string);
521
+ private static evaluateCustomGettersForInstance;
127
522
  /**
128
- * The unique identifier (base expression URI) of this instance.
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
129
534
  */
130
- get id(): string;
131
- /** Read-only perspective access for subclasses. */
132
- protected get perspective(): PerspectiveProxy;
133
- /** Builds the context object for all mutation functions. */
134
- private _mutationContext;
535
+ private static hydrateRelations;
135
536
  /**
136
- * Generates a SurrealQL query string for this model.
537
+ * Generates a SurrealQL query from a Query object.
137
538
  *
138
- * @param perspective - The perspective context
539
+ * @description
540
+ * This method translates high-level query parameters into a SurrealQL query string
541
+ * that can be executed against the SurrealDB backend. Unlike Prolog queries which
542
+ * operate on SDNA-aware predicates, SurrealQL queries operate directly on raw links
543
+ * stored in SurrealDB.
544
+ *
545
+ * The generated query uses a CTE (Common Table Expression) pattern:
546
+ * 1. First, identify candidate base expressions by filtering links based on where conditions
547
+ * 2. Then, for each candidate base, resolve properties and relations via subqueries
548
+ * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level
549
+ *
550
+ * Key architectural notes:
551
+ * - SurrealDB stores only raw links (source, predicate, target, author, timestamp)
552
+ * - No SDNA knowledge at the database level
553
+ * - Properties are resolved via subqueries that look for links with specific predicates
554
+ * - Relations are similar but return multiple values instead of one
555
+ * - Special fields (base, author, timestamp) are accessed directly, not via subqueries
556
+ *
557
+ * @param perspective - The perspective to query (used for metadata extraction)
139
558
  * @param query - Query parameters (where, order, limit, offset, properties, relations)
140
559
  * @returns Complete SurrealQL query string ready for execution
560
+ *
561
+ * @example
562
+ * ```typescript
563
+ * const query = Recipe.queryToSurrealQL(perspective, {
564
+ * where: { name: "Pasta", rating: { gt: 4 } },
565
+ * order: { timestamp: "DESC" },
566
+ * limit: 10
567
+ * });
568
+ * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...
569
+ * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10
570
+ * ```
141
571
  */
142
572
  static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
143
- /** @internal */
144
- static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[], _hydrateRelations?: boolean): Promise<ResultsWithTotalCount<T>>;
145
573
  /**
146
- * Internal implementation used by findAll and eager relation hydration.
147
- * Pass `_hydrateRelations = false` to prevent recursive model hydration (depth guard).
574
+ * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
575
+ *
576
+ * @description
577
+ * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
578
+ * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
579
+ *
580
+ * Handles several condition types:
581
+ * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
582
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
583
+ * - NOT operators: Use `NOT` prefix
584
+ * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
585
+ * - Special fields: base uses `uri` directly, author/timestamp handled post-query
586
+ *
587
+ * @param metadata - Model metadata containing property predicates
588
+ * @param where - Where conditions from the query
589
+ * @returns Graph traversal WHERE clause filters, or empty string if no conditions
590
+ *
591
+ * @private
592
+ */
593
+ private static buildGraphTraversalWhereClause;
594
+ /**
595
+ * Builds the WHERE clause for SurrealQL queries.
596
+ *
597
+ * @description
598
+ * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
599
+ * For each property filter, generates a subquery that checks for links with the appropriate
600
+ * predicate and target value.
601
+ *
602
+ * Handles several condition types:
603
+ * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
604
+ * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
605
+ * - Operators: `{ rating: { gt: 4 } }` → target > '4'
606
+ * - gt, gte, lt, lte: comparison operators
607
+ * - not: negation (single value or array)
608
+ * - between: range check
609
+ * - contains: substring/element check (uses SurrealQL CONTAINS)
610
+ * - Special fields: base, author, timestamp are accessed directly, not via subqueries
611
+ *
612
+ * All conditions are joined with AND.
613
+ *
614
+ * @param metadata - Model metadata containing property predicates
615
+ * @param where - Where conditions from the query
616
+ * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
617
+ *
618
+ * @private
619
+ */
620
+ private static buildSurrealWhereClause;
621
+ /**
622
+ * Builds the SELECT fields for SurrealQL queries.
623
+ *
624
+ * @description
625
+ * Generates the field list for the SELECT clause, resolving properties and relations
626
+ * via subqueries. Each property is fetched with a subquery that finds the link with the
627
+ * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
628
+ *
629
+ * Field types:
630
+ * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
631
+ * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
632
+ * - Author/Timestamp: Always included to provide metadata about each instance
633
+ *
634
+ * If properties or relations arrays are provided, only those fields are included.
635
+ * Otherwise, all properties/relations from metadata are included.
636
+ *
637
+ * @param metadata - Model metadata containing property and relation predicates
638
+ * @param properties - Optional array of property names to include (default: all)
639
+ * @param relations - Optional array of relation names to include (default: all)
640
+ * @returns Comma-separated SELECT field list
641
+ *
642
+ * @private
643
+ */
644
+ private static buildSurrealSelectFields;
645
+ /**
646
+ * Builds the SELECT fields for SurrealQL queries using aggregation functions.
647
+ * Compatible with GROUP BY source queries.
648
+ *
649
+ * @private
650
+ */
651
+ private static buildSurrealSelectFieldsWithAggregation;
652
+ /**
653
+ * Formats a value for use in SurrealQL queries.
654
+ *
655
+ * @description
656
+ * Handles different value types:
657
+ * - Strings: Wrapped in single quotes with backslash-escaped special characters
658
+ * - Numbers/booleans: Converted to string
659
+ * - Arrays: Recursively formatted and wrapped in brackets
660
+ *
661
+ * @param value - The value to format
662
+ * @returns Formatted value string ready for SurrealQL
663
+ *
664
+ * @private
665
+ */
666
+ private static formatSurrealValue;
667
+ static instancesFromPrologResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: AllInstancesResult): Promise<ResultsWithTotalCount<T>>;
668
+ /**
669
+ * Converts SurrealDB query results to Ad4mModel instances.
670
+ *
671
+ * @param perspective - The perspective context
672
+ * @param query - The query parameters used
673
+ * @param result - Array of result objects from SurrealDB
674
+ * @returns Promise resolving to results with total count
675
+ *
676
+ * @internal
677
+ */
678
+ static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[]): Promise<ResultsWithTotalCount<T>>;
679
+ /**
680
+ * Checks if a value matches a condition (for post-query filtering).
681
+ * @private
148
682
  */
149
- static _findAllInternal<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, _hydrateRelations?: boolean): Promise<T[]>;
683
+ private static matchesCondition;
150
684
  /**
151
- * Returns all instances matching `query`.
685
+ * Gets all instances of the model in the perspective that match the query params.
686
+ *
687
+ * @param perspective - The perspective to search in
688
+ * @param query - Optional query parameters to filter results
689
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
690
+ * @returns Array of matching models
152
691
  *
153
692
  * @example
154
693
  * ```typescript
694
+ * // Get all recipes (uses SurrealDB by default)
695
+ * const allRecipes = await Recipe.findAll(perspective);
696
+ *
697
+ * // Get recipes with specific criteria (uses SurrealDB)
155
698
  * const recipes = await Recipe.findAll(perspective, {
156
- * where: { rating: { gt: 4 } }, order: { createdAt: "DESC" }, limit: 10,
699
+ * where: {
700
+ * name: "Pasta",
701
+ * rating: { gt: 4 }
702
+ * },
703
+ * order: { createdAt: "DESC" },
704
+ * limit: 10
157
705
  * });
706
+ *
707
+ * // Explicitly use Prolog (legacy, for backward compatibility)
708
+ * const recipesProlog = await Recipe.findAll(perspective, {}, false);
158
709
  * ```
159
710
  */
160
- static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<T[]>;
711
+ static findAll<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T[]>;
161
712
  /**
162
- * Returns the first matching instance, or `null` if none found.
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`
163
721
  *
164
722
  * @example
165
723
  * ```typescript
166
- * const post = await TestPost.findOne(perspective, { where: { id: someId } });
724
+ * const recipe = await Recipe.findOne(perspective, {
725
+ * where: { name: "Pasta" }
726
+ * });
727
+ * if (recipe) {
728
+ * console.log(recipe.name);
729
+ * }
167
730
  * ```
168
731
  */
169
- static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<T | null>;
732
+ static findOne<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<T | null>;
170
733
  /**
171
- * Like `findAll` but also returns the unfiltered total count (useful for pagination UI).
734
+ * Gets all instances with count of total matches without offset & limit applied.
735
+ *
736
+ * @param perspective - The perspective to search in
737
+ * @param query - Optional query parameters to filter results
738
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
739
+ * @returns Object containing results array and total count
172
740
  *
173
741
  * @example
174
742
  * ```typescript
175
- * const { results, totalCount } = await Recipe.findAllAndCount(perspective, { limit: 10 });
176
- * console.log(`Showing ${results.length} of ${totalCount}`);
743
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {
744
+ * where: { category: "Dessert" },
745
+ * limit: 10
746
+ * });
747
+ * console.log(`Showing 10 of ${totalCount} dessert recipes`);
748
+ *
749
+ * // Use Prolog explicitly (legacy)
750
+ * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {}, false);
177
751
  * ```
178
752
  */
179
- static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): Promise<ResultsWithTotalCount<T>>;
753
+ static findAllAndCount<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): Promise<ResultsWithTotalCount<T>>;
180
754
  /**
181
- * Fetches a single page of results (`pageNumber` is 1-based).
755
+ * Helper function for pagination with explicit page size and number.
756
+ *
757
+ * @param perspective - The perspective to search in
758
+ * @param pageSize - Number of items per page
759
+ * @param pageNumber - Which page to retrieve (1-based)
760
+ * @param query - Optional additional query parameters
761
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
762
+ * @returns Paginated results with metadata
182
763
  *
183
764
  * @example
184
765
  * ```typescript
185
- * const page = await Recipe.paginate(perspective, 10, 1);
186
- * console.log(`Page ${page.pageNumber}, ${page.results.length} items`);
766
+ * const page = await Recipe.paginate(perspective, 10, 1, {
767
+ * where: { category: "Main Course" }
768
+ * });
769
+ * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
770
+ *
771
+ * // Use Prolog explicitly (legacy)
772
+ * const pageProlog = await Recipe.paginate(perspective, 10, 1, {}, false);
187
773
  * ```
188
774
  */
189
- static paginate<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, pageSize: number, pageNumber: number, query?: Query): Promise<PaginationResult<T>>;
775
+ 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>>;
776
+ static countQueryToProlog(perspective: PerspectiveProxy, query?: Query, modelClassName?: string | null): Promise<string>;
190
777
  /**
191
- * Generates a SurrealQL COUNT query for this model.
778
+ * Generates a SurrealQL COUNT query for the model.
779
+ *
780
+ * @param perspective - The perspective context
781
+ * @param query - Query parameters to filter the count
782
+ * @returns SurrealQL COUNT query string
783
+ *
192
784
  * @private
193
785
  */
194
786
  static countQueryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
195
- /** Returns the count of instances matching `query`. */
196
- static count(perspective: PerspectiveProxy, query?: Query): Promise<number>;
197
787
  /**
198
- * Persists the instance (create if new, update if existing).
788
+ * Gets a count of all matching instances.
199
789
  *
200
- * @param batchId - When provided the caller must call `perspective.commitBatch(batchId)`
790
+ * @param perspective - The perspective to search in
791
+ * @param query - Optional query parameters to filter results
792
+ * @param useSurrealDB - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
793
+ * @returns Total count of matching entities
201
794
  *
202
795
  * @example
203
796
  * ```typescript
797
+ * const totalRecipes = await Recipe.count(perspective);
798
+ * const activeRecipes = await Recipe.count(perspective, {
799
+ * where: { status: "active" }
800
+ * });
801
+ *
802
+ * // Use Prolog explicitly (legacy)
803
+ * const countProlog = await Recipe.count(perspective, {}, false);
804
+ * ```
805
+ */
806
+ static count(perspective: PerspectiveProxy, query?: Query, useSurrealDB?: boolean): any;
807
+ private setProperty;
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;
814
+ /**
815
+ * Saves the model instance to the perspective.
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.
824
+ *
825
+ * @param batchId - Optional batch ID for batch operations
826
+ * @throws Will throw if instance creation, linking, or updating fails
827
+ *
828
+ * @example
829
+ * ```typescript
830
+ * // Create
204
831
  * const recipe = new Recipe(perspective);
205
832
  * recipe.name = "Spaghetti";
206
- * await recipe.save(); // create
207
- * recipe.name = "Bolognese";
208
- * await recipe.save(); // update (detected automatically)
833
+ * await recipe.save();
834
+ *
835
+ * // Update
836
+ * recipe.rating = 10;
837
+ * await recipe.save();
209
838
  * ```
210
839
  */
211
840
  save(batchId?: string): Promise<void>;
841
+ private cleanCopy;
842
+ private innerUpdate;
212
843
  /**
213
844
  * Gets the model instance with all properties and relations populated.
214
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 } }`)
215
849
  * @returns The populated model instance
216
850
  * @throws Will throw if data retrieval fails
217
851
  *
@@ -220,75 +854,648 @@ export declare class Ad4mModel {
220
854
  * const recipe = new Recipe(perspective, existingId);
221
855
  * await recipe.get();
222
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'] });
223
863
  * ```
224
864
  */
225
- get(include?: IncludeMap): Promise<this>;
865
+ get(optsOrInclude?: GetOptions | IncludeMap): Promise<this>;
226
866
  /**
227
- * Removes this instance from the perspective, including all incoming links
228
- * that point to it (e.g. parent→child membership links created by
229
- * `create({ parent: ... })`). This ensures that `findAll({ parent: ... })`
230
- * will no longer return this instance after deletion.
867
+ * Deletes the model instance from the perspective.
868
+ *
869
+ * @param batchId - Optional batch ID for batch operations
870
+ * @throws Will throw if removal fails
231
871
  *
232
872
  * @example
233
- * await vote.delete();
873
+ * ```typescript
874
+ * const recipe = await Recipe.findAll(perspective)[0];
875
+ * await recipe.delete();
234
876
  *
235
- * @param batchId - Optional batch identifier for grouping removals.
877
+ * // Or with batch operations:
878
+ * const batchId = await perspective.createBatch();
879
+ * await recipe.delete(batchId);
880
+ * await perspective.commitBatch(batchId);
881
+ * ```
236
882
  */
237
883
  delete(batchId?: string): Promise<void>;
238
884
  /**
239
- * Returns a fluent query builder for this model.
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`
240
1001
  *
241
1002
  * @example
242
1003
  * ```typescript
243
- * const top5 = await Recipe.query(perspective)
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>;
1018
+ /**
1019
+ * Creates a query builder for fluent query construction.
1020
+ *
1021
+ * @param perspective - The perspective to query
1022
+ * @param query - Optional initial query parameters
1023
+ * @returns A new query builder instance
1024
+ *
1025
+ * @example
1026
+ * ```typescript
1027
+ * const recipes = await Recipe.query(perspective)
244
1028
  * .where({ category: "Dessert" })
245
1029
  * .order({ rating: "DESC" })
246
1030
  * .limit(5)
247
1031
  * .run();
1032
+ *
1033
+ * // With real-time updates
1034
+ * await Recipe.query(perspective)
1035
+ * .where({ status: "cooking" })
1036
+ * .subscribe(recipes => {
1037
+ * console.log("Currently cooking:", recipes);
1038
+ * });
248
1039
  * ```
249
1040
  */
250
1041
  static query<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query?: Query): ModelQueryBuilder<T>;
251
1042
  /**
252
- * Runs `callback` in an atomic batch; commits on success, aborts + rethrows on failure.
1043
+ * Creates an Ad4mModel class from a JSON Schema definition.
1044
+ *
1045
+ * @description
1046
+ * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
1047
+ * enabling integration with systems that use JSON Schema for type definitions.
1048
+ *
1049
+ * The method follows a cascading approach for determining predicates:
1050
+ * 1. Explicit configuration in options parameter (highest precedence)
1051
+ * 2. x-ad4m metadata in the JSON Schema
1052
+ * 3. Inference from schema title and property names
1053
+ * 4. Error if no namespace can be determined
253
1054
  *
254
1055
  * @example
255
1056
  * ```typescript
256
- * await Ad4mModel.transaction(perspective, async (tx) => {
257
- * await post.save(tx.batchId);
258
- * await comment.save(tx.batchId);
1057
+ * // With explicit configuration
1058
+ * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
1059
+ * name: "Person",
1060
+ * namespace: "person://",
1061
+ * resolveLanguage: "literal"
1062
+ * });
1063
+ *
1064
+ * // With property mapping
1065
+ * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
1066
+ * name: "Contact",
1067
+ * namespace: "contact://",
1068
+ * propertyMapping: {
1069
+ * "name": "foaf://name",
1070
+ * "email": "foaf://mbox"
1071
+ * }
259
1072
  * });
1073
+ *
1074
+ * // With x-ad4m metadata in schema
1075
+ * const schema = {
1076
+ * "title": "Product",
1077
+ * "x-ad4m": { "namespace": "product://" },
1078
+ * "properties": {
1079
+ * "name": {
1080
+ * "type": "string",
1081
+ * "x-ad4m": { "through": "product://title" }
1082
+ * }
1083
+ * }
1084
+ * };
1085
+ * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
260
1086
  * ```
1087
+ *
1088
+ * @param schema - JSON Schema definition
1089
+ * @param options - Configuration options
1090
+ * @returns Generated Ad4mModel subclass
1091
+ * @throws Error when namespace cannot be inferred
1092
+ */
1093
+ static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1094
+ /**
1095
+ * Determines the namespace for predicates using cascading precedence
1096
+ */
1097
+ private static determineNamespace;
1098
+ /**
1099
+ * Determines the predicate for a specific property using cascading precedence
1100
+ */
1101
+ private static determinePredicate;
1102
+ /**
1103
+ * Gets property-specific options using cascading precedence
261
1104
  */
262
- static transaction<T>(perspective: PerspectiveProxy, callback: (tx: import("./transaction").TransactionContext) => Promise<T>): Promise<T>;
1105
+ private static getPropertyOption;
1106
+ /**
1107
+ * Gets default value for a JSON Schema type
1108
+ */
1109
+ private static getDefaultValueForType;
1110
+ }
1111
+ /** Query builder for Ad4mModel queries.
1112
+ * Allows building queries with a fluent interface and either running them once
1113
+ * or subscribing to updates.
1114
+ *
1115
+ * @example
1116
+ * ```typescript
1117
+ * const builder = Recipe.query(perspective)
1118
+ * .where({ category: "Dessert" })
1119
+ * .order({ rating: "DESC" })
1120
+ * .limit(10);
1121
+ *
1122
+ * // Run once
1123
+ * const recipes = await builder.run();
1124
+ *
1125
+ * // Or subscribe to updates
1126
+ * await builder.subscribe(recipes => {
1127
+ * console.log("Updated recipes:", recipes);
1128
+ * });
1129
+ * ```
1130
+ */
1131
+ export declare class ModelQueryBuilder<T extends Ad4mModel> {
1132
+ private perspective;
1133
+ private queryParams;
1134
+ private modelClassName;
1135
+ private ctor;
1136
+ private currentSubscription?;
1137
+ private useSurrealDBFlag;
1138
+ constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query);
263
1139
  /**
264
- * Fires `callback` immediately with current results, then on every relevant perspective change.
1140
+ * Disposes of the current subscription if one exists.
265
1141
  *
266
- * @param options - Query params plus optional `debounce` (ms) and `onError` handler
267
- * @param callback - Receives the fresh result set on each delivery
268
- * @returns `Subscription` with `unsubscribe()` — call it in cleanup to avoid leaks
1142
+ * This method:
1143
+ * 1. Stops the keepalive signals to the subscription
1144
+ * 2. Unsubscribes from GraphQL subscription updates
1145
+ * 3. Notifies the backend to clean up subscription resources
1146
+ * 4. Clears the subscription reference
1147
+ *
1148
+ * You should call this method when you're done with a subscription
1149
+ * to prevent memory leaks and ensure proper cleanup.
1150
+ */
1151
+ dispose(): void;
1152
+ /**
1153
+ * Adds where conditions to the query.
1154
+ *
1155
+ * @param conditions - The conditions to filter by
1156
+ * @returns The query builder for chaining
269
1157
  *
270
1158
  * @example
271
1159
  * ```typescript
272
- * const sub = Post.subscribe(
273
- * perspective,
274
- * { where: { published: true }, debounce: 300 },
275
- * (posts) => setPosts(posts),
276
- * );
277
- * sub.unsubscribe(); // in cleanup
1160
+ * .where({
1161
+ * category: "Dessert",
1162
+ * rating: { gt: 4 },
1163
+ * tags: ["vegan", "quick"],
1164
+ * published: true
1165
+ * })
278
1166
  * ```
279
1167
  */
280
- static subscribe<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, options: SubscribeOptions, callback: (results: T[]) => void): Subscription;
1168
+ where(conditions: Where): ModelQueryBuilder<T>;
281
1169
  /**
282
- * Generates an `Ad4mModel` subclass from a JSON Schema definition.
1170
+ * Sets the order for the query results.
283
1171
  *
284
- * Predicate resolution order: explicit options → `x-ad4m` in schema → inferred from title/names.
1172
+ * @param orderBy - The ordering criteria
1173
+ * @returns The query builder for chaining
285
1174
  *
286
1175
  * @example
287
1176
  * ```typescript
288
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
289
- * name: "Person", namespace: "person://", resolveLanguage: "literal",
1177
+ * .order({ createdAt: "DESC" })
1178
+ * ```
1179
+ */
1180
+ order(orderBy: Order): ModelQueryBuilder<T>;
1181
+ /**
1182
+ * Sets the maximum number of results to return.
1183
+ *
1184
+ * @param limit - Maximum number of results
1185
+ * @returns The query builder for chaining
1186
+ *
1187
+ * @example
1188
+ * ```typescript
1189
+ * .limit(10)
1190
+ * ```
1191
+ */
1192
+ limit(limit: number): ModelQueryBuilder<T>;
1193
+ /**
1194
+ * Sets the number of results to skip.
1195
+ *
1196
+ * @param offset - Number of results to skip
1197
+ * @returns The query builder for chaining
1198
+ *
1199
+ * @example
1200
+ * ```typescript
1201
+ * .offset(20) // Skip first 20 results
1202
+ * ```
1203
+ */
1204
+ offset(offset: number): ModelQueryBuilder<T>;
1205
+ /**
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
1225
+ * @returns The query builder for chaining
1226
+ *
1227
+ * @example
1228
+ * ```typescript
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();
1243
+ * ```
1244
+ */
1245
+ parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
1246
+ field: string;
1247
+ }, options?: {
1248
+ field?: string;
1249
+ }): ModelQueryBuilder<T>;
1250
+ /**
1251
+ * Specifies which properties to include in the results.
1252
+ *
1253
+ * @param properties - Array of property names to include
1254
+ * @returns The query builder for chaining
1255
+ *
1256
+ * @example
1257
+ * ```typescript
1258
+ * .properties(["name", "description", "rating"])
1259
+ * ```
1260
+ */
1261
+ properties(properties: string[]): ModelQueryBuilder<T>;
1262
+ /**
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.
1268
+ *
1269
+ * Supports nested includes for multi-level eager loading.
1270
+ *
1271
+ * @param map - An IncludeMap describing which relations to hydrate
1272
+ * @returns The query builder for chaining
1273
+ *
1274
+ * @example
1275
+ * ```typescript
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();
1286
+ * ```
1287
+ */
1288
+ include(map: IncludeMap): ModelQueryBuilder<T>;
1289
+ overrideModelClassName(className: string): ModelQueryBuilder<T>;
1290
+ /**
1291
+ * Enables or disables SurrealDB query path.
1292
+ *
1293
+ * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1294
+ * @returns The query builder for chaining
1295
+ *
1296
+ * @example
1297
+ * ```typescript
1298
+ * // Use SurrealDB (default)
1299
+ * const recipes = await Recipe.query(perspective)
1300
+ * .where({ category: "Dessert" })
1301
+ * .useSurrealDB(true)
1302
+ * .get();
1303
+ *
1304
+ * // Use Prolog (legacy)
1305
+ * const recipesProlog = await Recipe.query(perspective)
1306
+ * .where({ category: "Dessert" })
1307
+ * .useSurrealDB(false)
1308
+ * .get();
1309
+ * ```
1310
+ *
1311
+ * @remarks
1312
+ * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
1313
+ * if useSurrealDB(true) is set (default).
1314
+ */
1315
+ useSurrealDB(enabled?: boolean): ModelQueryBuilder<T>;
1316
+ /**
1317
+ * Executes the query once and returns the results.
1318
+ *
1319
+ * @returns Array of matching entities
1320
+ *
1321
+ * @example
1322
+ * ```typescript
1323
+ * const recipes = await Recipe.query(perspective)
1324
+ * .where({ category: "Dessert" })
1325
+ * .get();
1326
+ * ```
1327
+ */
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>;
1344
+ /**
1345
+ * Subscribes to the query and receives updates when results change.
1346
+ *
1347
+ * This method:
1348
+ * 1. Creates and initializes a SurrealDB live query subscription (default)
1349
+ * 2. Sets up the callback to process future updates
1350
+ * 3. Returns the initial results immediately
1351
+ *
1352
+ * Remember to call dispose() when you're done with the subscription
1353
+ * to clean up resources.
1354
+ *
1355
+ * @param callback - Function to call with updated results
1356
+ * @returns Initial results array
1357
+ *
1358
+ * @example
1359
+ * ```typescript
1360
+ * const builder = Recipe.query(perspective)
1361
+ * .where({ status: "cooking" });
1362
+ *
1363
+ * const initialRecipes = await builder.subscribe(recipes => {
1364
+ * console.log("Updated recipes:", recipes);
290
1365
  * });
1366
+ *
1367
+ * // When done with subscription:
1368
+ * builder.dispose();
291
1369
  * ```
1370
+ *
1371
+ * @remarks
1372
+ * By default, this uses SurrealDB live queries for real-time updates.
1373
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
292
1374
  */
293
- static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1375
+ subscribe(callback: (results: T[]) => void): Promise<T[]>;
1376
+ /**
1377
+ * Gets the total count of matching entities.
1378
+ *
1379
+ * @returns Total count
1380
+ *
1381
+ * @example
1382
+ * ```typescript
1383
+ * const totalDesserts = await Recipe.query(perspective)
1384
+ * .where({ category: "Dessert" })
1385
+ * .count();
1386
+ * ```
1387
+ */
1388
+ count(): Promise<number>;
1389
+ /**
1390
+ * Subscribes to count updates for matching entities.
1391
+ *
1392
+ * This method:
1393
+ * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
1394
+ * 2. Sets up the callback to process future count updates
1395
+ * 3. Returns the initial count immediately
1396
+ *
1397
+ * Remember to call dispose() when you're done with the subscription
1398
+ * to clean up resources.
1399
+ *
1400
+ * @param callback - Function to call with updated count
1401
+ * @returns Initial count
1402
+ *
1403
+ * @example
1404
+ * ```typescript
1405
+ * const builder = Recipe.query(perspective)
1406
+ * .where({ status: "active" });
1407
+ *
1408
+ * const initialCount = await builder.countSubscribe(count => {
1409
+ * console.log("Active items:", count);
1410
+ * });
1411
+ *
1412
+ * // When done with subscription:
1413
+ * builder.dispose();
1414
+ * ```
1415
+ *
1416
+ * @remarks
1417
+ * By default, this uses SurrealDB live queries for real-time updates.
1418
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1419
+ */
1420
+ countSubscribe(callback: (count: number) => void): Promise<number>;
1421
+ /**
1422
+ * Gets a page of results with pagination metadata.
1423
+ *
1424
+ * @param pageSize - Number of items per page
1425
+ * @param pageNumber - Which page to retrieve (1-based)
1426
+ * @returns Paginated results with metadata
1427
+ *
1428
+ * @example
1429
+ * ```typescript
1430
+ * const page = await Recipe.query(perspective)
1431
+ * .where({ category: "Main" })
1432
+ * .paginate(10, 1);
1433
+ * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1434
+ * ```
1435
+ */
1436
+ paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
1437
+ /**
1438
+ * Subscribes to paginated results updates.
1439
+ *
1440
+ * This method:
1441
+ * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
1442
+ * 2. Sets up the callback to process future page updates
1443
+ * 3. Returns the initial page immediately
1444
+ *
1445
+ * Remember to call dispose() when you're done with the subscription
1446
+ * to clean up resources.
1447
+ *
1448
+ * @param pageSize - Number of items per page
1449
+ * @param pageNumber - Which page to retrieve (1-based)
1450
+ * @param callback - Function to call with updated pagination results
1451
+ * @returns Initial pagination results
1452
+ *
1453
+ * @example
1454
+ * ```typescript
1455
+ * const builder = Recipe.query(perspective)
1456
+ * .where({ category: "Main" });
1457
+ *
1458
+ * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1459
+ * console.log("Updated page:", page.results);
1460
+ * });
1461
+ *
1462
+ * // When done with subscription:
1463
+ * builder.dispose();
1464
+ * ```
1465
+ *
1466
+ * @remarks
1467
+ * By default, this uses SurrealDB live queries for real-time updates.
1468
+ * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1469
+ */
1470
+ paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
294
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;
1501
+ export {};