@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0

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 (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -1,210 +1,7 @@
1
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
- export 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
- export type WhereCondition = string | number | boolean | string[] | number[] | {
53
- [K in keyof WhereOps]?: WhereOps[K];
54
- };
55
- export 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 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
- /** Target model class thunk for hydration and type filtering */
188
- target?: () => any;
189
- /**
190
- * Whether to auto-generate a conformance filter when `target` is set.
191
- * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
192
- */
193
- filter?: boolean;
194
- /** Where clause for relation filtering (query DSL) */
195
- where?: Where;
196
- }
197
- /**
198
- * Complete model metadata extracted from decorators.
199
- */
200
- export interface ModelMetadata {
201
- /** The model class name from @Model */
202
- className: string;
203
- /** Map of property name to metadata */
204
- properties: Record<string, PropertyMetadata>;
205
- /** Map of relation name to metadata */
206
- relations: Record<string, RelationMetadata>;
207
- }
2
+ import type { JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
3
+ import { ModelQueryBuilder } from "./ModelQueryBuilder";
4
+ import type { ParentScope, IncludeMap, Query, GetOptions, AllInstancesResult, ResultsWithTotalCount, PaginationResult, ModelMetadata, ValueTuple } from "./types";
208
5
  /**
209
6
  * Base class for defining data models in AD4M.
210
7
  *
@@ -303,7 +100,6 @@ export interface ModelMetadata {
303
100
  */
304
101
  export declare class Ad4mModel {
305
102
  private _baseExpression;
306
- private _subjectClassName;
307
103
  private _perspective;
308
104
  private _snapshot;
309
105
  author: string;
@@ -406,7 +202,7 @@ export declare class Ad4mModel {
406
202
  */
407
203
  protected get perspective(): PerspectiveProxy;
408
204
  /**
409
- * Get property metadata from decorator (Phase 1: Prolog-free refactor)
205
+ * Get property metadata from decorator.
410
206
  * @private
411
207
  */
412
208
  private getPropertyMetadata;
@@ -416,70 +212,20 @@ export declare class Ad4mModel {
416
212
  */
417
213
  private getRelationOptions;
418
214
  /**
419
- * Generate property setter action from metadata (Phase 1: Prolog-free refactor)
420
- * Replaces Prolog query: property_setter(C, key, Setter)
215
+ * Generate property setter action from metadata.
421
216
  * @private
422
217
  */
423
218
  private generatePropertySetterAction;
424
219
  /**
425
- * Generate relation action from metadata (Phase 1: Prolog-free refactor)
426
- * Replaces Prolog queries: collection_adder, collection_remover, collection_setter
220
+ * Generate relation action from metadata.
427
221
  * @private
428
222
  */
429
223
  private generateRelationAction;
430
224
  /**
431
- * Resolves a raw link target value into a hydrated property value.
432
- *
433
- * Handles, in order:
434
- * 1. Non-literal expression resolution (`perspective.getExpression`)
435
- * 2. Literal URI parsing (`Literal.fromUrl(…).get()`)
436
- * 3. Primitive type coercion (string → number / boolean)
437
- * 4. Transform function application
438
- *
439
- * @param target - The raw target string from the link
440
- * @param propMeta - Property metadata from the decorator registry
441
- * @param perspective - The perspective for expression resolution
442
- * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
443
- * @returns The resolved value
444
- * @private
445
- */
446
- private static hydratePropertyValue;
447
- /**
448
- * Link shape accepted by `hydrateFromLinks`.
449
- * Both `getData()` and `instancesFromSurrealResult()` produce this shape.
225
+ * Assigns decoded Prolog property values to an instance.
226
+ * Delegates to the standalone function in hydration.ts.
450
227
  */
451
- private static readonly _linkShape;
452
- /**
453
- * Hydrates an instance from an array of raw links.
454
- *
455
- * Processes properties (latest-wins semantics), relations
456
- * (chronological accumulation), and timestamps/author in a single
457
- * pass over the links array.
458
- *
459
- * @param instance - The blank model instance to populate
460
- * @param links - Array of link objects (predicate, target, author?, timestamp?)
461
- * @param metadata - Model metadata from `getModelMetadata()`
462
- * @param perspective - The perspective for expression resolution
463
- * @param requestedProperties - Optional sparse fieldset; when provided, only these
464
- * property names are hydrated (relations are unaffected).
465
- * Omit or pass `undefined` to hydrate all properties.
466
- * @private
467
- */
468
- private static hydrateFromLinks;
469
228
  static assignValuesToInstance(perspective: PerspectiveProxy, instance: Ad4mModel, values: ValueTuple[]): Promise<void>;
470
- /**
471
- * Captures a shallow snapshot of the instance's current property and
472
- * relation values. Called automatically after hydration (`get()`,
473
- * query results). The snapshot is used by `isDirty()`,
474
- * `changedFields()`, and by `update()` to skip unchanged fields.
475
- * @private
476
- */
477
- /**
478
- * Normalize a value for snapshot storage.
479
- * Arrays of model instances are reduced to their `.id` strings so that
480
- * dirty-tracking compares stable identifiers instead of object references.
481
- */
482
- private static normalizeValue;
483
229
  /**
484
230
  * @param includedRelations Controls which relation fields are recorded
485
231
  * in the snapshot for dirty-tracking:
@@ -523,46 +269,6 @@ export declare class Ad4mModel {
523
269
  changedFields(): string[];
524
270
  private getData;
525
271
  static queryToProlog(perspective: PerspectiveProxy, query: Query, modelClassName?: string | null): Promise<string>;
526
- /**
527
- * Builds a SurrealQL conformance getter for a relation whose `target` model
528
- * is known but no explicit `getter` string was supplied.
529
- *
530
- * The generated getter traverses outgoing links matching the relation's
531
- * predicate and then filters the target nodes to only those that conform to
532
- * the target model's shape (required properties / flags).
533
- *
534
- * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
535
- * so the same logic is used at shape-definition time and at query time.
536
- *
537
- * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
538
- * @param targetClass - The target model class (result of calling the `target()` thunk)
539
- * @returns A SurrealQL expression string, or `undefined` if no conformance
540
- * conditions could be derived from the target model.
541
- * @private
542
- */
543
- private static buildConformanceGetter;
544
- /**
545
- * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
546
- *
547
- * For relations that declare a `target` but no explicit `getter`, a conformance
548
- * getter is auto-generated from the target model's metadata (unless `filter: false`).
549
- * @private
550
- */
551
- private static evaluateCustomGettersForInstance;
552
- /**
553
- * Hydrates relation fields on instances according to the provided IncludeMap.
554
- *
555
- * For each relation listed in `includeMap`, the raw expression-URI strings
556
- * stored on the instance are replaced with fully-hydrated model instances
557
- * (fetched via the relation's `target()` class). Nested IncludeMaps are
558
- * supported for multi-level eager loading.
559
- *
560
- * @param instances - The instances whose relations should be hydrated
561
- * @param perspective - The perspective to fetch related instances from
562
- * @param includeMap - Describes which relations to hydrate
563
- * @private
564
- */
565
- private static hydrateRelations;
566
272
  /**
567
273
  * Generates a SurrealQL query from a Query object.
568
274
  *
@@ -600,100 +306,6 @@ export declare class Ad4mModel {
600
306
  * ```
601
307
  */
602
308
  static queryToSurrealQL(perspective: PerspectiveProxy, query: Query): Promise<string>;
603
- /**
604
- * Builds the WHERE clause for SurrealQL queries using graph traversal syntax.
605
- *
606
- * @description
607
- * Translates where conditions into graph traversal filters: `->link[WHERE ...]`
608
- * This is more efficient than nested SELECTs because SurrealDB can optimize graph traversals.
609
- *
610
- * Handles several condition types:
611
- * - Simple equality: `{ name: "Pasta" }` → `->link[WHERE predicate = 'X' AND out.uri = 'Pasta']`
612
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → `->link[WHERE predicate = 'X' AND out.uri IN [...]]`
613
- * - NOT operators: Use `NOT` prefix
614
- * - Comparison operators (gt, gte, lt, lte, etc.): Handled in post-query JavaScript filtering
615
- * - Special fields: base uses `uri` directly, author/timestamp handled post-query
616
- *
617
- * @param metadata - Model metadata containing property predicates
618
- * @param where - Where conditions from the query
619
- * @returns Graph traversal WHERE clause filters, or empty string if no conditions
620
- *
621
- * @private
622
- */
623
- private static buildGraphTraversalWhereClause;
624
- /**
625
- * Builds the WHERE clause for SurrealQL queries.
626
- *
627
- * @description
628
- * Translates the where conditions from the Query object into SurrealQL WHERE clause fragments.
629
- * For each property filter, generates a subquery that checks for links with the appropriate
630
- * predicate and target value.
631
- *
632
- * Handles several condition types:
633
- * - Simple equality: `{ name: "Pasta" }` → subquery checking for predicate and target match
634
- * - Arrays (IN clause): `{ name: ["Pasta", "Pizza"] }` → target IN [...]
635
- * - Operators: `{ rating: { gt: 4 } }` → target > '4'
636
- * - gt, gte, lt, lte: comparison operators
637
- * - not: negation (single value or array)
638
- * - between: range check
639
- * - contains: substring/element check (uses SurrealQL CONTAINS)
640
- * - Special fields: base, author, timestamp are accessed directly, not via subqueries
641
- *
642
- * All conditions are joined with AND.
643
- *
644
- * @param metadata - Model metadata containing property predicates
645
- * @param where - Where conditions from the query
646
- * @returns WHERE clause string (without the "WHERE" keyword), or empty string if no conditions
647
- *
648
- * @private
649
- */
650
- private static buildSurrealWhereClause;
651
- /**
652
- * Builds the SELECT fields for SurrealQL queries.
653
- *
654
- * @description
655
- * Generates the field list for the SELECT clause, resolving properties and relations
656
- * via subqueries. Each property is fetched with a subquery that finds the link with the
657
- * appropriate predicate and returns its target. Relations are similar but don't use LIMIT 1.
658
- *
659
- * Field types:
660
- * - Properties: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X' LIMIT 1) AS propName`
661
- * - Relations: `(SELECT VALUE target FROM link WHERE source = $parent.base AND predicate = 'X') AS relName`
662
- * - Author/Timestamp: Always included to provide metadata about each instance
663
- *
664
- * If properties or relations arrays are provided, only those fields are included.
665
- * Otherwise, all properties/relations from metadata are included.
666
- *
667
- * @param metadata - Model metadata containing property and relation predicates
668
- * @param properties - Optional array of property names to include (default: all)
669
- * @param relations - Optional array of relation names to include (default: all)
670
- * @returns Comma-separated SELECT field list
671
- *
672
- * @private
673
- */
674
- private static buildSurrealSelectFields;
675
- /**
676
- * Builds the SELECT fields for SurrealQL queries using aggregation functions.
677
- * Compatible with GROUP BY source queries.
678
- *
679
- * @private
680
- */
681
- private static buildSurrealSelectFieldsWithAggregation;
682
- /**
683
- * Formats a value for use in SurrealQL queries.
684
- *
685
- * @description
686
- * Handles different value types:
687
- * - Strings: Wrapped in single quotes with backslash-escaped special characters
688
- * - Numbers/booleans: Converted to string
689
- * - Arrays: Recursively formatted and wrapped in brackets
690
- *
691
- * @param value - The value to format
692
- * @returns Formatted value string ready for SurrealQL
693
- *
694
- * @private
695
- */
696
- private static formatSurrealValue;
697
309
  static instancesFromPrologResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: AllInstancesResult): Promise<ResultsWithTotalCount<T>>;
698
310
  /**
699
311
  * Converts SurrealDB query results to Ad4mModel instances.
@@ -706,11 +318,6 @@ export declare class Ad4mModel {
706
318
  * @internal
707
319
  */
708
320
  static instancesFromSurrealResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, query: Query, result: any[]): Promise<ResultsWithTotalCount<T>>;
709
- /**
710
- * Checks if a value matches a condition (for post-query filtering).
711
- * @private
712
- */
713
- private static matchesCondition;
714
321
  /**
715
322
  * Gets all instances of the model in the perspective that match the query params.
716
323
  *
@@ -911,10 +518,6 @@ export declare class Ad4mModel {
911
518
  * ```
912
519
  */
913
520
  delete(batchId?: string): Promise<void>;
914
- /**
915
- * Options for `Ad4mModel.create()`.
916
- */
917
- static readonly CreateOptions: undefined;
918
521
  /**
919
522
  * Creates and saves a new model instance in one step.
920
523
  *
@@ -1121,411 +724,4 @@ export declare class Ad4mModel {
1121
724
  * @throws Error when namespace cannot be inferred
1122
725
  */
1123
726
  static fromJSONSchema(schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
1124
- /**
1125
- * Determines the namespace for predicates using cascading precedence
1126
- */
1127
- private static determineNamespace;
1128
- /**
1129
- * Determines the predicate for a specific property using cascading precedence
1130
- */
1131
- private static determinePredicate;
1132
- /**
1133
- * Gets property-specific options using cascading precedence
1134
- */
1135
- private static getPropertyOption;
1136
- /**
1137
- * Gets default value for a JSON Schema type
1138
- */
1139
- private static getDefaultValueForType;
1140
- }
1141
- /** Query builder for Ad4mModel queries.
1142
- * Allows building queries with a fluent interface and either running them once
1143
- * or subscribing to updates.
1144
- *
1145
- * @example
1146
- * ```typescript
1147
- * const builder = Recipe.query(perspective)
1148
- * .where({ category: "Dessert" })
1149
- * .order({ rating: "DESC" })
1150
- * .limit(10);
1151
- *
1152
- * // Run once
1153
- * const recipes = await builder.run();
1154
- *
1155
- * // Or subscribe to updates
1156
- * await builder.subscribe(recipes => {
1157
- * console.log("Updated recipes:", recipes);
1158
- * });
1159
- * ```
1160
- */
1161
- export declare class ModelQueryBuilder<T extends Ad4mModel> {
1162
- private perspective;
1163
- private queryParams;
1164
- private modelClassName;
1165
- private ctor;
1166
- private currentSubscription?;
1167
- private useSurrealDBFlag;
1168
- constructor(perspective: PerspectiveProxy, ctor: typeof Ad4mModel, query?: Query);
1169
- /**
1170
- * Disposes of the current subscription if one exists.
1171
- *
1172
- * This method:
1173
- * 1. Stops the keepalive signals to the subscription
1174
- * 2. Unsubscribes from GraphQL subscription updates
1175
- * 3. Notifies the backend to clean up subscription resources
1176
- * 4. Clears the subscription reference
1177
- *
1178
- * You should call this method when you're done with a subscription
1179
- * to prevent memory leaks and ensure proper cleanup.
1180
- */
1181
- dispose(): void;
1182
- /**
1183
- * Adds where conditions to the query.
1184
- *
1185
- * @param conditions - The conditions to filter by
1186
- * @returns The query builder for chaining
1187
- *
1188
- * @example
1189
- * ```typescript
1190
- * .where({
1191
- * category: "Dessert",
1192
- * rating: { gt: 4 },
1193
- * tags: ["vegan", "quick"],
1194
- * published: true
1195
- * })
1196
- * ```
1197
- */
1198
- where(conditions: Where): ModelQueryBuilder<T>;
1199
- /**
1200
- * Sets the order for the query results.
1201
- *
1202
- * @param orderBy - The ordering criteria
1203
- * @returns The query builder for chaining
1204
- *
1205
- * @example
1206
- * ```typescript
1207
- * .order({ createdAt: "DESC" })
1208
- * ```
1209
- */
1210
- order(orderBy: Order): ModelQueryBuilder<T>;
1211
- /**
1212
- * Sets the maximum number of results to return.
1213
- *
1214
- * @param limit - Maximum number of results
1215
- * @returns The query builder for chaining
1216
- *
1217
- * @example
1218
- * ```typescript
1219
- * .limit(10)
1220
- * ```
1221
- */
1222
- limit(limit: number): ModelQueryBuilder<T>;
1223
- /**
1224
- * Sets the number of results to skip.
1225
- *
1226
- * @param offset - Number of results to skip
1227
- * @returns The query builder for chaining
1228
- *
1229
- * @example
1230
- * ```typescript
1231
- * .offset(20) // Skip first 20 results
1232
- * ```
1233
- */
1234
- offset(offset: number): ModelQueryBuilder<T>;
1235
- /**
1236
- * Scopes the query to instances linked from a parent.
1237
- *
1238
- * The predicate is resolved in order of precedence:
1239
- * 1. **Instance only** — the parent's constructor is used as the model
1240
- * class; its relation metadata is scanned for a relation whose
1241
- * `target()` matches the queried model class.
1242
- * 2. **Instance + options with `field`** — direct field-name lookup on
1243
- * the parent model's relation metadata (disambiguates when a parent
1244
- * has multiple relations targeting the same child class).
1245
- * 3. **String id + model class** — same metadata scan (or field lookup if
1246
- * options include `field`).
1247
- * 4. **String id + string predicate** — raw escape hatch, no metadata lookup.
1248
- *
1249
- * Passing a plain string id with no second argument throws because the
1250
- * predicate cannot be resolved without a model class.
1251
- *
1252
- * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance
1253
- * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string
1254
- * @param options - Optional settings: `field` for direct relation-name lookup
1255
- * @returns The query builder for chaining
1256
- *
1257
- * @example
1258
- * ```typescript
1259
- * // Instance — predicate auto-resolved from Cookbook's @HasMany(() => Recipe)
1260
- * Recipe.query(perspective).parent(cookbook).get();
1261
- *
1262
- * // Instance + field — disambiguate when parent has multiple relations to same child
1263
- * Recipe.query(perspective).parent(cookbook, { field: "recipes" }).get();
1264
- *
1265
- * // String id + model class
1266
- * Recipe.query(perspective).parent(cookbookId, Cookbook).get();
1267
- *
1268
- * // String id + model class + field
1269
- * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: "recipes" }).get();
1270
- *
1271
- * // String id + raw predicate (escape hatch)
1272
- * Recipe.query(perspective).parent(cookbookId, "cookbook://recipe").get();
1273
- * ```
1274
- */
1275
- parent(idOrInstance: string | Ad4mModel, modelOrPredicate?: typeof Ad4mModel | string | {
1276
- field: string;
1277
- }, options?: {
1278
- field?: string;
1279
- }): ModelQueryBuilder<T>;
1280
- /**
1281
- * Specifies which properties to include in the results.
1282
- *
1283
- * @param properties - Array of property names to include
1284
- * @returns The query builder for chaining
1285
- *
1286
- * @example
1287
- * ```typescript
1288
- * .properties(["name", "description", "rating"])
1289
- * ```
1290
- */
1291
- properties(properties: string[]): ModelQueryBuilder<T>;
1292
- /**
1293
- * Specifies which relations to eager-load (hydrate into model instances).
1294
- *
1295
- * Without `include`, relation fields contain raw expression URIs (strings).
1296
- * With `include`, the URIs are resolved into fully-hydrated model instances
1297
- * using the `target` class declared in the relation decorator.
1298
- *
1299
- * Supports nested includes for multi-level eager loading.
1300
- *
1301
- * @param map - An IncludeMap describing which relations to hydrate
1302
- * @returns The query builder for chaining
1303
- *
1304
- * @example
1305
- * ```typescript
1306
- * // Hydrate comments one level deep
1307
- * const recipes = await Recipe.query(perspective)
1308
- * .include({ comments: true })
1309
- * .run();
1310
- * // recipe.comments is now Comment[] (model instances), not string[]
1311
- *
1312
- * // Nested: hydrate comments AND each comment's author
1313
- * const recipes = await Recipe.query(perspective)
1314
- * .include({ comments: { author: true } })
1315
- * .run();
1316
- * ```
1317
- */
1318
- include(map: IncludeMap): ModelQueryBuilder<T>;
1319
- overrideModelClassName(className: string): ModelQueryBuilder<T>;
1320
- /**
1321
- * Enables or disables SurrealDB query path.
1322
- *
1323
- * @param enabled - Whether to use SurrealDB (default: true, 10-100x faster) or Prolog (legacy)
1324
- * @returns The query builder for chaining
1325
- *
1326
- * @example
1327
- * ```typescript
1328
- * // Use SurrealDB (default)
1329
- * const recipes = await Recipe.query(perspective)
1330
- * .where({ category: "Dessert" })
1331
- * .useSurrealDB(true)
1332
- * .get();
1333
- *
1334
- * // Use Prolog (legacy)
1335
- * const recipesProlog = await Recipe.query(perspective)
1336
- * .where({ category: "Dessert" })
1337
- * .useSurrealDB(false)
1338
- * .get();
1339
- * ```
1340
- *
1341
- * @remarks
1342
- * Note: Subscriptions (subscribe(), countSubscribe(), paginateSubscribe()) default to SurrealDB live queries
1343
- * if useSurrealDB(true) is set (default).
1344
- */
1345
- useSurrealDB(enabled?: boolean): ModelQueryBuilder<T>;
1346
- /**
1347
- * Executes the query once and returns the results.
1348
- *
1349
- * @returns Array of matching entities
1350
- *
1351
- * @example
1352
- * ```typescript
1353
- * const recipes = await Recipe.query(perspective)
1354
- * .where({ category: "Dessert" })
1355
- * .get();
1356
- * ```
1357
- */
1358
- get(): Promise<T[]>;
1359
- /**
1360
- * Returns the first matching instance, or `null` if none match.
1361
- *
1362
- * Internally sets `limit: 1` and delegates to `get()`.
1363
- *
1364
- * @returns The first matching instance, or `null`
1365
- *
1366
- * @example
1367
- * ```typescript
1368
- * const recipe = await Recipe.query(perspective)
1369
- * .where({ name: "Pasta" })
1370
- * .first();
1371
- * ```
1372
- */
1373
- first(): Promise<T | null>;
1374
- /**
1375
- * Subscribes to the query and receives updates when results change.
1376
- *
1377
- * This method:
1378
- * 1. Creates and initializes a SurrealDB live query subscription (default)
1379
- * 2. Sets up the callback to process future updates
1380
- * 3. Returns the initial results immediately
1381
- *
1382
- * Remember to call dispose() when you're done with the subscription
1383
- * to clean up resources.
1384
- *
1385
- * @param callback - Function to call with updated results
1386
- * @returns Initial results array
1387
- *
1388
- * @example
1389
- * ```typescript
1390
- * const builder = Recipe.query(perspective)
1391
- * .where({ status: "cooking" });
1392
- *
1393
- * const initialRecipes = await builder.subscribe(recipes => {
1394
- * console.log("Updated recipes:", recipes);
1395
- * });
1396
- *
1397
- * // When done with subscription:
1398
- * builder.dispose();
1399
- * ```
1400
- *
1401
- * @remarks
1402
- * By default, this uses SurrealDB live queries for real-time updates.
1403
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1404
- */
1405
- subscribe(callback: (results: T[]) => void): Promise<T[]>;
1406
- /**
1407
- * Gets the total count of matching entities.
1408
- *
1409
- * @returns Total count
1410
- *
1411
- * @example
1412
- * ```typescript
1413
- * const totalDesserts = await Recipe.query(perspective)
1414
- * .where({ category: "Dessert" })
1415
- * .count();
1416
- * ```
1417
- */
1418
- count(): Promise<number>;
1419
- /**
1420
- * Subscribes to count updates for matching entities.
1421
- *
1422
- * This method:
1423
- * 1. Creates and initializes a SurrealDB live query subscription for the count (default)
1424
- * 2. Sets up the callback to process future count updates
1425
- * 3. Returns the initial count immediately
1426
- *
1427
- * Remember to call dispose() when you're done with the subscription
1428
- * to clean up resources.
1429
- *
1430
- * @param callback - Function to call with updated count
1431
- * @returns Initial count
1432
- *
1433
- * @example
1434
- * ```typescript
1435
- * const builder = Recipe.query(perspective)
1436
- * .where({ status: "active" });
1437
- *
1438
- * const initialCount = await builder.countSubscribe(count => {
1439
- * console.log("Active items:", count);
1440
- * });
1441
- *
1442
- * // When done with subscription:
1443
- * builder.dispose();
1444
- * ```
1445
- *
1446
- * @remarks
1447
- * By default, this uses SurrealDB live queries for real-time updates.
1448
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1449
- */
1450
- countSubscribe(callback: (count: number) => void): Promise<number>;
1451
- /**
1452
- * Gets a page of results with pagination metadata.
1453
- *
1454
- * @param pageSize - Number of items per page
1455
- * @param pageNumber - Which page to retrieve (1-based)
1456
- * @returns Paginated results with metadata
1457
- *
1458
- * @example
1459
- * ```typescript
1460
- * const page = await Recipe.query(perspective)
1461
- * .where({ category: "Main" })
1462
- * .paginate(10, 1);
1463
- * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);
1464
- * ```
1465
- */
1466
- paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
1467
- /**
1468
- * Subscribes to paginated results updates.
1469
- *
1470
- * This method:
1471
- * 1. Creates and initializes a SurrealDB live query subscription for the paginated results (default)
1472
- * 2. Sets up the callback to process future page updates
1473
- * 3. Returns the initial page immediately
1474
- *
1475
- * Remember to call dispose() when you're done with the subscription
1476
- * to clean up resources.
1477
- *
1478
- * @param pageSize - Number of items per page
1479
- * @param pageNumber - Which page to retrieve (1-based)
1480
- * @param callback - Function to call with updated pagination results
1481
- * @returns Initial pagination results
1482
- *
1483
- * @example
1484
- * ```typescript
1485
- * const builder = Recipe.query(perspective)
1486
- * .where({ category: "Main" });
1487
- *
1488
- * const initialPage = await builder.paginateSubscribe(10, 1, page => {
1489
- * console.log("Updated page:", page.results);
1490
- * });
1491
- *
1492
- * // When done with subscription:
1493
- * builder.dispose();
1494
- * ```
1495
- *
1496
- * @remarks
1497
- * By default, this uses SurrealDB live queries for real-time updates.
1498
- * Prolog subscriptions remain available via `.useSurrealDB(false)`.
1499
- */
1500
- paginateSubscribe(pageSize: number, pageNumber: number, callback: (results: PaginationResult<T>) => void): Promise<PaginationResult<T>>;
1501
727
  }
1502
- /**
1503
- * Generate Prolog predicate facts from a model class's decorator metadata.
1504
- *
1505
- * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
1506
- * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
1507
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
1508
- *
1509
- * The generated predicates are:
1510
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
1511
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
1512
- * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
1513
- *
1514
- * @example
1515
- * ```typescript
1516
- * import { generatePrologFacts } from '@coasys/ad4m';
1517
- *
1518
- * const facts = generatePrologFacts(Poll);
1519
- * const result = await perspective.infer(\`
1520
- * \${facts}
1521
- * recent_popular_poll(X) :-
1522
- * poll(X),
1523
- * poll_vote_count(X, N), N > 10.
1524
- * \`);
1525
- * ```
1526
- *
1527
- * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
1528
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
1529
- */
1530
- export declare function generatePrologFacts(ModelClass: typeof Ad4mModel): string;
1531
- export {};