@coasys/ad4m 0.12.0-rc1-dev.1 → 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 (124) hide show
  1. package/jest.config.js +8 -1
  2. package/lib/index.cjs +13793 -12854
  3. package/lib/index.js +13782 -12851
  4. package/lib/src/Ad4mClient.test.d.ts +1 -0
  5. package/lib/src/Ad4mClient.test.js +1204 -0
  6. package/lib/src/Literal.test.d.ts +1 -0
  7. package/lib/src/Literal.test.js +41 -0
  8. package/lib/src/model/Ad4mModel.d.ts +528 -101
  9. package/lib/src/model/Ad4mModel.js +1670 -748
  10. package/lib/src/model/Ad4mModel.test.js +140 -156
  11. package/lib/src/model/Subject.d.ts +3 -3
  12. package/lib/src/model/Subject.js +25 -25
  13. package/lib/src/model/decorators.d.ts +259 -247
  14. package/lib/src/model/decorators.js +379 -422
  15. package/lib/src/model/mutation.d.ts +81 -0
  16. package/lib/src/model/mutation.js +317 -0
  17. package/lib/src/model/parentUtils.d.ts +32 -0
  18. package/lib/src/model/parentUtils.js +64 -0
  19. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  20. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  21. package/lib/src/model/prolog/index.d.ts +1 -0
  22. package/lib/src/model/prolog/index.js +1 -0
  23. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  24. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  25. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  26. package/lib/src/model/query/QueryBuilder.js +193 -0
  27. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  28. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  29. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  30. package/lib/src/model/query/fetchInstance.js +144 -0
  31. package/lib/src/model/query/hydration.d.ts +54 -0
  32. package/lib/src/model/query/hydration.js +214 -0
  33. package/lib/src/model/query/operations.d.ts +59 -0
  34. package/lib/src/model/query/operations.js +384 -0
  35. package/lib/src/model/query/snapshot.d.ts +59 -0
  36. package/lib/src/model/query/snapshot.js +106 -0
  37. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  38. package/lib/src/model/query/surrealCompiler.js +304 -0
  39. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  40. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  41. package/lib/src/model/schema/metadata.d.ts +15 -0
  42. package/lib/src/model/schema/metadata.js +112 -0
  43. package/lib/src/model/subscription.d.ts +47 -0
  44. package/lib/src/model/subscription.js +231 -0
  45. package/lib/src/model/transaction.d.ts +27 -0
  46. package/lib/src/model/transaction.js +32 -0
  47. package/lib/src/model/types.d.ts +195 -0
  48. package/lib/src/model/types.js +8 -0
  49. package/lib/src/model/util.d.ts +6 -6
  50. package/lib/src/model/util.js +22 -22
  51. package/lib/src/neighbourhood/NeighbourhoodClient.js +31 -12
  52. package/lib/src/perspectives/PerspectiveProxy.d.ts +9 -9
  53. package/lib/src/perspectives/PerspectiveProxy.js +63 -51
  54. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  55. package/lib/src/shacl/SHACLShape.js +28 -4
  56. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  57. package/lib/src/shims/type-graphql.d.ts +32 -0
  58. package/lib/src/src/Ad4mClient.d.ts +28 -0
  59. package/lib/src/src/Address.d.ts +1 -0
  60. package/lib/src/src/DID.d.ts +1 -0
  61. package/lib/src/src/Exception.d.ts +7 -0
  62. package/lib/src/src/Literal.d.ts +7 -0
  63. package/lib/src/src/PubSub.d.ts +17 -0
  64. package/lib/src/src/SmartLiteral.d.ts +12 -0
  65. package/lib/src/src/agent/Agent.d.ts +110 -0
  66. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  67. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  68. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  69. package/lib/src/src/ai/AIClient.d.ts +32 -0
  70. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  71. package/lib/src/src/ai/Tasks.d.ts +37 -0
  72. package/lib/src/src/buildSchema.d.ts +1 -0
  73. package/lib/src/src/expression/Expression.d.ts +28 -0
  74. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  75. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  76. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  77. package/lib/src/src/index.d.ts +35 -0
  78. package/lib/src/src/jestSetup.d.ts +1 -0
  79. package/lib/src/src/language/Icon.d.ts +4 -0
  80. package/lib/src/src/language/Language.d.ts +206 -0
  81. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  82. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  83. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  84. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  85. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  86. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  87. package/lib/src/src/links/Links.d.ts +39 -0
  88. package/lib/src/src/links/Links.test.d.ts +1 -0
  89. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  90. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  91. package/lib/src/src/model/Subject.d.ts +25 -0
  92. package/lib/src/src/model/decorators.d.ts +545 -0
  93. package/lib/src/src/model/util.d.ts +12 -0
  94. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  95. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  96. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  97. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  98. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  99. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  100. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  101. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  102. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  103. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  104. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  105. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  106. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  107. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  108. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  109. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  110. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  111. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  112. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  113. package/lib/src/src/typeDefs.d.ts +1 -0
  114. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  115. package/lib/src/src/utils.d.ts +25 -0
  116. package/package.json +20 -24
  117. package/src/model/Ad4mModel.test.ts +132 -149
  118. package/src/model/Ad4mModel.ts +1930 -784
  119. package/src/model/Subject.ts +24 -24
  120. package/src/model/decorators.ts +626 -482
  121. package/src/model/util.ts +22 -22
  122. package/src/neighbourhood/NeighbourhoodClient.ts +32 -16
  123. package/src/perspectives/PerspectiveProxy.ts +69 -55
  124. package/src/shacl/SHACLShape.ts +33 -4
@@ -1,149 +1,169 @@
1
- import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- import { Subject } from "./Subject";
3
1
  import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
4
2
  import { SHACLShape, SHACLPropertyShape } from "../shacl/SHACLShape";
5
3
 
