@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
@@ -0,0 +1,292 @@
1
+ /**
2
+ * SHACL shape generation for AD4M model classes.
3
+ *
4
+ * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)
5
+ * from a model's property and relation metadata. The heavy lifting used
6
+ * to live inside the `@Model` decorator closure — it is extracted here so
7
+ * decorators.ts stays focused on decorator registration logic.
8
+ */
9
+ import { SHACLShape } from "../shacl/SHACLShape";
10
+ import type { SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
11
+ import { escapeSurrealString } from "../utils";
12
+ import { compileWhereClause } from "./surreal-utils";
13
+ import { propertyNameToSetterName } from "./util";
14
+ import type { PropertyMetadataEntry, RelationMetadataEntry, Ad4mModelLike } from "./decorators";
15
+
16
+ /** Signature for the conformance-filter builder injected by the caller. */
17
+ export type ConformanceFilterFn = (
18
+ relationPredicate: string,
19
+ targetClass: Ad4mModelLike,
20
+ ) => { getter: string; conformanceConditions: ConformanceCondition[] } | undefined;
21
+
22
+ /**
23
+ * Build a SHACL shape for a model class.
24
+ *
25
+ * @param subjectName - The model's registered name (from `@Model({ name })`)
26
+ * @param target - The class constructor (used for prototype access,
27
+ * inheritance chain, and relation target resolution)
28
+ * @param properties - Merged property metadata (from `getPropertiesMetadata`)
29
+ * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)
30
+ * @param conformanceFilterFn - Injected conformance-filter builder
31
+ * (avoids circular dependency back into decorators.ts)
32
+ */
33
+ export function buildSHACL(
34
+ subjectName: string,
35
+ target: any,
36
+ properties: Record<string, PropertyMetadataEntry>,
37
+ allRelationsMeta: Record<string, RelationMetadataEntry>,
38
+ conformanceFilterFn: ConformanceFilterFn,
39
+ ): { shape: SHACLShape; name: string } {
40
+ const obj = target.prototype;
41
+
42
+ // ── Determine namespace from first property or relation ─────────────
43
+ let namespace = "ad4m://";
44
+ const relations = Object.fromEntries(
45
+ Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
46
+ );
47
+
48
+ // Try properties first
49
+ if (Object.keys(properties).length > 0) {
50
+ const firstProp = properties[Object.keys(properties)[0]];
51
+ if (firstProp.through) {
52
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
53
+ if (match) {
54
+ namespace = match[1];
55
+ }
56
+ }
57
+ }
58
+ // Fall back to relations if no properties
59
+ else if (Object.keys(relations).length > 0) {
60
+ const firstRel = relations[Object.keys(relations)[0]];
61
+ if (firstRel.predicate) {
62
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
63
+ if (match) {
64
+ namespace = match[1];
65
+ }
66
+ }
67
+ }
68
+
69
+ // ── Create SHACL shape ──────────────────────────────────────────────
70
+ const shapeUri = `${namespace}${subjectName}Shape`;
71
+ const targetClass = `${namespace}${subjectName}`;
72
+ const shape = new SHACLShape(shapeUri, targetClass);
73
+
74
+ // Detect @Model inheritance — if the parent class also has
75
+ // generateSHACL it is itself a @Model and we reference its shape
76
+ // via sh:node so SHACL validators can walk the hierarchy.
77
+ const parentCtor = Object.getPrototypeOf(target);
78
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
79
+ const parentSHACL = parentCtor.generateSHACL();
80
+ if (parentSHACL?.shape?.nodeShapeUri) {
81
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
82
+ }
83
+ }
84
+
85
+ // ── Constructor / Destructor actions ────────────────────────────────
86
+ let constructorActions: any[] = [];
87
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
88
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
89
+ }
90
+
91
+ let destructorActions: any[] = [];
92
+
93
+ // ── Convert properties to SHACL property shapes ────────────────────
94
+ for (const propName in properties) {
95
+ const propMeta = properties[propName];
96
+
97
+ if (!propMeta.through) continue; // Skip properties without predicates
98
+
99
+ const propShape: SHACLPropertyShape = {
100
+ name: propName,
101
+ path: propMeta.through,
102
+ };
103
+
104
+ // Determine datatype from initial value or resolveLanguage
105
+ if (propMeta.resolveLanguage === "literal") {
106
+ propShape.datatype = "xsd://string";
107
+ } else if (propMeta.initial) {
108
+ const initialType = typeof obj[propName];
109
+ if (initialType === "number") {
110
+ propShape.datatype = "xsd://integer";
111
+ } else if (initialType === "boolean") {
112
+ propShape.datatype = "xsd://boolean";
113
+ } else if (initialType === "string") {
114
+ propShape.datatype = "xsd://string";
115
+ }
116
+ }
117
+
118
+ // Cardinality constraints
119
+ if (propMeta.required) {
120
+ propShape.minCount = 1;
121
+ }
122
+
123
+ // Single-valued properties get maxCount 1
124
+ propShape.maxCount = 1;
125
+
126
+ // Flag properties have fixed value
127
+ if (propMeta.flag && propMeta.initial) {
128
+ propShape.hasValue = propMeta.initial;
129
+ }
130
+
131
+ // AD4M-specific metadata
132
+ if (propMeta.local !== undefined) {
133
+ propShape.local = propMeta.local;
134
+ }
135
+
136
+ if (propMeta.writable !== undefined) {
137
+ propShape.writable = propMeta.writable;
138
+ }
139
+
140
+ if (propMeta.resolveLanguage) {
141
+ propShape.resolveLanguage = propMeta.resolveLanguage;
142
+ }
143
+
144
+ // ── Setter actions ──────────────────────────────────────────────
145
+ if (propMeta.prologSetter) {
146
+ console.warn(
147
+ `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
148
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
149
+ );
150
+ } else if (propMeta.writable && propMeta.through) {
151
+ let setter = obj[propertyNameToSetterName(propName)];
152
+ if (typeof setter === "function") {
153
+ propShape.setter = [{
154
+ action: "setSingleTarget",
155
+ source: "this",
156
+ predicate: propMeta.through,
157
+ target: "value",
158
+ ...(propMeta.local && { local: true })
159
+ }];
160
+ }
161
+ }
162
+
163
+ // ── Constructor / Destructor entries ────────────────────────────
164
+ const effectiveInitial = propMeta.initial
165
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
166
+ ? "literal://string:" : undefined);
167
+
168
+ if (effectiveInitial) {
169
+ constructorActions.push({
170
+ action: "addLink",
171
+ source: "this",
172
+ predicate: propMeta.through,
173
+ target: effectiveInitial,
174
+ });
175
+
176
+ destructorActions.push({
177
+ action: "removeLink",
178
+ source: "this",
179
+ predicate: propMeta.through,
180
+ target: "*",
181
+ });
182
+ }
183
+
184
+ shape.addProperty(propShape);
185
+ }
186
+
187
+ // ── Convert relations to SHACL property shapes ─────────────────────
188
+ for (const relName in relations) {
189
+ const relMeta = relations[relName];
190
+
191
+ if (!relMeta.predicate) continue;
192
+
193
+ const relShape: SHACLPropertyShape = {
194
+ name: relName,
195
+ path: relMeta.predicate,
196
+ };
197
+
198
+ // Relations typically contain IRIs
199
+ relShape.nodeKind = 'IRI';
200
+
201
+ // AD4M-specific metadata
202
+ if (relMeta.local !== undefined) {
203
+ relShape.local = relMeta.local;
204
+ }
205
+
206
+ // Adder action
207
+ relShape.adder = [{
208
+ action: "addLink",
209
+ source: "this",
210
+ predicate: relMeta.predicate,
211
+ target: "value",
212
+ ...(relMeta.local && { local: true })
213
+ }];
214
+
215
+ // Remover action
216
+ relShape.remover = [{
217
+ action: "removeLink",
218
+ source: "this",
219
+ predicate: relMeta.predicate,
220
+ target: "value",
221
+ ...(relMeta.local && { local: true })
222
+ }];
223
+
224
+ // ── Build Getter (conformance filter) ───────────────────────────
225
+ // Priority chain:
226
+ // 1. Explicit getter string → use verbatim
227
+ // 2. `where` clause → compile DSL to SurrealQL getter
228
+ // 3. target + filter !== false → auto-derive from shape
229
+ if (relMeta.getter) {
230
+ relShape.getter = relMeta.getter;
231
+ } else if (relMeta.where) {
232
+ try {
233
+ const TargetClass = relMeta.target?.();
234
+ const targetMetadata = TargetClass
235
+ ? (TargetClass as any).getModelMetadata?.() ?? null
236
+ : null;
237
+
238
+ const conditions = compileWhereClause(
239
+ relMeta.where,
240
+ targetMetadata,
241
+ );
242
+
243
+ if (conditions.length > 0) {
244
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
245
+ relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
246
+ }
247
+ } catch (e) {
248
+ // Target metadata may not be available yet
249
+ }
250
+ } else if (relMeta.target && relMeta.filter !== false) {
251
+ try {
252
+ const TargetClass = relMeta.target();
253
+ const filter = conformanceFilterFn(relMeta.predicate, TargetClass);
254
+ if (filter) {
255
+ relShape.getter = filter.getter;
256
+ relShape.conformanceConditions = filter.conformanceConditions;
257
+ }
258
+ } catch (e) {
259
+ // Target class may not be available yet — getter will be
260
+ // absent and runtime will fall back to unfiltered get_links
261
+ }
262
+ }
263
+
264
+ // ── sh:class — target shape reference ───────────────────────────
265
+ if (relMeta.target) {
266
+ try {
267
+ const TargetClass = relMeta.target();
268
+ const targetSHACL = (TargetClass as any).generateSHACL?.();
269
+ if (targetSHACL?.shape?.nodeShapeUri) {
270
+ relShape.class = targetSHACL.shape.nodeShapeUri;
271
+ }
272
+ } catch (e) {
273
+ // Target class may not be available yet
274
+ }
275
+ }
276
+
277
+ shape.addProperty(relShape);
278
+ }
279
+
280
+ // Always set constructor and destructor actions on the shape, even
281
+ // when empty. An empty array serialises to `literal://string:[]`
282
+ // which the Rust executor parses as a valid (no-op) command list,
283
+ // avoiding "No SHACL constructor found" errors for models whose
284
+ // properties are all optional and have no @Flag.
285
+ shape.setConstructorActions(constructorActions);
286
+ shape.setDestructorActions(destructorActions);
287
+
288
+ return {
289
+ shape,
290
+ name: subjectName
291
+ };
292
+ }
@@ -5,7 +5,7 @@
5
5
  * the compile-time SHACL generator (`decorators.ts`).
6
6
  */
7
7
 
8
- import type { WhereCondition, Where, ModelMetadata } from "./Ad4mModel";
8
+ import type { WhereCondition, Where, ModelMetadata } from "./types";
9
9
  import { escapeSurrealString } from "../utils";
10
10
 
11
11
  /**
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Shared type definitions for the Ad4mModel system.
3
+ *
4
+ * Extracted into a standalone module so that utility files
5
+ * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
6
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
7
+ */
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // Forward type-only reference to Ad4mModel (no runtime circular dependency)
11
+ // ---------------------------------------------------------------------------
12
+ import type { Ad4mModel } from "./Ad4mModel";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Query DSL types
16
+ // ---------------------------------------------------------------------------
17
+
18
+ export type WhereOps = {
19
+ not: string | number | boolean | string[] | number[];
20
+ between: [number, number];
21
+ lt: number; // less than
22
+ lte: number; // less than or equal to
23
+ gt: number; // greater than
24
+ gte: number; // greater than or equal to
25
+ contains: string | number; // substring/element check
26
+ };
27
+ export type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
28
+ export type Where = { [propertyName: string]: WhereCondition };
29
+ export type Order = { [propertyName: string]: "ASC" | "DESC" };
30
+
31
+ /**
32
+ * Discriminated union for parent-scoped queries.
33
+ *
34
+ * **Model form** (preferred) — predicate auto-resolved from the parent model's
35
+ * relation metadata. Use `field` to disambiguate when the parent has multiple
36
+ * relations targeting the same child class.
37
+ *
38
+ * **Raw form** — explicit predicate string, no metadata lookup.
39
+ */
40
+ export type ParentScope =
41
+ | { model: typeof Ad4mModel; id: string; field?: string }
42
+ | { id: string; predicate: string };
43
+
44
+ /**
45
+ * Describes which relations to eager-load when querying.
46
+ *
47
+ * Each value is either:
48
+ * - `true` — hydrate the relation one level deep
49
+ * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * // One level deep
54
+ * { comments: true }
55
+ *
56
+ * // Sub-query: only the 5 most-recent comments
57
+ * { comments: { order: { createdAt: 'DESC' }, limit: 5 } }
58
+ *
59
+ * // Nested eager-load
60
+ * { comments: { include: { author: true } } }
61
+ * ```
62
+ */
63
+ export interface IncludeMap {
64
+ [relation: string]: boolean | RelationSubQuery;
65
+ }
66
+
67
+ export type Query = {
68
+ /** Filter to instances that are the target of a link from a given parent. */
69
+ parent?: ParentScope;
70
+ properties?: string[];
71
+ include?: IncludeMap;
72
+ where?: Where;
73
+ order?: Order;
74
+ offset?: number;
75
+ limit?: number;
76
+ count?: boolean;
77
+ };
78
+
79
+ /**
80
+ * Sub-query options for a specific relation inside an `IncludeMap`.
81
+ *
82
+ * Equivalent to `Query` without top-level scoping (`parent`) or `count`,
83
+ * since the result set is already constrained to the linked relation.
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
88
+ * ```
89
+ */
90
+ export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
91
+
92
+ /**
93
+ * Options accepted by the instance `get()` method.
94
+ *
95
+ * A subset of `Query` — only hydration controls apply to a single known instance.
96
+ */
97
+ export type GetOptions = Pick<Query, 'include' | 'properties'>;
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Result types
101
+ // ---------------------------------------------------------------------------
102
+
103
+ export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
104
+ export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
105
+ export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Internal value transport
109
+ // ---------------------------------------------------------------------------
110
+
111
+ export type ValueTuple = [name: string, value: any, resolve?: boolean];
112
+
113
+ // ---------------------------------------------------------------------------
114
+ // Model metadata interfaces
115
+ // ---------------------------------------------------------------------------
116
+
117
+ /**
118
+ * Metadata for a single property extracted from decorators.
119
+ */
120
+ export interface PropertyMetadata {
121
+ /** The property name */
122
+ name: string;
123
+ /** The predicate URI (through value) */
124
+ predicate: string;
125
+ /** Whether the property is required */
126
+ required: boolean;
127
+ /** Whether the property is read-only */
128
+ readOnly: boolean;
129
+ /** Initial value if specified */
130
+ initial?: string;
131
+ /** Language for resolution (e.g., "literal") */
132
+ resolveLanguage?: string;
133
+ /** Custom Prolog getter code */
134
+ prologGetter?: string;
135
+ /** Custom Prolog setter code */
136
+ prologSetter?: string;
137
+ /** Custom SurrealQL getter code */
138
+ getter?: string;
139
+ /** Whether stored locally only */
140
+ local?: boolean;
141
+ /** Transform function */
142
+ transform?: (value: any) => any;
143
+ /** Whether this is a flag property */
144
+ flag?: boolean;
145
+ }
146
+
147
+ /**
148
+ * Metadata for a single relation extracted from decorators.
149
+ */
150
+ export interface RelationMetadata {
151
+ /** The relation name */
152
+ name: string;
153
+ /** The predicate URI (through value) */
154
+ predicate: string;
155
+ /** Custom SurrealQL getter code */
156
+ getter?: string;
157
+ /** Whether stored locally only */
158
+ local?: boolean;
159
+ /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
160
+ direction?: 'forward' | 'reverse';
161
+ /** Target model class thunk for hydration and type filtering */
162
+ target?: () => any;
163
+ /**
164
+ * Whether to auto-generate a conformance filter when `target` is set.
165
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
166
+ */
167
+ filter?: boolean;
168
+ /** Where clause for relation filtering (query DSL) */
169
+ where?: Where;
170
+ }
171
+
172
+ /**
173
+ * Complete model metadata extracted from decorators.
174
+ */
175
+ export interface ModelMetadata {
176
+ /** The model class name from @Model */
177
+ className: string;
178
+ /** Map of property name to metadata */
179
+ properties: Record<string, PropertyMetadata>;
180
+ /** Map of relation name to metadata */
181
+ relations: Record<string, RelationMetadata>;
182
+ }
package/src/model/util.ts CHANGED
@@ -7,19 +7,6 @@ export function propertyNameToSetterName(property: string): string {
7
7
  return `set${capitalize(property)}`
8
8
  }
9
9
 
10
- // e.g. "setName" -> "name"
11
- export function setterNameToPropertyName(setter: string): string {
12
- return setter.replace("set", "").replace(/^[A-Z]/, (m) => m.toLowerCase())
13
- }
14
-
15
- export function singularToPlural(singular: string): string {
16
- if(singular.endsWith("y")) {
17
- return singular.slice(0, -1) + "ies"
18
- } else {
19
- return singular + "s"
20
- }
21
- }
22
-
23
10
  export function pluralToSingular(plural: string): string {
24
11
  if(plural.endsWith("ies")) {
25
12
  return plural.slice(0, -3) + "y"
@@ -35,40 +22,30 @@ export function relationToAdderName(relation: string): string {
35
22
  return `add${capitalize(pluralToSingular(relation))}`
36
23
  }
37
24
 
38
- // e.g. "addComments" -> "comments"
39
- export function relationAdderToName(adderName: string): string {
40
- // Extract the relation name after "add" and lowercase first char
41
- // The method name already has the plural relation name (e.g., "addComments")
42
- let relationName = adderName.substring(3)
43
- return relationName.charAt(0).toLowerCase() + relationName.slice(1)
44
- }
45
-
46
25
  // e.g. "comments" -> "removeComment"
47
26
  export function relationToRemoverName(relation: string): string {
48
27
  return `remove${capitalize(pluralToSingular(relation))}`
49
28
  }
50
29
 
51
- // e.g. "removeComments" -> "comments"
52
- export function relationRemoverToName(removerName: string): string {
53
- // Extract the relation name after "remove" and lowercase first char
54
- // The method name already has the plural relation name (e.g., "removeComments")
55
- let relationName = removerName.substring(6)
56
- return relationName.charAt(0).toLowerCase() + relationName.slice(1)
57
- }
58
-
59
- export function relationSetterToName(setterName: string): string {
60
- // Extract the relation name after "set" and lowercase first char
61
- // The method name already has the plural relation name (e.g., "setComments")
62
- let relationName = setterName.substring(3)
63
- return relationName.charAt(0).toLowerCase() + relationName.slice(1)
64
- }
65
-
66
30
  // e.g. "comments" -> "setComments"
67
31
  export function relationToSetterName(relation: string): string {
68
32
  return `set${capitalize(relation)}`
69
33
  }
70
34
 
71
35
 
36
+ /**
37
+ * Generate a random identifier string of the given length (lowercase alpha).
38
+ */
39
+ export function makeRandomId(length: number): string {
40
+ let result = '';
41
+ const characters = 'abcdefghijklmnopqrstuvwxyz';
42
+ const charactersLength = characters.length;
43
+ for (let i = 0; i < length; i++) {
44
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
45
+ }
46
+ return result;
47
+ }
48
+
72
49
  export function stringifyObjectLiteral(obj) {
73
50
  if(Array.isArray(obj)) {
74
51
  //@ts-ignore
@@ -10,7 +10,7 @@ import { Perspective } from "./Perspective";
10
10
  import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
11
11
  import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
12
12
  import { AIClient } from "../ai/AIClient";
13
- import { AllInstancesResult } from "../model/Ad4mModel";
13
+ import { AllInstancesResult } from "../model/types";
14
14
 
15
15
  const LINK_EXPRESSION_FIELDS = `
16
16
  author
@@ -12,7 +12,7 @@ import { AIClient } from "../ai/AIClient";
12
12
  import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
13
13
  import { gql } from "@apollo/client/core";
14
14
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
15
- import { AllInstancesResult } from "../model/Ad4mModel";
15
+ import { AllInstancesResult } from "../model/types";
16
16
  import { escapeSurrealString } from "../utils";
17
17
  import { SHACLShape } from "../shacl/SHACLShape";
18
18
  import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";