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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6872 -5886
  3. package/lib/index.js +6868 -5874
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3737 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4361 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -1,176 +0,0 @@
1
- import type { Ad4mModel } from "../Ad4mModel";
2
- import type {
3
- ModelMetadata,
4
- PropertyMetadata,
5
- RelationMetadata,
6
- } from "../Ad4mModel";
7
-
8
- type ModelClass = typeof Ad4mModel & {
9
- getModelMetadata(): ModelMetadata;
10
- };
11
-
12
- /**
13
- * Convert a camelCase or PascalCase identifier to snake_case.
14
- * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
15
- */
16
- function toSnakeCase(str: string): string {
17
- return str
18
- .replace(/([A-Z])/g, "_$1")
19
- .toLowerCase()
20
- .replace(/^_/, "");
21
- }
22
-
23
- /**
24
- * Build the instance recognizer clause for a model.
25
- *
26
- * Uses @Flag properties (fixed-value predicates) as the primary recognition
27
- * strategy, since they uniquely identify the type in the graph. Falls back to
28
- * required properties if no flags are present.
29
- *
30
- * Examples:
31
- * poll(X) :- triple(X, 'flux://entry_type', 'flux://has_poll').
32
- * note(X) :- triple(X, 'ad4m://title', _).
33
- */
34
- function buildInstanceClause(
35
- predicateName: string,
36
- metadata: ModelMetadata,
37
- ): string | null {
38
- const props = metadata.properties;
39
-
40
- // Collect flags first — these are the strongest recognizers
41
- const flags = Object.values(props).filter(
42
- (p) => p.flag && p.predicate && p.initial,
43
- );
44
- if (flags.length > 0) {
45
- const conditions = flags
46
- .map((p) => `triple(X, '${p.predicate}', '${p.initial}')`)
47
- .join(",\n ");
48
- return `${predicateName}(X) :-\n ${conditions}.`;
49
- }
50
-
51
- // Fallback: required non-flag properties
52
- const required = Object.values(props).filter(
53
- (p) => p.required && p.predicate && !p.flag,
54
- );
55
- if (required.length > 0) {
56
- const conditions = required
57
- .map((p) => `triple(X, '${p.predicate}', _)`)
58
- .join(",\n ");
59
- return `${predicateName}(X) :-\n ${conditions}.`;
60
- }
61
-
62
- return null;
63
- }
64
-
65
- /**
66
- * Build a property getter clause for a single property.
67
- *
68
- * Example:
69
- * poll_title(X, Value) :- triple(X, 'rdf://title', Value).
70
- */
71
- function buildPropertyClause(
72
- modelPredicateName: string,
73
- prop: PropertyMetadata,
74
- ): string | null {
75
- // Flags are handled by the instance clause, not individual getters
76
- if (prop.flag) return null;
77
- // No predicate = no clause
78
- if (!prop.predicate) return null;
79
-
80
- const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
81
- return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
82
- }
83
-
84
- /**
85
- * Build a collection getter clause.
86
- *
87
- * Forward relations (@HasMany / @HasOne):
88
- * poll_entries(X, Values) :- findall(V, triple(X, 'flux://entry', V), Values).
89
- *
90
- * Reverse relations (@BelongsToMany / @BelongsToOne):
91
- * The link points TO this instance (OtherNode → predicate → ThisNode), so
92
- * the subject and object are swapped:
93
- * test_tag_posts(X, Values) :- findall(V, triple(V, 'test://has_tag', X), Values).
94
- */
95
- function buildCollectionClause(
96
- modelPredicateName: string,
97
- coll: RelationMetadata,
98
- ): string | null {
99
- if (!coll.predicate) return null;
100
-
101
- const clauseName = `${modelPredicateName}_${toSnakeCase(coll.name)}`;
102
- if (coll.direction === "reverse") {
103
- // Reverse traversal: find nodes whose outgoing predicate link points to X
104
- return `${clauseName}(X, Values) :- findall(V, triple(V, '${coll.predicate}', X), Values).`;
105
- }
106
- return `${clauseName}(X, Values) :- findall(V, triple(X, '${coll.predicate}', V), Values).`;
107
- }
108
-
109
- /**
110
- * Generate Prolog predicate facts from a model class's SHACL metadata.
111
- *
112
- * Given a model class decorated with `@ModelOptions` (and its `@Flag`,
113
- * `@Property`, `@Collection` decorators), this function emits a string of
114
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
115
- *
116
- * The generated predicates are:
117
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
118
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
119
- * - **Collection getters** — `modelName_collName(X, Values)` — one per collection
120
- *
121
- * @example
122
- * ```typescript
123
- * import { generatePrologFacts } from '@coasys/ad4m/model/prolog';
124
- *
125
- * const facts = generatePrologFacts(Poll);
126
- * const result = await perspective.infer(`
127
- * ${facts}
128
- * recent_popular_poll(X) :-
129
- * poll(X),
130
- * poll_vote_count(X, N), N > 10,
131
- * poll_created_at(X, T), T > ${yesterday}.
132
- * `);
133
- * ```
134
- *
135
- * @param ModelClass - A class decorated with `@ModelOptions` that extends `Ad4mModel`
136
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
137
- */
138
- export function generatePrologFacts(ModelClass: ModelClass): string {
139
- const metadata = ModelClass.getModelMetadata();
140
- const predicateName = toSnakeCase(metadata.className);
141
- const lines: string[] = [];
142
-
143
- lines.push(`% ${metadata.className} — generated Prolog facts`);
144
-
145
- // Instance recognizer
146
- const instanceClause = buildInstanceClause(predicateName, metadata);
147
- if (instanceClause) {
148
- lines.push("");
149
- lines.push(`% Instance recognizer`);
150
- lines.push(instanceClause);
151
- }
152
-
153
- // Property getters
154
- const propClauses = Object.values(metadata.properties)
155
- .map((p) => buildPropertyClause(predicateName, p))
156
- .filter((c): c is string => c !== null);
157
-
158
- if (propClauses.length > 0) {
159
- lines.push("");
160
- lines.push(`% Field getters`);
161
- lines.push(...propClauses);
162
- }
163
-
164
- // Relation getters
165
- const collClauses = Object.values(metadata.relations)
166
- .map((c) => buildCollectionClause(predicateName, c))
167
- .filter((c): c is string => c !== null);
168
-
169
- if (collClauses.length > 0) {
170
- lines.push("");
171
- lines.push(`% Relation getters`);
172
- lines.push(...collClauses);
173
- }
174
-
175
- return lines.join("\n");
176
- }
@@ -1 +0,0 @@
1
- export { generatePrologFacts } from './generatePrologFacts';
@@ -1,173 +0,0 @@
1
- /**
2
- * Fluent query builder for Ad4mModel.
3
- *
4
- * Extracted from Ad4mModel.ts. The class holds a `Query` object and delegates
5
- * all execution to `Ad4mModel` static methods via the `ctor` constructor
6
- * reference, so there is no circular import (this module imports from the
7
- * Ad4mModel module, but Ad4mModel does not import from here — it re-exports
8
- * ModelQueryBuilder from its own file for backward compatibility).
9
- */
10
-
11
- import { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
12
- import {
13
- Order,
14
- PaginationResult,
15
- Query,
16
- Where,
17
- IncludeMap,
18
- SubscribeOptions,
19
- Subscription,
20
- } from "../types";
21
- import { createSubscription } from "../subscription";
22
-
23
- // Forward-reference type only — avoids importing the full Ad4mModel
24
- // module at the class level.
25
- export type Ad4mModelCtor<T> = typeof import("../Ad4mModel").Ad4mModel &
26
- (new (...args: any[]) => T);
27
-
28
- /**
29
- * Fluent builder for Ad4mModel queries.
30
- *
31
- * Create via `MyModel.query(perspective)`:
32
- * ```typescript
33
- * const posts = await Post.query(perspective)
34
- * .where({ published: true })
35
- * .order({ createdAt: "DESC" })
36
- * .limit(10)
37
- * .get();
38
- * ```
39
- */
40
- export class ModelQueryBuilder<T extends import("../Ad4mModel").Ad4mModel> {
41
- private perspective: PerspectiveProxy;
42
- private queryParams: Query = {};
43
- private modelClassName: string | null = null;
44
- private ctor: Ad4mModelCtor<T>;
45
-
46
- constructor(
47
- perspective: PerspectiveProxy,
48
- ctor: Ad4mModelCtor<T>,
49
- query?: Query,
50
- ) {
51
- this.perspective = perspective;
52
- this.ctor = ctor;
53
- if (query) this.queryParams = query;
54
- }
55
-
56
- where(conditions: Where): ModelQueryBuilder<T> {
57
- this.queryParams.where = conditions;
58
- return this;
59
- }
60
-
61
- order(orderBy: Order): ModelQueryBuilder<T> {
62
- this.queryParams.order = orderBy;
63
- return this;
64
- }
65
-
66
- limit(limit: number): ModelQueryBuilder<T> {
67
- this.queryParams.limit = limit;
68
- return this;
69
- }
70
-
71
- offset(offset: number): ModelQueryBuilder<T> {
72
- this.queryParams.offset = offset;
73
- return this;
74
- }
75
-
76
- properties(properties: string[]): ModelQueryBuilder<T> {
77
- this.queryParams.properties = properties;
78
- return this;
79
- }
80
-
81
- /**
82
- * Eagerly load specific relations as full model instances.
83
- *
84
- * Key = relation field name on the model.
85
- * Value = `true` (all instances) or a `Query` to filter/order/limit the nested set.
86
- *
87
- * @example
88
- * ```typescript
89
- * Recipe.query(perspective)
90
- * .include({
91
- * comments: true,
92
- * tags: { where: { active: true }, limit: 5 },
93
- * })
94
- * .get();
95
- * ```
96
- */
97
- include(map: IncludeMap): ModelQueryBuilder<T> {
98
- this.queryParams.include = map;
99
- return this;
100
- }
101
-
102
- overrideModelClassName(className: string): ModelQueryBuilder<T> {
103
- this.modelClassName = className;
104
- return this;
105
- }
106
-
107
- /** Executes the query and returns all matching instances. */
108
- async get(): Promise<T[]> {
109
- return this.ctor.findAll(this.perspective, this.queryParams) as Promise<
110
- T[]
111
- >;
112
- }
113
-
114
- /** Returns the first matching instance, or `null` if none found. */
115
- async first(): Promise<T | null> {
116
- return this.ctor.findOne(
117
- this.perspective,
118
- this.queryParams,
119
- ) as Promise<T | null>;
120
- }
121
-
122
- /** Returns the total count of matching entities. */
123
- async count(): Promise<number> {
124
- return this.ctor.count(this.perspective, this.queryParams);
125
- }
126
-
127
- /** Returns a single page of results with pagination metadata. */
128
- async paginate(
129
- pageSize: number,
130
- pageNumber: number,
131
- ): Promise<PaginationResult<T>> {
132
- return this.ctor.paginate(
133
- this.perspective,
134
- pageSize,
135
- pageNumber,
136
- this.queryParams,
137
- ) as Promise<PaginationResult<T>>;
138
- }
139
-
140
- /**
141
- * Terminal: creates a live subscription using the query parameters accumulated
142
- * so far. Fires `callback` immediately with current results, then on every
143
- * relevant link change.
144
- *
145
- * Pass additional delivery options (`debounce`, `onError`) in `deliveryOpts`.
146
- * Call `sub.unsubscribe()` to detach.
147
- *
148
- * @example
149
- * ```typescript
150
- * const sub = Post.query(perspective)
151
- * .where({ published: true })
152
- * .order({ createdAt: "DESC" })
153
- * .live((posts) => setPosts(posts), { debounce: 300 });
154
- *
155
- * // cleanup:
156
- * sub.unsubscribe();
157
- * ```
158
- */
159
- live(
160
- callback: (results: T[]) => void,
161
- deliveryOpts?: Pick<SubscribeOptions, "debounce" | "onError">,
162
- ): Subscription {
163
- const options: SubscribeOptions = { ...this.queryParams, ...deliveryOpts };
164
- return createSubscription<T>(
165
- (p, q) => this.ctor.findAll(p, q ?? {}),
166
- () => this.ctor.getModelMetadata(),
167
- this.perspective,
168
- options,
169
- callback,
170
- this.ctor as any,
171
- );
172
- }
173
- }
@@ -1,181 +0,0 @@
1
- /**
2
- * Single-instance hydration pipeline for Ad4mModel.
3
- *
4
- * Extracted from Ad4mModel.getData() (Phase 3a Part 5).
5
- *
6
- * `fetchInstanceData()` queries SurrealDB for all links belonging to one
7
- * instance and populates the instance in-place:
8
- * 1. Forward-link query → shared `hydrateInstanceFromLinks`
9
- * 2. relatedModel eager hydration via `_findAllInternal`
10
- * 3. Reverse-relation batch query
11
- * 4. Custom SurrealQL getters (`evaluateCustomGetters`)
12
- */
13
-
14
- import type { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
15
- import type { ModelMetadata, IncludeMap, Query } from "../types";
16
- import { formatSurrealValue } from "./surrealCompiler";
17
- import { hydrateInstanceFromLinks, evaluateCustomGetters } from "./hydration";
18
- import { captureSnapshot } from "./snapshot";
19
- import { _findAllInternal } from "./operations";
20
-
21
- /**
22
- * Hydrates `instance` in-place from SurrealDB and returns it.
23
- *
24
- * @param instance - The Ad4mModel instance to populate
25
- * @param perspective - Perspective that owns the instance
26
- * @param id - The instance's base expression URI
27
- * @param metadata - Pre-resolved model metadata (from `getModelMetadata()`)
28
- * @param include - Optional eager-load map
29
- */
30
- export async function fetchInstanceData(
31
- instance: any,
32
- perspective: PerspectiveProxy,
33
- id: string,
34
- metadata: ModelMetadata,
35
- include?: IncludeMap,
36
- ): Promise<any> {
37
- try {
38
- const safeBase = formatSurrealValue(id);
39
-
40
- // ── 1. Forward links ────────────────────────────────────────────────────
41
- const links = await perspective.querySurrealDB(`
42
- SELECT id, predicate, out.uri AS target, author, timestamp
43
- FROM link
44
- WHERE in.uri = ${safeBase}
45
- ORDER BY timestamp ASC
46
- `);
47
-
48
- if (links && links.length > 0) {
49
- // ── 2. Shared hydration: properties + forward relations + timestamps ──
50
- await hydrateInstanceFromLinks(instance, links, metadata, perspective);
51
-
52
- // ── 2. relatedModel eager hydration ──────────────────────────────────
53
- const forwardRelations = Object.entries(metadata.relations).filter(
54
- ([, m]: [string, any]) => !m.getter && m.direction !== "reverse",
55
- );
56
-
57
- for (const [relationName, relationMeta] of forwardRelations) {
58
- const current = instance[relationName];
59
- let values: string[] = Array.isArray(current)
60
- ? [...current]
61
- : current != null
62
- ? [current as string]
63
- : [];
64
-
65
- // relatedModel: eager hydration — only when caller asked for it via include
66
- const includeEntry = include?.[relationName];
67
- if (
68
- includeEntry !== undefined &&
69
- (relationMeta as any).relatedModel &&
70
- values.length > 0
71
- ) {
72
- try {
73
- const RelatedModel = (relationMeta as any).relatedModel() as any;
74
- const subQuery: Query =
75
- includeEntry === true
76
- ? { where: { id: values } }
77
- : {
78
- ...includeEntry,
79
- where: { id: values, ...(includeEntry as Query).where },
80
- };
81
- const hydrated = await _findAllInternal(
82
- RelatedModel,
83
- perspective,
84
- subQuery,
85
- false,
86
- );
87
- instance[relationName] =
88
- (relationMeta as any).maxCount === 1
89
- ? (hydrated[0] ?? null)
90
- : hydrated;
91
- } catch (e) {
92
- console.warn(`Failed to hydrate ${relationName}:`, e);
93
- instance[relationName] =
94
- (relationMeta as any).maxCount === 1
95
- ? (values[0] ?? null)
96
- : values;
97
- }
98
- } else {
99
- instance[relationName] =
100
- (relationMeta as any).maxCount === 1 ? (values[0] ?? null) : values;
101
- }
102
- }
103
- }
104
-
105
- // ── 3. Reverse relations ────────────────────────────────────────────────
106
- const reverseRelations = Object.entries(metadata.relations).filter(
107
- ([, m]: [string, any]) => !m.getter && m.direction === "reverse",
108
- );
109
- if (reverseRelations.length > 0) {
110
- let reverseLinks: any[] = [];
111
- try {
112
- reverseLinks =
113
- (await perspective.querySurrealDB(`
114
- SELECT in.uri AS source, predicate, id, author, timestamp
115
- FROM link
116
- WHERE out.uri = ${safeBase}
117
- ORDER BY timestamp ASC
118
- `)) ?? [];
119
- } catch {
120
- // leave empty — instance just won't have reverse relation data
121
- }
122
-
123
- for (const [relationName, relationMeta] of reverseRelations) {
124
- const matching = reverseLinks.filter(
125
- (l: any) => l.predicate === (relationMeta as any).predicate,
126
- );
127
- const values = matching.map((l: any) => l.source);
128
-
129
- const includeEntry = include?.[relationName];
130
- if (
131
- includeEntry !== undefined &&
132
- (relationMeta as any).relatedModel &&
133
- values.length > 0
134
- ) {
135
- try {
136
- const RelatedModel = (relationMeta as any).relatedModel() as any;
137
- const subQuery: Query =
138
- includeEntry === true
139
- ? { where: { id: values } }
140
- : {
141
- ...includeEntry,
142
- where: { id: values, ...(includeEntry as Query).where },
143
- };
144
- const hydrated = await _findAllInternal(
145
- RelatedModel,
146
- perspective,
147
- subQuery,
148
- false,
149
- );
150
- instance[relationName] =
151
- (relationMeta as any).maxCount === 1
152
- ? (hydrated[0] ?? null)
153
- : hydrated;
154
- } catch (e) {
155
- instance[relationName] =
156
- (relationMeta as any).maxCount === 1
157
- ? (values[0] ?? null)
158
- : values;
159
- }
160
- } else {
161
- instance[relationName] =
162
- (relationMeta as any).maxCount === 1 ? (values[0] ?? null) : values;
163
- }
164
- }
165
- }
166
-
167
- // ── 4. Custom SurrealQL getters ─────────────────────────────────────────
168
- await evaluateCustomGetters(instance, perspective, metadata);
169
-
170
- // ── 5. Snapshot capture — baseline for dirty tracking on next save() ────
171
- const schemaKeys = [
172
- ...Object.keys(metadata.properties),
173
- ...Object.keys(metadata.relations),
174
- ];
175
- captureSnapshot(instance, schemaKeys);
176
- } catch (e) {
177
- console.error(`SurrealDB getData failed for ${id}:`, e);
178
- }
179
-
180
- return instance;
181
- }