6
- export class PerspectiveAction {
7
- action: string
8
- source: string
9
- predicate: string
10
- target: string
4
+ // ============================================================================
5
+ // WeakMap-based metadata registry
6
+ // ============================================================================
7
+ // Stores property and relation metadata per-class using WeakMaps keyed by
8
+ // the class constructor. This replaces the old prototype-mutation approach
9
+ // and avoids issues with inheritance chains sharing mutable state.
10
+
11
+ /** Metadata stored for each property via @Property / @Optional / @ReadOnly / @Flag */
12
+ export interface PropertyMetadataEntry extends PropertyOptions {
13
+ /** Internal computed writable flag (inverse of readOnly) for SDNA/SHACL compatibility */
14
+ writable?: boolean;
15
+ flag?: boolean;
11
16
  }
12
17
 
13
- export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
14
- return {
15
- action: "addLink",
16
- source,
17
- predicate,
18
- target,
19
- };
18
+ /** Metadata stored for each relation via @HasMany / @HasOne / @BelongsToOne / @BelongsToMany */
19
+ export interface RelationMetadataEntry {
20
+ predicate: string;
21
+ /** Target model class thunk. Optional for untyped string relations. */
22
+ target?: () => Ad4mModelLike;
23
+ kind: 'hasMany' | 'hasOne' | 'belongsToOne' | 'belongsToMany';
24
+ /**
25
+ * Maximum number of related instances.
26
+ * Set automatically: 1 for `@HasOne`/`@BelongsToOne`, undefined (unlimited) for `*Many`.
27
+ */
28
+ maxCount?: number;
29
+ local?: boolean;
30
+ /**
31
+ * Custom SurrealQL getter to resolve the relation values.
32
+ * The expression can reference 'Base' which will be replaced with the instance's base expression.
33
+ */
34
+ getter?: string;
20
35
  }
21
36
 
22
- export function hasLink(predicate: string): string {
23
- return `triple(this, "${predicate}", _)`
37
+ /** Registry of property metadata keyed by constructor → { propName → metadata } */
38
+ const propertyRegistry = new WeakMap<Function, Record<string, PropertyMetadataEntry>>();
39
+
40
+ /** Registry of relation metadata keyed by constructor → { propName → metadata } */
41
+ const relationRegistry = new WeakMap<Function, Record<string, RelationMetadataEntry>>();
42
+
43
+
44
+ /**
45
+ * Retrieve property metadata for a given class constructor.
46
+ * Walks the prototype chain so subclass decorators compose with parent decorators.
47
+ */
48
+ export function getPropertiesMetadata(ctor: Function): Record<string, PropertyMetadataEntry> {
49
+ const result: Record<string, PropertyMetadataEntry> = {};
50
+ const chain: Function[] = [];
51
+ let current = ctor;
52
+ while (current && current !== Object) {
53
+ chain.unshift(current); // parent-first order
54
+ current = Object.getPrototypeOf(current);
55
+ }
56
+ for (const c of chain) {
57
+ const meta = propertyRegistry.get(c);
58
+ if (meta) Object.assign(result, meta);
59
+ }
60
+ return result;
24
61
  }
25
62
 
26
- export interface InstanceQueryParams {
27
63
  /**
28
- * An object representing the WHERE clause of the query.
64
+ * Retrieve relation metadata for a given class constructor.
65
+ * Walks the prototype chain so subclass decorators compose with parent decorators.
29
66
  */
30
- where?: object;
67
+ export function getRelationsMetadata(ctor: Function): Record<string, RelationMetadataEntry> {
68
+ const result: Record<string, RelationMetadataEntry> = {};
69
+ const chain: Function[] = [];
70
+ let current = ctor;
71
+ while (current && current !== Object) {
72
+ chain.unshift(current);
73
+ current = Object.getPrototypeOf(current);
74
+ }
75
+ for (const c of chain) {
76
+ const meta = relationRegistry.get(c);
77
+ if (meta) Object.assign(result, meta);
78
+ }
79
+ return result;
80
+ }
81
+
31
82
 
32
83
  /**
33
- * A string representing the Prolog condition clause of the query.
84
+ * Programmatically register property metadata for a given constructor.
85
+ * Used by `fromJSONSchema()` and other dynamic model builders.
34
86
  */
35
- prologCondition?: string;
87
+ export function setPropertyRegistryEntry(
88
+ ctor: Function,
89
+ propName: string,
90
+ meta: PropertyMetadataEntry & { writable?: boolean },
91
+ ): void {
92
+ if (!propertyRegistry.has(ctor)) propertyRegistry.set(ctor, {});
93
+ propertyRegistry.get(ctor)![propName] = meta;
36
94
  }
37
95
 
38
96
  /**
39
- * Decorator for querying instances of a model class.
40
- *
41
- * @category Decorators
42
- *
43
- * @description
44
- * Allows you to define static query methods on your model class to retrieve instances based on custom conditions.
45
- * This decorator can only be applied to static async methods that return a Promise of an array of model instances.
46
- *
47
- * The query can be constrained using either:
48
- * - A `where` clause that matches property values
49
- * - A custom Prolog `condition` for more complex queries
50
- *
51
- * @example
52
- * ```typescript
53
- * class Recipe extends Ad4mModel {
54
- * @Property({ through: "recipe://name" })
55
- * name: string = "";
56
- *
57
- * @Property({ through: "recipe://rating" })
58
- * rating: number = 0;
59
- *
60
- * // Get all recipes
61
- * @InstanceQuery()
62
- * static async all(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
63
- *
64
- * // Get recipes by name
65
- * @InstanceQuery({ where: { name: "Chocolate Cake" }})
66
- * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
67
- *
68
- * // Get highly rated recipes using a custom condition
69
- * @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
70
- * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
71
- * }
72
- * ```
73
- *
74
- * @param {Object} [options] - Query options
75
- * @param {object} [options.where] - Object with property-value pairs to match
76
- * @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
97
+ * Programmatically register relation metadata for a given constructor.
98
+ * Used by `fromJSONSchema()` and other dynamic model builders.
77
99
  */
78
- export function InstanceQuery(options?: InstanceQueryParams) {
79
- return function <T>(target: T, key: keyof T, descriptor: PropertyDescriptor) {
80
- const originalMethod = descriptor.value;
81
- if(typeof originalMethod !== "function") {
82
- throw new Error("InstanceQuery decorator can only be applied to methods");
83
- }
100
+ export function setRelationRegistryEntry(
101
+ ctor: Function,
102
+ relName: string,
103
+ meta: RelationMetadataEntry,
104
+ ): void {
105
+ if (!relationRegistry.has(ctor)) relationRegistry.set(ctor, {});
106
+ relationRegistry.get(ctor)![relName] = meta;
107
+ }
84
108
 
85
- descriptor.value = async function(perspective: PerspectiveProxy): Promise<T[]> {
86
- let instances: T[] = []
87
- //@ts-ignore
88
- let subjectClassName = target.name
89
- let query = `subject_class("${subjectClassName}", C), instance(C, Instance)`
90
- if(options && options.where) {
91
- for(let prop in options.where) {
92
- let value = options.where[prop]
93
- query += `, property_getter(C, Instance, "${prop}", "${value}")`
94
- }
95
- }
109
+ /**
110
+ * Interface for any class that looks like an Ad4mModel (used in circular-ref-safe typings).
111
+ */
112
+ export interface Ad4mModelLike {
113
+ new (...args: any[]): any;
114
+ className?: string;
115
+ generateSDNA?: () => any;
116
+ generateSHACL?: () => any;
117
+ }
96
118
 
97
- if(options && options.prologCondition) {
98
- query += ', ' + options.prologCondition
99
- }
119
+ /**
120
+ * Convert a model instance to a plain serializable object.
121
+ * Reads the property metadata and extracts values from the instance.
122
+ */
123
+ export function instanceToSerializable(instance: any): Record<string, any> {
124
+ const ctor = instance.constructor;
125
+ const props = getPropertiesMetadata(ctor);
126
+ const result: Record<string, any> = {};
127
+ for (const [key, _meta] of Object.entries(props)) {
128
+ result[key] = instance[key];
129
+ }
130
+ return result;
131
+ }
100
132
 
101
- // Try Prolog first
102
- try {
103
- let results = await perspective.infer(query)
104
- if(results && results !== false && typeof results !== "string" && results.length > 0) {
105
- for(let result of results) {
106
- let instance = result.Instance
107
- let subject = new Subject(perspective, instance, subjectClassName)
108
- await subject.init()
109
- instances.push(subject as T)
110
- }
111
- return instances
112
- }
113
- } catch (e) {
114
- // Prolog failed, fall through to SurrealDB
115
- }
133
+ /**
134
+ * Generate a random identifier string (lowercase alpha).
135
+ * Generate a random identifier string of the given length (lowercase alpha).
136
+ */
137
+ export function makeRandomId(length: number): string {
138
+ let result = '';
139
+ const characters = 'abcdefghijklmnopqrstuvwxyz';
140
+ const charactersLength = characters.length;
141
+ for (let i = 0; i < length; i++) {
142
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
143
+ }
144
+ return result;
145
+ }
116
146
 
117
- // Fallback to SurrealDB (SdnaOnly mode)
118
- // Get all instances first - pass the class constructor, not just the name
119
- let allInstances = await perspective.getAllSubjectInstances(target)
120
-
121
- // Filter by where clause if provided
122
- if(options && options.where) {
123
- let filtered = []
124
- for(let instance of allInstances) {
125
- let matches = true
126
- for(let prop in options.where) {
127
- let expectedValue = options.where[prop]
128
- //@ts-ignore
129
- let actualValue = await instance[prop]
130
- if(actualValue !== expectedValue) {
131
- matches = false
132
- break
133
- }
134
- }
135
- if(matches) {
136
- filtered.push(instance as T)
137
- }
138
- }
139
- return filtered
140
- }
147
+ export class PerspectiveAction {
148
+ action: string
149
+ source: string
150
+ predicate: string
151
+ target: string
152
+ }
141
153
 
142
- return allInstances as T[]
143
- }
154
+ export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
155
+ return {
156
+ action: "addLink",
157
+ source,
158
+ predicate,
159
+ target,
144
160
  };
145
161
  }
146
162
 
163
+ export function hasLink(predicate: string): string {
164
+ return `triple(this, "${predicate}", _)`
165
+ }
166
+
147
167
 
148
168
  export interface PropertyOptions {
149
169
  /**
@@ -162,9 +182,10 @@ export interface PropertyOptions {
162
182
  required?: boolean;
163
183
 
164
184
  /**
165
- * Indicates whether the property is writable. If true, a setter will be available in the prolog engine.
185
+ * Indicates whether the property is read-only. If true, no setter will be generated.
186
+ * Defaults to false (property is writable).
166
187
  */
167
- writable?: boolean;
188
+ readOnly?: boolean;
168
189
 
169
190
  /**
170
191
  * The language used to store the property. Can be the default `Literal` Language or a custom language address.
@@ -203,89 +224,15 @@ export interface PropertyOptions {
203
224
 
204
225
 
205
226
  /**
206
- * Decorator for defining optional properties on model classes.
207
- *
208
- * @category Decorators
209
- *
210
- * @description
211
- * The most flexible property decorator that allows you to define properties with full control over:
212
- * - Whether the property is required
213
- * - Whether the property is writable
214
- * - How values are stored and retrieved
215
- * - Custom getter/setter logic
216
- * - Local vs network storage
217
- *
218
- * Both @Property and @ReadOnly are specialized versions of @Optional with preset configurations.
219
- *
220
- * @example
221
- * ```typescript
222
- * class Recipe extends Ad4mModel {
223
- * // Basic optional property
224
- * @Optional({
225
- * through: "recipe://description"
226
- * })
227
- * description?: string;
228
- *
229
- * // Optional property with custom initial value
230
- * @Optional({
231
- * through: "recipe://status",
232
- * initial: "recipe://draft",
233
- * required: true
234
- * })
235
- * status: string = "";
236
- *
237
- * // Read-only property with custom getter
238
- * @Optional({
239
- * through: "recipe://rating",
240
- * writable: false,
241
- * getter: `
242
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
243
- * sum_list(Ratings, Sum),
244
- * length(Ratings, Count),
245
- * Value is Sum / Count
246
- * `
247
- * })
248
- * averageRating: number = 0;
249
- *
250
- * // Property that resolves to a Literal and is stored locally
251
- * @Optional({
252
- * through: "recipe://notes",
253
- * resolveLanguage: "literal",
254
- * local: true
255
- * })
256
- * notes?: string;
257
- *
258
- * // Property with custom getter and setter logic
259
- * @Optional({
260
- * through: "recipe://ingredients",
261
- * getter: `
262
- * triple(Base, "recipe://ingredients", RawValue),
263
- * atom_json_term(RawValue, Value)
264
- * `,
265
- * setter: `
266
- * atom_json_term(Value, JsonValue),
267
- * Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "recipe://ingredients", "target": JsonValue}]
268
- * `
269
- * })
270
- * ingredients: string[] = [];
271
- * }
272
- * ```
273
- *
274
- * @param {PropertyOptions} opts - Property configuration options
275
- * @param {string} opts.through - The predicate URI for the property
276
- * @param {string} [opts.initial] - Initial value (required if property is required)
277
- * @param {boolean} [opts.required] - Whether the property must have a value
278
- * @param {boolean} [opts.writable=true] - Whether the property can be modified
279
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
280
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
281
- * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
282
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
227
+ * Internal core implementation for registering property metadata on the prototype.
228
+ * All property decorators (@Property, @Optional, @ReadOnly) and relation decorators
229
+ * that create properties delegate to this function.
230
+ * @internal
283
231
  */
284
- export function Optional(opts: PropertyOptions) {
232
+ function applyPropertyMetadata(opts: PropertyOptions) {
285
233
  return function <T>(target: T, key: keyof T) {
286
- if(typeof opts.writable === "undefined" && opts.through) {
287
- opts.writable = true
288
- }
234
+ // Map readOnly → internal writable for SDNA/SHACL compatibility
235
+ const writable = opts.readOnly ? false : (opts.through ? true : false);
289
236
 
290
237
  if (opts.required && !opts.initial) {
291
238
  throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
@@ -295,11 +242,12 @@ export function Optional(opts: PropertyOptions) {
295
242
  throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option")
296
243
  }
297
244
 
298
- target["__properties"] = target["__properties"] || {};
299
- target["__properties"][key] = target["__properties"][key] || {};
300
- target["__properties"][key] = { ...target["__properties"][key], ...opts }
245
+ // Write to WeakMap registry (keyed by constructor)
246
+ const ctor = (target as any).constructor;
247
+ if (!propertyRegistry.has(ctor)) propertyRegistry.set(ctor, {});
248
+ propertyRegistry.get(ctor)![key as string] = { ...opts, writable } as any;
301
249
 
302
- if (opts.writable) {
250
+ if (writable) {
303
251
  const value = key as string
304
252
  target[`set${capitalize(value)}`] = () => {}
305
253
  }
@@ -308,6 +256,34 @@ export function Optional(opts: PropertyOptions) {
308
256
  };
309
257
  }
310
258
 
259
+ /**
260
+ * Convenience decorator for defining optional (not required) properties.
261
+ *
262
+ * @category Decorators
263
+ *
264
+ * @description
265
+ * Equivalent to `@Property` but defaults `required` to `false` and does not
266
+ * apply `resolveLanguage` or `initial` defaults. Use this when a property
267
+ * may or may not have a value, and you want full control over its configuration.
268
+ *
269
+ * @example
270
+ * ```typescript
271
+ * class Recipe extends Ad4mModel {
272
+ * @Optional({ through: "recipe://description" })
273
+ * description?: string;
274
+ * }
275
+ * ```
276
+ *
277
+ * @param {PropertyOptions} opts - Property configuration (same options as @Property)
278
+ */
279
+ export function Optional(opts: PropertyOptions) {
280
+ return applyPropertyMetadata({
281
+ ...opts,
282
+ required: opts.required ?? false,
283
+ readOnly: opts.readOnly ?? false,
284
+ });
285
+ }
286
+
311
287
  export interface FlagOptions {
312
288
  /**
313
289
  * The predicate of the property. All properties must have this option.
@@ -387,15 +363,19 @@ export function Flag(opts: FlagOptions) {
387
363
  throw new Error("SubjectFlag requires a 'value' option")
388
364
  }
389
365
 
390
- target["__properties"] = target["__properties"] || {};
391
- target["__properties"][key] = target["__properties"][key] || {};
392
- target["__properties"][key] = {
393
- ...target["__properties"][key],
366
+ const entry = {
394
367
  through: opts.through,
395
368
  required: true,
396
369
  initial: opts.value,
397
- flag: true
398
- }
370
+ flag: true,
371
+ readOnly: true,
372
+ writable: false,
373
+ };
374
+
375
+ // Write to WeakMap registry
376
+ const ctor = (target as any).constructor;
377
+ if (!propertyRegistry.has(ctor)) propertyRegistry.set(ctor, {});
378
+ propertyRegistry.get(ctor)![key as string] = entry as any;
399
379
 
400
380
  // @ts-ignore
401
381
  target[key] = opts.value;
@@ -404,133 +384,9 @@ export function Flag(opts: FlagOptions) {
404
384
  };
405
385
  }
406
386
 
407
- interface WhereOptions {
408
- isInstance?: any
409
- prologCondition?: string
410
- condition?: string
411
- }
412
-
413
- export interface CollectionOptions {
414
- /**
415
- * The predicate of the property. All properties must have this option.
416
- */
417
- through: string;
418
-
419
- /**
420
- * An object representing the WHERE clause of the query.
421
- */
422
- where?: WhereOptions;
423
387
 
424
- /**
425
- * Custom SurrealQL getter to resolve the collection values. Use this for custom graph traversals.
426
- * The expression can reference 'Base' which will be replaced with the instance's base expression.
427
- * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)"
428
- */
429
- getter?: string;
430
388
 
431
- /**
432
- * Indicates whether the property is stored locally in the perspective and not in the network. Useful for properties that are not meant to be shared with the network.
433
- */
434
- local?: boolean;
435
- }
436
-
437
- /**
438
- * Decorator for defining collections on model classes.
439
- *
440
- * @category Decorators
441
- *
442
- * @description
443
- * Defines a property that represents a collection of values linked to the model instance.
444
- * Collections are always arrays and support operations for adding, removing, and setting values.
445
- *
446
- * For each collection property, the following methods are automatically generated:
447
- * - `addX(value)` - Add a value to the collection
448
- * - `removeX(value)` - Remove a value from the collection
449
- * - `setCollectionX(values)` - Replace all values in the collection
450
- *
451
- * Where X is the capitalized property name.
452
- *
453
- * Collections can be filtered using the `where` option to only include values that:
454
- * - Are instances of a specific model class
455
- * - Match a custom Prolog condition
456
- *
457
- * @example
458
- * ```typescript
459
- * class Recipe extends Ad4mModel {
460
- * // Basic collection of ingredients
461
- * @Collection({
462
- * through: "recipe://ingredient"
463
- * })
464
- * ingredients: string[] = [];
465
- *
466
- * // Collection that only includes instances of another model
467
- * @Collection({
468
- * through: "recipe://comment",
469
- * where: { isInstance: Comment }
470
- * })
471
- * comments: string[] = [];
472
- *
473
- * // Collection with custom Prolog filter condition
474
- * @Collection({
475
- * through: "recipe://step",
476
- * where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
477
- * })
478
- * firstSteps: string[] = [];
479
- *
480
- * // Collection with custom SurrealDB filter condition
481
- * @Collection({
482
- * through: "recipe://entries",
483
- * where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
484
- * })
485
- * ingredients: string[] = [];
486
- *
487
- * // Local-only collection not shared with network
488
- * @Collection({
489
- * through: "recipe://note",
490
- * local: true
491
- * })
492
- * privateNotes: string[] = [];
493
- * }
494
- *
495
- * // Using the generated methods:
496
- * const recipe = new Recipe(perspective);
497
- * await recipe.addIngredients("ingredient://flour");
498
- * await recipe.removeIngredients("ingredient://sugar");
499
- * await recipe.setCollectionIngredients(["ingredient://butter", "ingredient://eggs"]);
500
- * ```
501
- *
502
- * @param {CollectionOptions} opts - Collection configuration
503
- * @param {string} opts.through - The predicate URI for collection links
504
- * @param {WhereOptions} [opts.where] - Filter conditions for collection values
505
- * @param {any} [opts.where.isInstance] - Model class to filter instances by
506
- * @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
507
- * @param {boolean} [opts.local] - Whether collection links are stored locally only
508
- */
509
- export function Collection(opts: CollectionOptions) {
510
- return function <T>(target: T, key: keyof T) {
511
- target["__collections"] = target["__collections"] || {};
512
- target["__collections"][key] = opts;
513
-
514
- const value = key as string
515
- target[`add${capitalize(value)}`] = () => {}
516
- target[`remove${capitalize(value)}`] = () => {}
517
- target[`setCollection${capitalize(value)}`] = () => {}
518
-
519
- Object.defineProperty(target, key, {configurable: true, writable: true});
520
- };
521
- }
522
-
523
- export function makeRandomPrologAtom(length: number): string {
524
- let result = '';
525
- let characters = 'abcdefghijklmnopqrstuvwxyz';
526
- let charactersLength = characters.length;
527
- for (let i = 0; i < length; i++) {
528
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
529
- }
530
- return result;
531
- }
532
-
533
- export interface ModelOptionsOptions {
389
+ export interface ModelConfig {
534
390
  /**
535
391
  * The name of the entity.
536
392
  */
@@ -549,13 +405,13 @@ export interface ModelOptionsOptions {
549
405
  *
550
406
  * This decorator:
551
407
  * - Registers the class with a unique name in the AD4M system
552
- * - Generates the necessary SDNA code for the model's properties and collections
553
- * - Enables the use of other model decorators (@Property, @Collection, etc.)
408
+ * - Generates the necessary SDNA code for the model's properties and relations
409
+ * - Enables the use of other model decorators (@Property, @HasMany, etc.)
554
410
  * - Provides static query methods through the Ad4mModel base class
555
411
  *
556
412
  * @example
557
413
  * ```typescript
558
- * @ModelOptions({ name: "Recipe" })
414
+ * @Model({ name: "Recipe" })
559
415
  * class Recipe extends Ad4mModel {
560
416
  * @Property({
561
417
  * through: "recipe://name",
@@ -563,7 +419,7 @@ export interface ModelOptionsOptions {
563
419
  * })
564
420
  * name: string = "";
565
421
  *
566
- * @Collection({ through: "recipe://ingredient" })
422
+ * @HasMany({ through: "recipe://ingredient" })
567
423
  * ingredients: string[] = [];
568
424
  *
569
425
  * // Static query methods from Ad4mModel:
@@ -588,10 +444,10 @@ export interface ModelOptionsOptions {
588
444
  * await perspective.ensureSDNASubjectClass(Recipe);
589
445
  * ```
590
446
  *
591
- * @param {ModelOptionsOptions} opts - Model configuration
447
+ * @param {ModelConfig} opts - Model configuration
592
448
  * @param {string} opts.name - Unique name for the model class in AD4M
593
449
  */
594
- export function ModelOptions(opts: ModelOptionsOptions) {
450
+ export function Model(opts: ModelConfig) {
595
451
  return function (target: any) {
596
452
  target.prototype.className = opts.name;
597
453
  target.className = opts.name;
@@ -601,7 +457,7 @@ export function ModelOptions(opts: ModelOptionsOptions) {
601
457
  let subjectName = opts.name
602
458
  let obj = target.prototype;
603
459
 
604
- let uuid = makeRandomPrologAtom(8)
460
+ let uuid = makeRandomId(8)
605
461
 
606
462
  sdna += `subject_class("${subjectName}", ${uuid}).\n`
607
463
 
@@ -619,7 +475,7 @@ export function ModelOptions(opts: ModelOptionsOptions) {
619
475
  }
620
476
 
621
477
  let propertiesCode = []
622
- let properties = obj.__properties || {}
478
+ let properties = getPropertiesMetadata(target)
623
479
  for(let property in properties) {
624
480
  let propertyCode = `property(${uuid}, "${property}").\n`
625
481
 
@@ -662,12 +518,19 @@ export function ModelOptions(opts: ModelOptionsOptions) {
662
518
 
663
519
  propertiesCode.push(propertyCode)
664
520
 
665
- if(initial) {
521
+ // Auto-derive effectiveInitial for required, writable, non-flag properties
522
+ // so constructor/destructor always handle the property link.
523
+ // Optional properties (required: false) are excluded — they should
524
+ // remain unset (undefined) until explicitly assigned.
525
+ const effectiveInitial = initial
526
+ ?? (required && writable && !flag && through ? "literal://string:" : undefined);
527
+
528
+ if(effectiveInitial) {
666
529
  constructorActions.push({
667
530
  action: "addLink",
668
531
  source: "this",
669
532
  predicate: through,
670
- target: initial,
533
+ target: effectiveInitial,
671
534
  })
672
535
 
673
536
  classRemoverActions.push({
@@ -679,49 +542,20 @@ export function ModelOptions(opts: ModelOptionsOptions) {
679
542
  }
680
543
  }
681
544
 
682
- let collectionsCode = []
683
- let collections = obj.__collections || {}
684
- for(let collection in collections) {
685
- let collectionCode = `collection(${uuid}, "${collection}").\n`
545
+ let relationsCode = []
546
+ const allRelationsMeta = getRelationsMetadata(target)
547
+ const relations = Object.fromEntries(
548
+ Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
549
+ )
550
+ for(let relation in relations) {
551
+ let relationCode = `collection(${uuid}, "${relation}").\n`
686
552
 
687
- let { through, where, local} = collections[collection]
553
+ let { predicate: through, local} = relations[relation]
688
554
 
689
555
  if(through) {
690
- if(where) {
691
- if(!where.isInstance && !where.prologCondition && !where.condition) {
692
- throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'"
693
- }
694
-
695
- let conditions = []
696
-
697
- if(where.isInstance) {
698
- let otherClass
699
- if(where.isInstance.name) {
700
- otherClass = where.isInstance.name
701
- } else {
702
- otherClass = where.isInstance
703
- }
704
- conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`)
705
- }
706
-
707
- if(where.prologCondition) {
708
- conditions.push(where.prologCondition)
709
- }
710
-
711
- // If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
712
- // If only condition is present, use simple findall (SurrealDB will filter later)
713
- if(conditions.length > 0) {
714
- const conditionString = conditions.join(", ")
715
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`
716
- } else {
717
- // Only SurrealDB condition present (no Prolog filtering)
718
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
719
- }
720
- } else {
721
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
722
- }
556
+ relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
723
557
 
724
- let collectionAdderAction = [{
558
+ let relationAdderAction = [{
725
559
  action: "addLink",
726
560
  source: "this",
727
561
  predicate: through,
@@ -729,26 +563,26 @@ export function ModelOptions(opts: ModelOptionsOptions) {
729
563
  ...(local && { local: true })
730
564
  }]
731
565
 
732
- let collectionRemoverAction = [{
566
+ let relationRemoverAction = [{
733
567
  action: "removeLink",
734
568
  source: "this",
735
569
  predicate: through,
736
570
  target: "value",
737
571
  }]
738
572
 
739
- let collectionSetterAction = [{
573
+ let relationSetterAction = [{
740
574
  action: "collectionSetter",
741
575
  source: "this",
742
576
  predicate: through,
743
577
  target: "value",
744
578
  ...(local && { local: true })
745
579
  }]
746
- collectionCode += `collection_adder(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`
747
- collectionCode += `collection_remover(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`
748
- collectionCode += `collection_setter(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`
580
+ relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`
581
+ relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`
582
+ relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`
749
583
  }
750
584
 
751
- collectionsCode.push(collectionCode)
585
+ relationsCode.push(relationCode)
752
586
  }
753
587
 
754
588
  let subjectContructorJSONString = stringifyObjectLiteral(constructorActions)
@@ -762,7 +596,7 @@ export function ModelOptions(opts: ModelOptionsOptions) {
762
596
  sdna += "\n"
763
597
  sdna += propertiesCode.join("\n")
764
598
  sdna += "\n"
765
- sdna += collectionsCode.join("\n")
599
+ sdna += relationsCode.join("\n")
766
600
 
767
601
  return {
768
602
  sdna,
@@ -775,10 +609,13 @@ export function ModelOptions(opts: ModelOptionsOptions) {
775
609
  const subjectName = opts.name;
776
610
  const obj = target.prototype;
777
611
 
778
- // Determine namespace from first property or collection, or use default
612
+ // Determine namespace from first property or relation, or use default
779
613
  let namespace = "ad4m://";
780
- const properties = obj.__properties || {};
781
- const collections = obj.__collections || {};
614
+ const properties = getPropertiesMetadata(target);
615
+ const allRelationsMeta2 = getRelationsMetadata(target);
616
+ const relations = Object.fromEntries(
617
+ Object.entries(allRelationsMeta2).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
618
+ );
782
619
 
783
620
  // Try properties first
784
621
  if (Object.keys(properties).length > 0) {
@@ -791,11 +628,11 @@ export function ModelOptions(opts: ModelOptionsOptions) {
791
628
  }
792
629
  }
793
630
  }
794
- // Fall back to collections if no properties
795
- else if (Object.keys(collections).length > 0) {
796
- const firstColl = collections[Object.keys(collections)[0]];
797
- if (firstColl.through) {
798
- const match = firstColl.through.match(/^([^:]+:\/\/)/);
631
+ // Fall back to relations if no properties
632
+ else if (Object.keys(relations).length > 0) {
633
+ const firstRel = relations[Object.keys(relations)[0]];
634
+ if (firstRel.predicate) {
635
+ const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
799
636
  if (match) {
800
637
  namespace = match[1];
801
638
  }
@@ -807,6 +644,17 @@ export function ModelOptions(opts: ModelOptionsOptions) {
807
644
  const targetClass = `${namespace}${subjectName}`;
808
645
  const shape = new SHACLShape(shapeUri, targetClass);
809
646
 
647
+ // Detect @Model inheritance — if the parent class also has
648
+ // generateSHACL it is itself a @Model and we reference its shape
649
+ // via sh:node so SHACL validators can walk the hierarchy.
650
+ const parentCtor = Object.getPrototypeOf(target);
651
+ if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
652
+ const parentSHACL = parentCtor.generateSHACL();
653
+ if (parentSHACL?.shape?.nodeShapeUri) {
654
+ shape.addParentShape(parentSHACL.shape.nodeShapeUri);
655
+ }
656
+ }
657
+
810
658
  // === Extract Constructor Actions (same logic as generateSDNA) ===
811
659
  let constructorActions = [];
812
660
  if(obj.subjectConstructor && obj.subjectConstructor.length) {
@@ -849,10 +697,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
849
697
  }
850
698
 
851
699
  // Single-valued properties get maxCount 1
852
- // (collections are handled separately below)
853
- if (!propMeta.collection) {
854
- propShape.maxCount = 1;
855
- }
700
+ // (relations are handled separately below)
701
+ propShape.maxCount = 1;
856
702
 
857
703
  // Flag properties have fixed value
858
704
  if (propMeta.flag && propMeta.initial) {
@@ -873,8 +719,8 @@ export function ModelOptions(opts: ModelOptionsOptions) {
873
719
  }
874
720
 
875
721
  // === Extract Setter Actions (same logic as generateSDNA) ===
876
- if (propMeta.setter) {
877
- // Custom setter defined - not yet supported in SHACL
722
+ if (propMeta.prologSetter) {
723
+ // Custom Prolog setter defined - not yet supported in SHACL
878
724
  console.warn(
879
725
  `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
880
726
  `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
@@ -894,12 +740,19 @@ export function ModelOptions(opts: ModelOptionsOptions) {
894
740
  }
895
741
 
896
742
  // Add to constructor actions if property has initial value
897
- if (propMeta.initial) {
743
+ // Auto-derive effectiveInitial for required, writable, non-flag properties.
744
+ // Optional properties (required: false) are excluded — they should
745
+ // remain unset (undefined) until explicitly assigned.
746
+ const effectiveInitial = propMeta.initial
747
+ ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
748
+ ? "literal://string:" : undefined);
749
+
750
+ if (effectiveInitial) {
898
751
  constructorActions.push({
899
752
  action: "addLink",
900
753
  source: "this",
901
754
  predicate: propMeta.through,
902
- target: propMeta.initial,
755
+ target: effectiveInitial,
903
756
  });
904
757
 
905
758
  // Add to destructor actions
@@ -914,70 +767,57 @@ export function ModelOptions(opts: ModelOptionsOptions) {
914
767
  shape.addProperty(propShape);
915
768
  }
916
769
 
917
- // Convert collections to SHACL property shapes
918
- // (collections variable already declared above for namespace inference)
919
- for (const collName in collections) {
920
- const collMeta = collections[collName];
770
+ // Convert relations to SHACL property shapes
771
+ // (relations variable already declared above for namespace inference)
772
+ for (const relName in relations) {
773
+ const relMeta = relations[relName];
921
774
 
922
- if (!collMeta.through) continue;
775
+ if (!relMeta.predicate) continue;
923
776
 
924
- const collShape: SHACLPropertyShape = {
925
- name: collName, // Collection name for generating named URIs
926
- path: collMeta.through,
927
- // Collections have no maxCount (unlimited)
777
+ const relShape: SHACLPropertyShape = {
778
+ name: relName, // Relation name for generating named URIs
779
+ path: relMeta.predicate,
780
+ // Relations have no maxCount (unlimited)
928
781
  // minCount defaults to 0 (optional)
929
782
  };
930
783
 
931
- // Determine if it's a reference (IRI) or literal
932
- // Collections typically contain references (IRIs) to other entities
933
- // They're literals only if explicitly marked or contain primitive values
934
- if (collMeta.where?.isInstance) {
935
- // Collection of typed entities - definitely IRIs
936
- collShape.nodeKind = 'IRI';
937
- } else {
938
- // Default to IRI for collections (most common case)
939
- // Literal collections are rare and would need explicit marking
940
- collShape.nodeKind = 'IRI';
941
- }
784
+ // Determine node kind — relations typically contain IRIs
785
+ relShape.nodeKind = 'IRI';
942
786
 
943
787
  // AD4M-specific metadata
944
- if (collMeta.local !== undefined) {
945
- collShape.local = collMeta.local;
788
+ if (relMeta.local !== undefined) {
789
+ relShape.local = relMeta.local;
946
790
  }
947
791
 
948
- if (collMeta.writable !== undefined) {
949
- collShape.writable = collMeta.writable;
950
- }
951
-
952
- // === Extract Collection Actions (adder/remover) ===
953
- // Adder action - adds a link to the collection
954
- collShape.adder = [{
792
+ // === Extract Relation Actions (adder/remover) ===
793
+ // Adder action - adds a link to the relation
794
+ relShape.adder = [{
955
795
  action: "addLink",
956
796
  source: "this",
957
- predicate: collMeta.through,
797
+ predicate: relMeta.predicate,
958
798
  target: "value",
959
- ...(collMeta.local && { local: true })
799
+ ...(relMeta.local && { local: true })
960
800
  }];
961
801
 
962
- // Remover action - removes a link from the collection
963
- collShape.remover = [{
802
+ // Remover action - removes a link from the relation
803
+ relShape.remover = [{
964
804
  action: "removeLink",
965
805
  source: "this",
966
- predicate: collMeta.through,
806
+ predicate: relMeta.predicate,
967
807
  target: "value",
968
- ...(collMeta.local && { local: true })
808
+ ...(relMeta.local && { local: true })
969
809
  }];
970
810
 
971
- shape.addProperty(collShape);
811
+ shape.addProperty(relShape);
972
812
  }
973
813
 
974
- // Set constructor and destructor actions on the shape
975
- if (constructorActions.length > 0) {
976
- shape.setConstructorActions(constructorActions);
977
- }
978
- if (destructorActions.length > 0) {
979
- shape.setDestructorActions(destructorActions);
980
- }
814
+ // Always set constructor and destructor actions on the shape, even
815
+ // when empty. An empty array serialises to `literal://string:[]`
816
+ // which the Rust executor parses as a valid (no-op) command list,
817
+ // avoiding "No SHACL constructor found" errors for models whose
818
+ // properties are all optional and have no @Flag.
819
+ shape.setConstructorActions(constructorActions);
820
+ shape.setDestructorActions(destructorActions);
981
821
 
982
822
  return {
983
823
  shape,
@@ -990,66 +830,76 @@ export function ModelOptions(opts: ModelOptionsOptions) {
990
830
  }
991
831
 
992
832
  /**
993
- * Decorator for defining required and writable properties on model classes.
833
+ * The primary property decorator for AD4M model classes.
994
834
  *
995
835
  * @category Decorators
996
836
  *
997
837
  * @description
998
- * A convenience decorator that defines a required property that must have an initial value and is writable by default.
999
- * This is equivalent to using @Optional with `required: true` and `writable: true`.
838
+ * The core property decorator with smart defaults. All other property decorators
839
+ * (@Optional, @ReadOnly) are thin wrappers that adjust these defaults.
840
+ *
841
+ * Smart defaults (all overridable):
842
+ * - `required` → `false`
843
+ * - `readOnly` → `false`
844
+ * - `resolveLanguage` → `"literal"`
845
+ * - `initial` → `undefined` (no link created until a value is explicitly set)
1000
846
  *
1001
- * Properties defined with this decorator:
1002
- * - Must have a value (required)
1003
- * - Can be modified after creation (writable)
1004
- * - Default to "literal://string:uninitialized" if no initial value is provided
847
+ * Properties are optional by default. When a model instance is created without
848
+ * providing a value for an optional property, no link is added to the graph.
849
+ * Set `required: true` explicitly when a property must always be present (this
850
+ * also adds a `"literal://string:uninitialized"` sentinel as the initial value
851
+ * so that the SDNA constructor creates a placeholder link).
1005
852
  *
1006
853
  * @example
1007
854
  * ```typescript
1008
855
  * class User extends Ad4mModel {
1009
- * // Basic required property with default initial value
856
+ * // Optional property (default) — no link created until a value is set
1010
857
  * @Property({
1011
858
  * through: "user://name"
1012
859
  * })
1013
860
  * name: string = "";
1014
861
  *
1015
- * // Required property with custom initial value
862
+ * // Explicitly required property with sentinel initial value
1016
863
  * @Property({
1017
864
  * through: "user://status",
1018
- * initial: "user://active"
865
+ * required: true
1019
866
  * })
1020
867
  * status: string = "";
1021
868
  *
1022
- * // Required property with literal resolution
869
+ * // Required property with custom initial value
870
+ * @Property({
871
+ * through: "user://role",
872
+ * required: true,
873
+ * initial: "user://member"
874
+ * })
875
+ * role: string = "";
876
+ *
877
+ * // Optional property with literal resolution
1023
878
  * @Property({
1024
879
  * through: "user://bio",
1025
880
  * resolveLanguage: "literal"
1026
881
  * })
1027
882
  * bio: string = "";
1028
- *
1029
- * // Required property with custom getter/setter
1030
- * @Property({
1031
- * through: "user://age",
1032
- * getter: `triple(Base, "user://birthYear", Year), Value is 2024 - Year`,
1033
- * setter: `Year is 2024 - Value, Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "user://birthYear", "target": Year}]`
1034
- * })
1035
- * age: number = 0;
1036
883
  * }
1037
884
  * ```
1038
885
  *
1039
886
  * @param {PropertyOptions} opts - Property configuration
1040
887
  * @param {string} opts.through - The predicate URI for the property
1041
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
888
+ * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)
889
+ * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized" when required)
1042
890
  * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
1043
891
  * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
1044
892
  * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
1045
893
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
1046
894
  */
1047
895
  export function Property(opts: PropertyOptions) {
1048
- return Optional({
896
+ const required = opts.required ?? false;
897
+ return applyPropertyMetadata({
1049
898
  ...opts,
1050
- required: true,
1051
- writable: true,
1052
- initial: opts.initial || "literal://string:uninitialized"
899
+ required,
900
+ readOnly: opts.readOnly ?? false,
901
+ resolveLanguage: opts.resolveLanguage ?? "literal",
902
+ initial: opts.initial ?? (required ? "literal://string:uninitialized" : undefined),
1053
903
  });
1054
904
  }
1055
905
 
@@ -1059,8 +909,8 @@ export function Property(opts: PropertyOptions) {
1059
909
  * @category Decorators
1060
910
  *
1061
911
  * @description
1062
- * A convenience decorator that defines a property that can only be read and cannot be modified after initialization.
1063
- * This is equivalent to using @Optional with `writable: false`.
912
+ * A convenience decorator that defines a read-only property.
913
+ * Equivalent to `@Property` with `readOnly: true`.
1064
914
  *
1065
915
  * Read-only properties are ideal for:
1066
916
  * - Computed or derived values
@@ -1109,8 +959,302 @@ export function Property(opts: PropertyOptions) {
1109
959
  * @param {boolean} [opts.local] - Whether the property should only be stored locally
1110
960
  */
1111
961
  export function ReadOnly(opts: PropertyOptions) {
1112
- return Optional({
962
+ return Property({
1113
963
  ...opts,
1114
- writable: false
964
+ readOnly: true,
1115
965
  });
1116
- }
966
+ }
967
+
968
+ // ============================================================================
969
+ // Relation decorators
970
+ // ============================================================================
971
+
972
+ /**
973
+ * Options for relation decorators (@HasMany, @HasOne, @BelongsToOne, @BelongsToMany).
974
+ */
975
+ 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. */
979
+ target?: () => Ad4mModelLike;
980
+ /**
981
+ * Custom SurrealQL getter to resolve the relation values. Use this for custom graph traversals.
982
+ * The expression can reference 'Base' which will be replaced with the instance's base expression.
983
+ * Example: "(<-link[WHERE predicate = 'flux://has_reply'].out.uri)"
984
+ */
985
+ getter?: string;
986
+ /** Whether the link is stored locally (not shared on the network) */
987
+ local?: boolean;
988
+ }
989
+
990
+ /**
991
+ * Utility type that describes the auto-generated helper methods for a HasMany
992
+ * relation. For a property named `comments` on a class `Post`, the following
993
+ * methods will be available on instances:
994
+ *
995
+ * post.addComment(value)
996
+ * post.removeComment(value)
997
+ * post.setComment(values)
998
+ */
999
+ export type HasManyMethods<Keys extends string> = {
1000
+ [K in Keys as `add${Capitalize<K>}`]: (value: string | { id: string }, batchId?: string) => Promise<void>;
1001
+ } & {
1002
+ [K in Keys as `remove${Capitalize<K>}`]: (value: string | { id: string }, batchId?: string) => Promise<void>;
1003
+ } & {
1004
+ [K in Keys as `set${Capitalize<K>}`]: (values: (string | { id: string })[], batchId?: string) => Promise<void>;
1005
+ };
1006
+
1007
+ /**
1008
+ * Resolve overloaded relation decorator arguments.
1009
+ * Supports two calling conventions:
1010
+ * @HasMany({ through: "...", target: () => X }) — single options object
1011
+ * @HasMany(() => X, { through: "..." }) — target thunk + options
1012
+ * @internal
1013
+ */
1014
+ function resolveRelationArgs(
1015
+ first: (() => Ad4mModelLike) | RelationOptions,
1016
+ second?: Omit<RelationOptions, 'target'>,
1017
+ ): RelationOptions {
1018
+ const opts = typeof first === 'function'
1019
+ ? { ...second!, target: first }
1020
+ : first;
1021
+
1022
+ if (!opts.through) {
1023
+ throw new Error(
1024
+ `Relation decorator requires a { through: '...' } option specifying the predicate URI.`
1025
+ );
1026
+ }
1027
+
1028
+ return opts;
1029
+ }
1030
+
1031
+ /**
1032
+ * Decorator for defining a one-to-many relation.
1033
+ *
1034
+ * @category Decorators
1035
+ *
1036
+ * @description
1037
+ * Declares that the decorated property is an array of related model instances.
1038
+ * Under the hood it registers the relation in the relation registry and also
1039
+ * creates the corresponding relation entry so that the SDNA / SHACL
1040
+ * generators continue to emit the correct subject-class code.
1041
+ *
1042
+ * Supports two calling conventions:
1043
+ * ```typescript
1044
+ * // Options-object style
1045
+ * @HasMany({ through: "post://comment", target: () => Comment })
1046
+ *
1047
+ * // Target-first shorthand
1048
+ * @HasMany(() => Comment, { through: "post://comment" })
1049
+ * ```
1050
+ *
1051
+ * @example
1052
+ * ```typescript
1053
+ * @Model({ name: "Post" })
1054
+ * class Post extends Ad4mModel {
1055
+ * @HasMany(() => Comment, { through: "post://comment" })
1056
+ * comments: string[] = [];
1057
+ * }
1058
+ * ```
1059
+ */
1060
+ export function HasMany(opts: RelationOptions): PropertyDecorator;
1061
+ export function HasMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1062
+ export function HasMany(
1063
+ first: (() => Ad4mModelLike) | RelationOptions,
1064
+ second?: Omit<RelationOptions, 'target'>,
1065
+ ): PropertyDecorator {
1066
+ const opts = resolveRelationArgs(first, second);
1067
+ return function <T>(target: T, key: keyof T) {
1068
+ // --- relation registry ---
1069
+ const ctor = (target as any).constructor;
1070
+ if (!relationRegistry.has(ctor)) relationRegistry.set(ctor, {});
1071
+ const map = relationRegistry.get(ctor)!;
1072
+ map[key as string] = {
1073
+ predicate: opts.through,
1074
+ target: opts.target,
1075
+ kind: 'hasMany',
1076
+ local: opts.local,
1077
+ ...(opts.getter && { getter: opts.getter }),
1078
+ };
1079
+
1080
+ // Add prototype methods for add/remove/set
1081
+ 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
+ };
1091
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
1092
+ };
1093
+ }
1094
+
1095
+ /**
1096
+ * Decorator for defining a one-to-one relation (owning side).
1097
+ *
1098
+ * @category Decorators
1099
+ *
1100
+ * @description
1101
+ * Declares that the decorated property holds a single related model instance.
1102
+ * The owning side manages the link.
1103
+ *
1104
+ * Supports two calling conventions:
1105
+ * ```typescript
1106
+ * @HasOne({ through: "post://author", target: () => Author })
1107
+ * @HasOne(() => Author, { through: "post://author" })
1108
+ * ```
1109
+ *
1110
+ * @example
1111
+ * ```typescript
1112
+ * @Model({ name: "Post" })
1113
+ * class Post extends Ad4mModel {
1114
+ * @HasOne(() => Author, { through: "post://author" })
1115
+ * author: string = "";
1116
+ * }
1117
+ * ```
1118
+ */
1119
+ export function HasOne(opts: RelationOptions): PropertyDecorator;
1120
+ export function HasOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1121
+ export function HasOne(
1122
+ first: (() => Ad4mModelLike) | RelationOptions,
1123
+ second?: Omit<RelationOptions, 'target'>,
1124
+ ): PropertyDecorator {
1125
+ const opts = resolveRelationArgs(first, second);
1126
+ return function <T>(target: T, key: keyof T) {
1127
+ const ctor = (target as any).constructor;
1128
+ if (!relationRegistry.has(ctor)) relationRegistry.set(ctor, {});
1129
+ const map = relationRegistry.get(ctor)!;
1130
+ map[key as string] = {
1131
+ predicate: opts.through,
1132
+ target: opts.target,
1133
+ kind: 'hasOne',
1134
+ maxCount: 1,
1135
+ local: opts.local,
1136
+ };
1137
+
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
+ 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
+ };
1156
+ };
1157
+ }
1158
+
1159
+ /**
1160
+ * Decorator for defining the inverse side of a one-to-one relation.
1161
+ *
1162
+ * @category Decorators
1163
+ *
1164
+ * @description
1165
+ * Declares the non-owning (inverse) side of a one-to-one relationship.
1166
+ * The property is read-only since the owning side manages the link.
1167
+ *
1168
+ * Supports two calling conventions:
1169
+ * ```typescript
1170
+ * @BelongsToOne({ through: "post://author", target: () => Post })
1171
+ * @BelongsToOne(() => Post, { through: "post://author" })
1172
+ * ```
1173
+ *
1174
+ * @example
1175
+ * ```typescript
1176
+ * @Model({ name: "Author" })
1177
+ * class Author extends Ad4mModel {
1178
+ * @BelongsToOne(() => Post, { through: "post://author" })
1179
+ * post: string = "";
1180
+ * }
1181
+ * ```
1182
+ */
1183
+ export function BelongsToOne(opts: RelationOptions): PropertyDecorator;
1184
+ export function BelongsToOne(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1185
+ export function BelongsToOne(
1186
+ first: (() => Ad4mModelLike) | RelationOptions,
1187
+ second?: Omit<RelationOptions, 'target'>,
1188
+ ): PropertyDecorator {
1189
+ const opts = resolveRelationArgs(first, second);
1190
+ return function <T>(target: T, key: keyof T) {
1191
+ const ctor = (target as any).constructor;
1192
+ if (!relationRegistry.has(ctor)) relationRegistry.set(ctor, {});
1193
+ const map = relationRegistry.get(ctor)!;
1194
+ map[key as string] = {
1195
+ predicate: opts.through,
1196
+ target: opts.target,
1197
+ kind: 'belongsToOne',
1198
+ maxCount: 1,
1199
+ local: opts.local,
1200
+ };
1201
+
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);
1208
+ };
1209
+ }
1210
+
1211
+ /**
1212
+ * Decorator for defining the inverse side of a many-to-many relation.
1213
+ *
1214
+ * @category Decorators
1215
+ *
1216
+ * @description
1217
+ * Declares the non-owning (inverse) side of a many-to-many relationship.
1218
+ * The property is a read-only relation since the owning side manages links.
1219
+ *
1220
+ * Supports two calling conventions:
1221
+ * ```typescript
1222
+ * @BelongsToMany({ through: "post://tag", target: () => Post })
1223
+ * @BelongsToMany(() => Post, { through: "post://tag" })
1224
+ * ```
1225
+ *
1226
+ * @example
1227
+ * ```typescript
1228
+ * @Model({ name: "Tag" })
1229
+ * class Tag extends Ad4mModel {
1230
+ * @BelongsToMany(() => Post, { through: "post://tag" })
1231
+ * posts: string[] = [];
1232
+ * }
1233
+ * ```
1234
+ */
1235
+ export function BelongsToMany(opts: RelationOptions): PropertyDecorator;
1236
+ export function BelongsToMany(target: () => Ad4mModelLike, opts: Omit<RelationOptions, 'target'>): PropertyDecorator;
1237
+ export function BelongsToMany(
1238
+ first: (() => Ad4mModelLike) | RelationOptions,
1239
+ second?: Omit<RelationOptions, 'target'>,
1240
+ ): PropertyDecorator {
1241
+ const opts = resolveRelationArgs(first, second);
1242
+ return function <T>(target: T, key: keyof T) {
1243
+ const ctor = (target as any).constructor;
1244
+ if (!relationRegistry.has(ctor)) relationRegistry.set(ctor, {});
1245
+ const map = relationRegistry.get(ctor)!;
1246
+ map[key as string] = {
1247
+ predicate: opts.through,
1248
+ target: opts.target,
1249
+ kind: 'belongsToMany',
1250
+ local: opts.local,
1251
+ ...(opts.getter && { getter: opts.getter }),
1252
+ };
1253
+
1254
+ // @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
1255
+ // prototype methods. Mutation must go through the owning side's @HasMany decorator.
1256
+ const relKey = key as string;
1257
+ Object.defineProperty(target, relKey, { configurable: true, writable: true });
1258
+ };
1259
+ }
1260
+