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

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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6046
  3. package/lib/index.js +5977 -6040
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2799
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3249
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -0,0 +1,176 @@
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
+ }
@@ -0,0 +1 @@
1
+ export { generatePrologFacts } from './generatePrologFacts';
@@ -0,0 +1,173 @@
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
+ }
@@ -0,0 +1,181 @@
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
+ }