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

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.
@@ -1,5 +1,8 @@
1
1
  import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
2
- import { SHACLShape, SHACLPropertyShape } from "../shacl/SHACLShape";
2
+ import { SHACLShape, SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
3
+ import { escapeSurrealString } from "../utils";
4
+ import type { Where } from "./Ad4mModel";
5
+ import { compileWhereClause } from "./surreal-utils";
3
6
 
4
7
  // ============================================================================
5
8
  // WeakMap-based metadata registry
@@ -32,6 +35,18 @@ export interface RelationMetadataEntry {
32
35
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
33
36
  */
34
37
  getter?: string;
38
+ /**
39
+ * Whether to auto-generate a conformance filter when `target` is set.
40
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering
41
+ * while keeping hydration capability via `include`.
42
+ */
43
+ filter?: boolean;
44
+ /**
45
+ * Filter constraints on linked target nodes using the query DSL.
46
+ * Property names reference the target model's properties.
47
+ * Overrides auto-derived conformance when set.
48
+ */
49
+ where?: Where;
35
50
  }
36
51
 
37
52
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
@@ -116,6 +131,69 @@ export interface Ad4mModelLike {
116
131
  generateSHACL?: () => any;
117
132
  }
118
133
 
134
+ /**
135
+ * Build a conformance filter for a relation whose target model is known.
136
+ *
137
+ * Inspects the target class's property metadata to derive:
138
+ * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
139
+ * - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
140
+ * target nodes to only those conforming to the target shape.
141
+ *
142
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
143
+ * @param targetClass - The target model class (resolved from the target() thunk)
144
+ * @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived
145
+ */
146
+ export function buildConformanceFilter(
147
+ relationPredicate: string,
148
+ targetClass: Ad4mModelLike
149
+ ): { getter: string; conformanceConditions: ConformanceCondition[] } | undefined {
150
+ try {
151
+ const targetProps = getPropertiesMetadata(targetClass);
152
+ const conditions: ConformanceCondition[] = [];
153
+ const surrealConditions: string[] = [];
154
+
155
+ // 1. Flags — check predicate + value
156
+ for (const [_propName, propMeta] of Object.entries(targetProps)) {
157
+ if (propMeta.flag && propMeta.initial && propMeta.through) {
158
+ conditions.push({
159
+ type: 'flag',
160
+ predicate: propMeta.through,
161
+ value: propMeta.initial,
162
+ });
163
+ surrealConditions.push(
164
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`
165
+ );
166
+ }
167
+ }
168
+
169
+ // 2. Required (non-flag) properties — check predicate exists
170
+ // Skip properties with custom getters (they don't follow the standard link pattern)
171
+ for (const [_propName, propMeta] of Object.entries(targetProps)) {
172
+ if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {
173
+ conditions.push({
174
+ type: 'required',
175
+ predicate: propMeta.through,
176
+ });
177
+ surrealConditions.push(
178
+ `count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`
179
+ );
180
+ }
181
+ }
182
+
183
+ if (conditions.length === 0) {
184
+ return undefined;
185
+ }
186
+
187
+ const escapedPredicate = escapeSurrealString(relationPredicate);
188
+ const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
189
+
190
+ return { getter, conformanceConditions: conditions };
191
+ } catch (e) {
192
+ // Target class may not have property metadata
193
+ return undefined;
194
+ }
195
+ }
196
+
119
197
  /**
120
198
  * Convert a model instance to a plain serializable object.
121
199
  * Reads the property metadata and extracts values from the instance.
@@ -808,6 +886,62 @@ export function Model(opts: ModelConfig) {
808
886
  ...(relMeta.local && { local: true })
809
887
  }];
810
888
 
889
+ // === Build Getter (conformance filter) ===
890
+ // Priority chain:
891
+ // 1. Explicit getter string → use verbatim
892
+ // 2. `where` clause → compile DSL to SurrealQL getter
893
+ // 3. target + filter !== false → auto-derive from shape
894
+ if (relMeta.getter) {
895
+ relShape.getter = relMeta.getter;
896
+ } else if (relMeta.where) {
897
+ // Compile Where DSL → SurrealQL getter
898
+ try {
899
+ const TargetClass = relMeta.target?.();
900
+ const targetMetadata = TargetClass
901
+ ? (TargetClass as any).getModelMetadata?.() ?? null
902
+ : null;
903
+
904
+ const conditions = compileWhereClause(
905
+ relMeta.where,
906
+ targetMetadata,
907
+ );
908
+
909
+ if (conditions.length > 0) {
910
+ const escapedPredicate = escapeSurrealString(relMeta.predicate);
911
+ relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
912
+ }
913
+ } catch (e) {
914
+ // Target metadata may not be available yet
915
+ }
916
+ } else if (relMeta.target && relMeta.filter !== false) {
917
+ try {
918
+ const TargetClass = relMeta.target();
919
+ const filter = buildConformanceFilter(relMeta.predicate, TargetClass);
920
+ if (filter) {
921
+ relShape.getter = filter.getter;
922
+ relShape.conformanceConditions = filter.conformanceConditions;
923
+ }
924
+ } catch (e) {
925
+ // Target class may not be available yet — getter will be
926
+ // absent and runtime will fall back to unfiltered get_links
927
+ }
928
+ }
929
+
930
+ // === sh:class — target shape reference ===
931
+ // Always set when a target model is declared, regardless of filter.
932
+ // This enables typed construction on the Rust/MCP side.
933
+ if (relMeta.target) {
934
+ try {
935
+ const TargetClass = relMeta.target();
936
+ const targetSHACL = (TargetClass as any).generateSHACL?.();
937
+ if (targetSHACL?.shape?.nodeShapeUri) {
938
+ relShape.class = targetSHACL.shape.nodeShapeUri;
939
+ }
940
+ } catch (e) {
941
+ // Target class may not be available yet
942
+ }
943
+ }
944
+
811
945
  shape.addProperty(relShape);
812
946
  }
813
947
 
@@ -973,18 +1107,54 @@ export function ReadOnly(opts: PropertyOptions) {
973
1107
  * Options for relation decorators (@HasMany, @HasOne, @BelongsToOne, @BelongsToMany).
974
1108
  */
975
1109
  export interface RelationOptions {
976
- /** The predicate URI used to link the two models */
977
- through: string;
978
- /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations. */
1110
+ /**
1111
+ * The predicate URI used to link the two models.
1112
+ * Defaults to `'ad4m://has_child'` when omitted.
1113
+ * Cannot be combined with `getter`.
1114
+ */
1115
+ through?: string;
1116
+ /** The target model class (use a thunk to avoid circular-dependency issues). Optional for untyped string relations.
1117
+ * Cannot be combined with `getter`. */
979
1118
  target?: () => Ad4mModelLike;
980
1119
  /**
981
1120
  * Custom SurrealQL getter to resolve the relation values. Use this for custom graph traversals.
982
1121
  * The expression can reference 'Base' which will be replaced with the instance's base expression.
983
1122
  * Example: "(<-link[WHERE predicate = 'flux://has_reply'].out.uri)"
1123
+ *
1124
+ * Mutually exclusive with `through` and `target`. When `getter` is provided the
1125
+ * relation is read-only (no adder/remover actions are generated).
984
1126
  */
985
1127
  getter?: string;
986
1128
  /** Whether the link is stored locally (not shared on the network) */
987
1129
  local?: boolean;
1130
+ /**
1131
+ * Whether to auto-generate a DB-level conformance filter when `target` is set.
1132
+ * Defaults to `true` when `target` is present — the query will only return linked
1133
+ * nodes whose shape matches the target model (required properties, flags, etc.).
1134
+ * Set to `false` to opt out of filtering while keeping hydration capability.
1135
+ */
1136
+ filter?: boolean;
1137
+ /**
1138
+ * Filter constraints on the linked target nodes, using the same query DSL
1139
+ * as `Model.query().where(...)`. Property names reference the **target**
1140
+ * model's properties (resolved via target metadata).
1141
+ *
1142
+ * When `target` is set and `where` is omitted, conformance conditions are
1143
+ * auto-derived from the target shape (flags + required properties).
1144
+ * Providing `where` overrides this auto-derivation.
1145
+ *
1146
+ * Mutually exclusive with `getter` and `filter: false`.
1147
+ *
1148
+ * @example
1149
+ * ```typescript
1150
+ * @HasMany(() => Message, {
1151
+ * through: "flux://entry_type",
1152
+ * where: { status: "active", priority: { gte: 3 } }
1153
+ * })
1154
+ * activeMessages: Message[] = []
1155
+ * ```
1156
+ */
1157
+ where?: Where;
988
1158
  }
989
1159
 
990
1160
  /**
@@ -1016,13 +1186,47 @@ function resolveRelationArgs(
1016
1186
  second?: Omit<RelationOptions, 'target'>,
1017
1187
  ): RelationOptions {
1018
1188
  const opts = typeof first === 'function'
1019
- ? { ...second!, target: first }
1189
+ ? { ...(second || {}), target: first }
1020
1190
  : first;
1021
1191
 
1192
+ // getter is mutually exclusive with through, target, and where
1193
+ if (opts.getter) {
1194
+ if (opts.through) {
1195
+ throw new Error(
1196
+ 'Relation decorator: `getter` and `through` are mutually exclusive. ' +
1197
+ 'Use `getter` alone for custom read-only relations, or `through` ' +
1198
+ '(with optional `target`) for standard link-based relations.'
1199
+ );
1200
+ }
1201
+ if (opts.target) {
1202
+ throw new Error(
1203
+ 'Relation decorator: `getter` and `target` are mutually exclusive. ' +
1204
+ '`target` auto-generates a conformance getter from the model shape; ' +
1205
+ 'providing both is contradictory.'
1206
+ );
1207
+ }
1208
+ if (opts.where) {
1209
+ throw new Error(
1210
+ 'Relation decorator: `where` and `getter` are mutually exclusive. ' +
1211
+ 'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.'
1212
+ );
1213
+ }
1214
+ return opts;
1215
+ }
1216
+
1217
+ // Default predicate when not provided
1022
1218
  if (!opts.through) {
1023
- throw new Error(
1024
- `Relation decorator requires a { through: '...' } option specifying the predicate URI.`
1025
- );
1219
+ opts.through = 'ad4m://has_child';
1220
+ }
1221
+
1222
+ // where validation
1223
+ if (opts.where) {
1224
+ if (opts.filter === false) {
1225
+ throw new Error(
1226
+ 'Relation decorator: `where` and `filter: false` are contradictory. ' +
1227
+ '`where` adds filtering constraints; `filter: false` disables filtering.'
1228
+ );
1229
+ }
1026
1230
  }
1027
1231
 
1028
1232
  return opts;
@@ -1058,7 +1262,7 @@ function resolveRelationArgs(
1058
1262
  * ```
1059
1263
  */
1060
1264
  export function HasMany(opts: RelationOptions): PropertyDecorator;
1061
- export function HasMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1265
+ export function HasMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1062
1266
  export function HasMany(
1063
1267
  first: (() => Ad4mModelLike) | RelationOptions,
1064
1268
  second?: Omit<RelationOptions, 'target'>,
@@ -1075,19 +1279,24 @@ export function HasMany(
1075
1279
  kind: 'hasMany',
1076
1280
  local: opts.local,
1077
1281
  ...(opts.getter && { getter: opts.getter }),
1282
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1283
+ ...(opts.where && { where: opts.where }),
1078
1284
  };
1079
1285
 
1080
- // Add prototype methods for add/remove/set
1081
1286
  const relKey = key as string;
1082
- (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1083
- return (this as any).addRelationValue(relKey, arg, batchId);
1084
- };
1085
- (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1086
- return (this as any).removeRelationValue(relKey, arg, batchId);
1087
- };
1088
- (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1089
- return (this as any).setRelationValues(relKey, arg, batchId);
1090
- };
1287
+ // Only add mutation methods when a predicate is available
1288
+ // (getter-only relations are read-only)
1289
+ if (opts.through) {
1290
+ (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1291
+ return (this as any).addRelationValue(relKey, arg, batchId);
1292
+ };
1293
+ (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1294
+ return (this as any).removeRelationValue(relKey, arg, batchId);
1295
+ };
1296
+ (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any, batchId?: string) {
1297
+ return (this as any).setRelationValues(relKey, arg, batchId);
1298
+ };
1299
+ }
1091
1300
  Object.defineProperty(target, relKey, { configurable: true, writable: true });
1092
1301
  };
1093
1302
  }
@@ -1117,7 +1326,7 @@ export function HasMany(
1117
1326
  * ```
1118
1327
  */
1119
1328
  export function HasOne(opts: RelationOptions): PropertyDecorator;
1120
- export function HasOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1329
+ export function HasOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1121
1330
  export function HasOne(
1122
1331
  first: (() => Ad4mModelLike) | RelationOptions,
1123
1332
  second?: Omit<RelationOptions, 'target'>,
@@ -1133,26 +1342,32 @@ export function HasOne(
1133
1342
  kind: 'hasOne',
1134
1343
  maxCount: 1,
1135
1344
  local: opts.local,
1345
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1346
+ ...(opts.where && { where: opts.where }),
1136
1347
  };
1137
1348
 
1138
- // Register as a writable property
1139
- applyPropertyMetadata({
1140
- through: opts.through,
1141
- readOnly: false,
1142
- local: opts.local,
1143
- })(target, key);
1144
-
1145
- // Add prototype methods for add/remove/set (mirroring @HasMany)
1146
1349
  const relKey = key as string;
1147
- (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any) {
1148
- return (this as any).addRelationValue(relKey, arg);
1149
- };
1150
- (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any) {
1151
- return (this as any).removeRelationValue(relKey, arg);
1152
- };
1153
- (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any) {
1154
- return (this as any).setRelationValues(relKey, arg);
1155
- };
1350
+ if (opts.through) {
1351
+ // Register as a writable property
1352
+ applyPropertyMetadata({
1353
+ through: opts.through,
1354
+ readOnly: false,
1355
+ local: opts.local,
1356
+ })(target, key);
1357
+
1358
+ // Add prototype methods for add/remove/set (mirroring @HasMany)
1359
+ (target as any)[`add${capitalize(relKey)}`] = async function(this: any, arg: any) {
1360
+ return (this as any).addRelationValue(relKey, arg);
1361
+ };
1362
+ (target as any)[`remove${capitalize(relKey)}`] = async function(this: any, arg: any) {
1363
+ return (this as any).removeRelationValue(relKey, arg);
1364
+ };
1365
+ (target as any)[`set${capitalize(relKey)}`] = async function(this: any, arg: any) {
1366
+ return (this as any).setRelationValues(relKey, arg);
1367
+ };
1368
+ } else {
1369
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
1370
+ }
1156
1371
  };
1157
1372
  }
1158
1373
 
@@ -1181,7 +1396,7 @@ export function HasOne(
1181
1396
  * ```
1182
1397
  */
1183
1398
  export function BelongsToOne(opts: RelationOptions): PropertyDecorator;
1184
- export function BelongsToOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1399
+ export function BelongsToOne(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1185
1400
  export function BelongsToOne(
1186
1401
  first: (() => Ad4mModelLike) | RelationOptions,
1187
1402
  second?: Omit<RelationOptions, 'target'>,
@@ -1197,14 +1412,20 @@ export function BelongsToOne(
1197
1412
  kind: 'belongsToOne',
1198
1413
  maxCount: 1,
1199
1414
  local: opts.local,
1415
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1416
+ ...(opts.where && { where: opts.where }),
1200
1417
  };
1201
1418
 
1202
- // Read-only property (the owning side manages the link)
1203
- applyPropertyMetadata({
1204
- through: opts.through,
1205
- readOnly: true,
1206
- local: opts.local,
1207
- })(target, key);
1419
+ if (opts.through) {
1420
+ // Read-only property (the owning side manages the link)
1421
+ applyPropertyMetadata({
1422
+ through: opts.through,
1423
+ readOnly: true,
1424
+ local: opts.local,
1425
+ })(target, key);
1426
+ } else {
1427
+ Object.defineProperty(target, key, { configurable: true, writable: true });
1428
+ }
1208
1429
  };
1209
1430
  }
1210
1431
 
@@ -1233,7 +1454,7 @@ export function BelongsToOne(
1233
1454
  * ```
1234
1455
  */
1235
1456
  export function BelongsToMany(opts: RelationOptions): PropertyDecorator;
1236
- export function BelongsToMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1457
+ export function BelongsToMany(target: () => Ad4mModelLike, opts?: Omit<RelationOptions, 'target'>): PropertyDecorator;
1237
1458
  export function BelongsToMany(
1238
1459
  first: (() => Ad4mModelLike) | RelationOptions,
1239
1460
  second?: Omit<RelationOptions, 'target'>,
@@ -1249,6 +1470,8 @@ export function BelongsToMany(
1249
1470
  kind: 'belongsToMany',
1250
1471
  local: opts.local,
1251
1472
  ...(opts.getter && { getter: opts.getter }),
1473
+ ...(opts.filter !== undefined && { filter: opts.filter }),
1474
+ ...(opts.where && { where: opts.where }),
1252
1475
  };
1253
1476
 
1254
1477
  // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*