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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6044
  3. package/lib/index.js +5977 -6038
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2797
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3247
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -1,1116 +1,759 @@
1
1
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- import { Subject } from "./Subject";
3
- import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
2
+ import {
3
+ capitalize,
4
+ propertyNameToSetterName,
5
+ stringifyObjectLiteral,
6
+ } from "./util";
4
7
  import { SHACLShape, SHACLPropertyShape } from "../shacl/SHACLShape";
5
8
 
6
- export class PerspectiveAction {
7
- action: string
8
- source: string
9
- predicate: string
10
- target: string
11
- }
12
-
13
- export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
14
- return {
15
- action: "addLink",
16
- source,
17
- predicate,
18
- target,
19
- };
9
+ // Module-level WeakMaps keyed on the constructor function (not the prototype).
10
+ // Each class constructor is a unique key, so subclass decorators write into their
11
+ // own entry rather than the parent prototype's — preventing silent metadata corruption
12
+ // across inherited classes (e.g. BaseBlock and PollBlock stay independent).
13
+ export const propertyRegistry = new WeakMap<Function, Record<string, any>>();
14
+ export const relationRegistry = new WeakMap<Function, Record<string, any>>();
15
+
16
+ /** Returns the own + inherited property metadata for a given constructor, with own values winning. */
17
+ export function getPropertiesMetadata(ctor: Function): Record<string, any> {
18
+ if (!ctor) return {};
19
+ const own = propertyRegistry.get(ctor) ?? {};
20
+ const parent = Object.getPrototypeOf(ctor);
21
+ if (!parent || parent === Function.prototype) return own;
22
+ return { ...getPropertiesMetadata(parent), ...own };
20
23
  }
21
24
 
22
- export function hasLink(predicate: string): string {
23
- return `triple(this, "${predicate}", _)`
25
+ /** Returns the own + inherited relation metadata for a given constructor, with own values winning. */
26
+ export function getRelationsMetadata(ctor: Function): Record<string, any> {
27
+ if (!ctor) return {};
28
+ const own = relationRegistry.get(ctor) ?? {};
29
+ const parent = Object.getPrototypeOf(ctor);
30
+ if (!parent || parent === Function.prototype) return own;
31
+ return { ...getRelationsMetadata(parent), ...own };
24
32
  }
25
33
 
26
- export interface InstanceQueryParams {
27
- /**
28
- * An object representing the WHERE clause of the query.
29
- */
30
- where?: object;
31
-
32
34
  /**
33
- * A string representing the Prolog condition clause of the query.
35
+ * Builds a plain, JSON-safe object from a model instance.
36
+ *
37
+ * Only includes `id` (if present) and decorator-registered \@Property keys.
38
+ * All other own enumerable properties are stripped — most importantly the
39
+ * TypeScript `private _perspective` field which is stored as a regular
40
+ * enumerable property at runtime and holds a PerspectiveProxy whose Apollo
41
+ * InMemoryCache creates a circular reference in `JSON.stringify`.
42
+ *
43
+ * Falls back to a shallow spread for plain objects with no registered props
44
+ * (e.g. raw link objects passed through before model hydration).
34
45
  */
35
- prologCondition?: string;
46
+ export function instanceToSerializable(instance: any): Record<string, unknown> {
47
+ if (!instance || typeof instance !== "object") return {};
48
+ const ctor = Object.getPrototypeOf(instance)?.constructor as
49
+ | Function
50
+ | undefined;
51
+ const registeredProps = ctor ? getPropertiesMetadata(ctor) : null;
52
+ const registeredRels = ctor ? getRelationsMetadata(ctor) : null;
53
+ const propKeys = registeredProps ? Object.keys(registeredProps) : null;
54
+ const relKeys = registeredRels ? Object.keys(registeredRels) : null;
55
+ const allKeys =
56
+ (propKeys ?? relKeys) ? [...(propKeys ?? []), ...(relKeys ?? [])] : null;
57
+ if (!allKeys || allKeys.length === 0) {
58
+ // Plain object / no @Property decorators — safe to spread.
59
+ return { ...(instance as object) };
60
+ }
61
+ const obj: Record<string, unknown> = {};
62
+ if ((instance as any).id !== undefined) {
63
+ obj.id = (instance as any).id;
64
+ }
65
+ for (const key of allKeys) {
66
+ const val = (instance as any)[key];
67
+ // For relation arrays containing model instances, serialize only their IDs
68
+ // to avoid circular references and keep the fingerprint lightweight.
69
+ if (Array.isArray(val)) {
70
+ obj[key] = val.map((item: any) =>
71
+ item && typeof item === "object" && item.id !== undefined
72
+ ? item.id
73
+ : item,
74
+ );
75
+ } else {
76
+ obj[key] = val;
77
+ }
78
+ }
79
+ return obj;
36
80
  }
37
81
 
38
- /**
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
77
- */
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
- }
82
+ export class PerspectiveAction {
83
+ action: string;
84
+ source: string;
85
+ predicate: string;
86
+ target: string;
87
+ }
84
88
 
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
- }
96
-
97
- if(options && options.prologCondition) {
98
- query += ', ' + options.prologCondition
99
- }
100
-
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
- }
116
-
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
- }
141
-
142
- return allInstances as T[]
143
- }
144
- };
89
+ export function addLink(
90
+ source: string,
91
+ predicate: string,
92
+ target: string,
93
+ ): PerspectiveAction {
94
+ return {
95
+ action: "addLink",
96
+ source,
97
+ predicate,
98
+ target,
99
+ };
145
100
  }
146
101
 
102
+ export function hasLink(predicate: string): string {
103
+ return `triple(this, "${predicate}", _)`;
104
+ }
147
105
 
148
106
  export interface PropertyOptions {
149
- /**
150
- * The predicate of the property. All properties must have this option.
151
- */
152
- through?: string;
153
-
154
- /**
155
- * The initial value of the property. Required if the property is marked as required.
156
- */
157
- initial?: string;
158
-
159
- /**
160
- * Indicates whether the property is required. If true, an initial value must be provided.
161
- */
162
- required?: boolean;
163
-
164
- /**
165
- * Indicates whether the property is writable. If true, a setter will be available in the prolog engine.
166
- */
167
- writable?: boolean;
168
-
169
- /**
170
- * The language used to store the property. Can be the default `Literal` Language or a custom language address.
171
- */
172
- resolveLanguage?: string;
173
-
174
- /**
175
- * Custom Prolog getter to get the value of the property. If not provided, the default getter will be used.
176
- */
177
- prologGetter?: string;
178
-
179
- /**
180
- * Custom Prolog setter to set the value of the property. Only available if the property is writable.
181
- */
182
- prologSetter?: string;
183
-
184
- /**
185
- * Custom SurrealQL getter to resolve the property value. Use this for custom graph traversals.
186
- * The expression can reference 'Base' which will be replaced with the instance's base expression.
187
- * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)[0]"
188
- */
189
- getter?: string;
190
-
191
- /**
192
- * 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.
193
- */
194
- local?: boolean;
195
-
196
- /**
197
- * Optional transform function to modify the property value after it is retrieved.
198
- * This is useful for transforming raw data into a more usable format.
199
- * The function takes the raw value as input and returns the transformed value.
200
- */
201
- transform?: (value: any) => any;
107
+ /**
108
+ * The predicate of the property. All properties must have this option.
109
+ */
110
+ through?: string;
111
+
112
+ /**
113
+ * The initial value written by the SHACL constructor action.
114
+ *
115
+ * For non-readOnly properties this is **optional** — Ad4mModel
116
+ * automatically derives a placeholder and overwrites it with the real
117
+ * instance field value when `save()` is called. Only set this explicitly
118
+ * when you need a specific non-literal default URI (e.g. a custom
119
+ * `resolveLanguage` address) or want a sentinel value if the property
120
+ * is never set.
121
+ */
122
+ initial?: string;
123
+
124
+ /**
125
+ * Indicates whether the property is required. If true, an initial value must be provided.
126
+ */
127
+ required?: boolean;
128
+
129
+ /**
130
+ * Marks the property as read-only — no setter action will be generated and
131
+ * the property cannot be updated via the model layer. Defaults to false
132
+ * (writable) when `through` is set.
133
+ */
134
+ readOnly?: boolean;
135
+
136
+ /**
137
+ * The language used to resolve the stored expression into a JS value.
138
+ *
139
+ * Omitting this (the common case) is equivalent to `"literal"` — scalar values
140
+ * (string / number / boolean) are encoded as `literal://` URIs automatically.
141
+ * Only specify this when you need a non-literal language (e.g. a custom IPFS
142
+ * language address) or want to be explicit for documentation purposes.
143
+ */
144
+ resolveLanguage?: string;
145
+
146
+ /**
147
+ * Custom SurrealQL getter to resolve the property value. Use this for custom graph traversals.
148
+ * The expression can reference 'Base' which will be replaced with the instance's base expression.
149
+ * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)[0]"
150
+ */
151
+ getter?: string;
152
+
153
+ /**
154
+ * 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.
155
+ */
156
+ local?: boolean;
157
+
158
+ /**
159
+ * Optional transform function to modify the property value after it is retrieved.
160
+ * This is useful for transforming raw data into a more usable format.
161
+ * The function takes the raw value as input and returns the transformed value.
162
+ */
163
+ transform?: (value: any) => any;
164
+
165
+ /**
166
+ * Indicates that this property is a @Flag — a fixed predicate/value pair written
167
+ * once by the createSubject constructor action and never changed. Flag properties
168
+ * are immutable and will be skipped during updates.
169
+ */
170
+ flag?: boolean;
202
171
  }
203
172
 
204
-
205
173
  /**
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
174
+ * Declares a typed property backed by a single link triple in the perspective.
175
+ *
176
+ * @param opts.through - Predicate URI (required)
177
+ * @param opts.initial - Default value written by the constructor action (auto-derived for non-readOnly properties; only needed for custom URIs)
178
+ * @param opts.required - Adds `sh:minCount 1` to the SHACL shape
179
+ * @param opts.readOnly - Skips setter generation; property cannot be updated after creation (default: false)
180
+ * @param opts.resolveLanguage - Language for value resolution (`"literal"`, etc.)
181
+ * @param opts.local - Store only in local perspective, not shared with the network
182
+ * @param opts.getter - Custom SurrealQL expression for computed / read-only properties
183
+ * @param opts.transform - Post-fetch transform applied to the raw value
283
184
  */
284
- export function Optional(opts: PropertyOptions) {
285
- return function <T>(target: T, key: keyof T) {
286
- if(typeof opts.writable === "undefined" && opts.through) {
287
- opts.writable = true
288
- }
289
-
290
- if (opts.required && !opts.initial) {
291
- throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
292
- }
293
-
294
- if (!opts.through && !opts.prologGetter) {
295
- throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option")
296
- }
185
+ export function Property(opts: PropertyOptions) {
186
+ return function <T>(target: T, key: keyof T) {
187
+ if (!opts.through) {
188
+ throw new Error("@Property requires a 'through' option");
189
+ }
297
190
 
298
- target["__properties"] = target["__properties"] || {};
299
- target["__properties"][key] = target["__properties"][key] || {};
300
- target["__properties"][key] = { ...target["__properties"][key], ...opts }
191
+ const _propertyExisting =
192
+ propertyRegistry.get((target as any).constructor) ?? {};
193
+ const _propertyExistingKey = _propertyExisting[key as string] ?? {};
194
+ propertyRegistry.set((target as any).constructor, {
195
+ ..._propertyExisting,
196
+ [key as string]: { ..._propertyExistingKey, ...opts },
197
+ });
301
198
 
302
- if (opts.writable) {
303
- const value = key as string
304
- target[`set${capitalize(value)}`] = () => {}
305
- }
199
+ if (!opts.readOnly) {
200
+ const value = key as string;
201
+ target[`set${capitalize(value)}`] = () => {};
202
+ }
306
203
 
307
- Object.defineProperty(target, key, {configurable: true, writable: true});
308
- };
204
+ Object.defineProperty(target, key, { configurable: true, writable: true });
205
+ };
309
206
  }
310
207
 
311
208
  export interface FlagOptions {
312
- /**
313
- * The predicate of the property. All properties must have this option.
314
- */
315
- through: string;
316
-
317
- /**
318
- * The value of the property.
319
- */
320
- value: string;
209
+ /**
210
+ * The predicate of the property. All properties must have this option.
211
+ */
212
+ through: string;
213
+
214
+ /**
215
+ * The value of the property.
216
+ */
217
+ value: string;
321
218
  }
322
219
 
323
220
  /**
324
- * Decorator for defining flags on model classes.
325
- *
326
- * @category Decorators
327
- *
328
- * @description
329
- * A specialized property decorator for defining immutable type flags or markers on model instances.
330
- * Flags are always required properties with a fixed value that cannot be changed after creation.
331
- *
332
- * Common uses for flags:
333
- * - Type discrimination between different kinds of models
334
- * - Marking models with specific capabilities or features
335
- * - Versioning or compatibility markers
336
- *
337
- * Note: Use of Flag is discouraged unless you specifically need type-based filtering or
338
- * discrimination between different kinds of models. For most cases, regular properties
339
- * with @Property or @Optional are more appropriate.
340
- *
221
+ * Immutable type-marker property: written once at creation and never modified.
222
+ *
223
+ * Use for type-discrimination predicates (e.g. `ad4m://type = "ad4m://message"`).
224
+ * For mutable data prefer `@Property`.
225
+ *
341
226
  * @example
342
227
  * ```typescript
343
- * class Message extends Ad4mModel {
344
- * // Type flag to identify message models
345
- * @Flag({
346
- * through: "ad4m://type",
347
- * value: "ad4m://message"
348
- * })
349
- * type: string = "";
350
- *
351
- * // Version flag for compatibility
352
- * @Flag({
353
- * through: "ad4m://version",
354
- * value: "1.0.0"
355
- * })
356
- * version: string = "";
357
- *
358
- * // Feature flag
359
- * @Flag({
360
- * through: "message://feature",
361
- * value: "message://encrypted"
362
- * })
363
- * feature: string = "";
364
- * }
365
- *
366
- * // Later you can query for specific types:
367
- * const messages = await Message.query(perspective)
368
- * .where({ type: "ad4m://message" })
369
- * .run();
228
+ * @Flag({ through: "ad4m://type", value: "ad4m://message" })
229
+ * type: string = "";
370
230
  * ```
371
- *
372
- * @param {FlagOptions} opts - Flag configuration
373
- * @param {string} opts.through - The predicate URI for the flag
374
- * @param {string} opts.value - The fixed value for the flag
375
231
  */
376
232
  export function Flag(opts: FlagOptions) {
377
- return function <T>(target: T, key: keyof T) {
378
- if (!opts.through && !opts.value) {
379
- throw new Error("SubjectFlag requires a 'through' and 'value' option")
380
- }
233
+ return function <T>(target: T, key: keyof T) {
234
+ if (!opts.through && !opts.value) {
235
+ throw new Error("SubjectFlag requires a 'through' and 'value' option");
236
+ }
381
237
 
382
- if (!opts.through) {
383
- throw new Error("SubjectFlag requires a 'through' option")
384
- }
238
+ if (!opts.through) {
239
+ throw new Error("SubjectFlag requires a 'through' option");
240
+ }
385
241
 
386
- if (!opts.value) {
387
- throw new Error("SubjectFlag requires a 'value' option")
388
- }
242
+ if (!opts.value) {
243
+ throw new Error("SubjectFlag requires a 'value' option");
244
+ }
389
245
 
390
- target["__properties"] = target["__properties"] || {};
391
- target["__properties"][key] = target["__properties"][key] || {};
392
- target["__properties"][key] = {
393
- ...target["__properties"][key],
394
- through: opts.through,
395
- required: true,
396
- initial: opts.value,
397
- flag: true
398
- }
246
+ const _flagExisting =
247
+ propertyRegistry.get((target as any).constructor) ?? {};
248
+ propertyRegistry.set((target as any).constructor, {
249
+ ..._flagExisting,
250
+ [key as string]: {
251
+ ...(_flagExisting[key as string] ?? {}),
252
+ through: opts.through,
253
+ required: true,
254
+ initial: opts.value,
255
+ flag: true,
256
+ readOnly: true, // Flags are always immutable after creation
257
+ },
258
+ });
399
259
 
400
- // @ts-ignore
401
- target[key] = opts.value;
260
+ // @ts-ignore
261
+ target[key] = opts.value;
402
262
 
403
- Object.defineProperty(target, key, {configurable: true, writable: true});
404
- };
263
+ Object.defineProperty(target, key, { configurable: true, writable: true });
264
+ };
405
265
  }
406
266
 
407
- interface WhereOptions {
408
- isInstance?: any
409
- prologCondition?: string
410
- condition?: string
267
+ export interface RelationOptions {
268
+ /**
269
+ * The predicate of the property. All properties must have this option.
270
+ */
271
+ through: string;
272
+
273
+ /**
274
+ * Custom SurrealQL getter to resolve the related values. Use this for custom graph traversals.
275
+ * The expression can reference 'Base' which will be replaced with the instance's base expression.
276
+ * Example: "(<-link[WHERE predicate = 'flux://has_reply'].in.uri)"
277
+ */
278
+ getter?: string;
279
+
280
+ /**
281
+ * 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.
282
+ */
283
+ local?: boolean;
411
284
  }
412
285
 
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
-
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
-
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;
286
+ /** Minimal structural type for Ad4mModel instances — used in mutator signatures to avoid circular imports. */
287
+ export interface Ad4mModelLike {
288
+ readonly id: string;
435
289
  }
436
290
 
437
291
  /**
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
- *
292
+ * Utility type that generates the runtime methods produced by \@HasMany / \@HasOne decorators.
293
+ *
294
+ * For each relation property `foo`, the decorator generates:
295
+ * - `addFoo(value)` — Add a value (string ID or model instance)
296
+ * - `removeFoo(value)` — Remove a value
297
+ * - `setFoo(values)` — Replace all values
298
+ *
299
+ * Pass a string union of your \@HasMany/\@HasOne property names and use interface merging:
457
300
  * @example
458
301
  * ```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[] = [];
302
+ * \@Model({ name: 'Post' })
303
+ * export class Post extends Ad4mModel {
304
+ * \@HasMany(() => Comment, { through: 'post://comment' })
305
+ * comments: Comment[] = [];
493
306
  * }
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"]);
307
+ * export interface Post extends HasManyMethods<'comments'> {}
500
308
  * ```
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
309
  */
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;
310
+ export type HasManyMethods<Keys extends string> = {
311
+ [K in Keys as `add${Capitalize<K>}`]: (
312
+ value: string | Ad4mModelLike,
313
+ batchId?: string,
314
+ ) => Promise<void>;
315
+ } & {
316
+ [K in Keys as `remove${Capitalize<K>}`]: (
317
+ value: string | Ad4mModelLike,
318
+ batchId?: string,
319
+ ) => Promise<void>;
320
+ } & {
321
+ [K in Keys as `set${Capitalize<K>}`]: (
322
+ values: (string | Ad4mModelLike)[],
323
+ batchId?: string,
324
+ ) => Promise<void>;
325
+ };
326
+
327
+ export function HasMany(
328
+ relatedModelOrOpts: (() => any) | RelationOptions,
329
+ opts?: RelationOptions,
330
+ ) {
331
+ const resolvedOpts: RelationOptions =
332
+ typeof relatedModelOrOpts === "function" ? opts! : relatedModelOrOpts;
333
+ const relatedModel: (() => any) | undefined =
334
+ typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
335
+ return function <T>(target: T, key: keyof T) {
336
+ if (!resolvedOpts?.through) {
337
+ throw new Error(
338
+ `@HasMany on "${String(key)}" requires a "through" predicate in RelationOptions`,
339
+ );
340
+ }
341
+ const _hasManyExisting =
342
+ relationRegistry.get((target as any).constructor) ?? {};
343
+ relationRegistry.set((target as any).constructor, {
344
+ ..._hasManyExisting,
345
+ [key as string]: {
346
+ ...resolvedOpts,
347
+ direction: "forward" as const,
348
+ ...(relatedModel ? { relatedModel } : {}),
349
+ },
350
+ });
513
351
 
514
- const value = key as string
515
- target[`add${capitalize(value)}`] = () => {}
516
- target[`remove${capitalize(value)}`] = () => {}
517
- target[`setCollection${capitalize(value)}`] = () => {}
352
+ const value = key as string;
353
+ target[`add${capitalize(value)}`] = () => {};
354
+ target[`remove${capitalize(value)}`] = () => {};
355
+ target[`set${capitalize(value)}`] = () => {};
518
356
 
519
- Object.defineProperty(target, key, {configurable: true, writable: true});
520
- };
357
+ Object.defineProperty(target, key, { configurable: true, writable: true });
358
+ };
521
359
  }
522
360
 
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));
361
+ export function HasOne(
362
+ relatedModelOrOpts: (() => any) | RelationOptions,
363
+ opts?: RelationOptions,
364
+ ) {
365
+ const resolvedOpts: RelationOptions =
366
+ typeof relatedModelOrOpts === "function" ? opts! : relatedModelOrOpts;
367
+ const relatedModel: (() => any) | undefined =
368
+ typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
369
+ return function <T>(target: T, key: keyof T) {
370
+ if (!resolvedOpts?.through) {
371
+ throw new Error(
372
+ `@HasOne on "${String(key)}" requires a "through" predicate in RelationOptions`,
373
+ );
529
374
  }
530
- return result;
531
- }
532
-
533
- export interface ModelOptionsOptions {
534
- /**
535
- * The name of the entity.
536
- */
537
- name: string;
538
- }
375
+ const _hasOneExisting =
376
+ relationRegistry.get((target as any).constructor) ?? {};
377
+ relationRegistry.set((target as any).constructor, {
378
+ ..._hasOneExisting,
379
+ [key as string]: {
380
+ ...resolvedOpts,
381
+ direction: "forward" as const,
382
+ maxCount: 1,
383
+ ...(relatedModel ? { relatedModel } : {}),
384
+ },
385
+ });
539
386
 
540
- /**
541
- * Decorator for defining model classes in AD4M.
542
- *
543
- * @category Decorators
544
- *
545
- * @description
546
- * The root decorator that must be applied to any class that represents a model in AD4M.
547
- * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure
548
- * for storing and retrieving instances.
549
- *
550
- * This decorator:
551
- * - 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.)
554
- * - Provides static query methods through the Ad4mModel base class
555
- *
556
- * @example
557
- * ```typescript
558
- * @ModelOptions({ name: "Recipe" })
559
- * class Recipe extends Ad4mModel {
560
- * @Property({
561
- * through: "recipe://name",
562
- * resolveLanguage: "literal"
563
- * })
564
- * name: string = "";
565
- *
566
- * @Collection({ through: "recipe://ingredient" })
567
- * ingredients: string[] = [];
568
- *
569
- * // Static query methods from Ad4mModel:
570
- * static async findByName(perspective: PerspectiveProxy, name: string) {
571
- * return Recipe.query(perspective)
572
- * .where({ name })
573
- * .run();
574
- * }
575
- * }
576
- *
577
- * // Using the model:
578
- * const recipe = new Recipe(perspective);
579
- * recipe.name = "Chocolate Cake";
580
- * await recipe.save();
581
- *
582
- * // Querying instances:
583
- * const recipes = await Recipe.query(perspective)
584
- * .where({ name: "Chocolate Cake" })
585
- * .run();
586
- *
587
- * // Using with PerspectiveProxy:
588
- * await perspective.ensureSDNASubjectClass(Recipe);
589
- * ```
590
- *
591
- * @param {ModelOptionsOptions} opts - Model configuration
592
- * @param {string} opts.name - Unique name for the model class in AD4M
593
- */
594
- export function ModelOptions(opts: ModelOptionsOptions) {
595
- return function (target: any) {
596
- target.prototype.className = opts.name;
597
- target.className = opts.name;
598
-
599
- target.generateSDNA = function() {
600
- let sdna = ""
601
- let subjectName = opts.name
602
- let obj = target.prototype;
603
-
604
- let uuid = makeRandomPrologAtom(8)
605
-
606
- sdna += `subject_class("${subjectName}", ${uuid}).\n`
607
-
608
-
609
- let classRemoverActions = []
610
-
611
- let constructorActions = []
612
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
613
- constructorActions = constructorActions.concat(obj.subjectConstructor)
614
- }
615
-
616
- let instanceConditions = []
617
- if(obj.isSubjectInstance && obj.isSubjectInstance.length) {
618
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance)
619
- }
620
-
621
- let propertiesCode = []
622
- let properties = obj.__properties || {}
623
- for(let property in properties) {
624
- let propertyCode = `property(${uuid}, "${property}").\n`
625
-
626
- let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property]
627
-
628
- if(resolveLanguage) {
629
- propertyCode += `property_resolve(${uuid}, "${property}").\n`
630
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
631
- }
632
-
633
- if(prologGetter) {
634
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`
635
- } else if(through) {
636
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
637
-
638
- if(required) {
639
- if(flag) {
640
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`)
641
- } else {
642
- instanceConditions.push(`triple(Base, "${through}", _)`)
643
- }
644
- }
645
- }
646
-
647
- if(prologSetter) {
648
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`
649
- } else if (writable && through) {
650
- let setter = obj[propertyNameToSetterName(property)]
651
- if(typeof setter === "function") {
652
- let action = [{
653
- action: "setSingleTarget",
654
- source: "this",
655
- predicate: through,
656
- target: "value",
657
- ...(local && { local: true })
658
- }]
659
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`
660
- }
661
- }
662
-
663
- propertiesCode.push(propertyCode)
664
-
665
- if(initial) {
666
- constructorActions.push({
667
- action: "addLink",
668
- source: "this",
669
- predicate: through,
670
- target: initial,
671
- })
672
-
673
- classRemoverActions.push({
674
- action: "removeLink",
675
- source: "this",
676
- predicate: through,
677
- target: "*",
678
- })
679
- }
680
- }
681
-
682
- let collectionsCode = []
683
- let collections = obj.__collections || {}
684
- for(let collection in collections) {
685
- let collectionCode = `collection(${uuid}, "${collection}").\n`
686
-
687
- let { through, where, local} = collections[collection]
688
-
689
- 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
- }
723
-
724
- let collectionAdderAction = [{
725
- action: "addLink",
726
- source: "this",
727
- predicate: through,
728
- target: "value",
729
- ...(local && { local: true })
730
- }]
731
-
732
- let collectionRemoverAction = [{
733
- action: "removeLink",
734
- source: "this",
735
- predicate: through,
736
- target: "value",
737
- }]
738
-
739
- let collectionSetterAction = [{
740
- action: "collectionSetter",
741
- source: "this",
742
- predicate: through,
743
- target: "value",
744
- ...(local && { local: true })
745
- }]
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`
749
- }
750
-
751
- collectionsCode.push(collectionCode)
752
- }
753
-
754
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions)
755
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`
756
- if(instanceConditions.length > 0) {
757
- let instanceConditionProlog = instanceConditions.join(", ")
758
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`
759
- sdna += "\n"
760
- }
761
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`
762
- sdna += "\n"
763
- sdna += propertiesCode.join("\n")
764
- sdna += "\n"
765
- sdna += collectionsCode.join("\n")
766
-
767
- return {
768
- sdna,
769
- name: subjectName
770
- }
771
- }
387
+ const value = key as string;
388
+ target[`add${capitalize(value)}`] = () => {};
389
+ target[`remove${capitalize(value)}`] = () => {};
390
+ target[`set${capitalize(value)}`] = () => {};
772
391
 
773
- // Generate SHACL shape (W3C standard + AD4M action definitions)
774
- target.generateSHACL = function() {
775
- const subjectName = opts.name;
776
- const obj = target.prototype;
777
-
778
- // Determine namespace from first property or collection, or use default
779
- let namespace = "ad4m://";
780
- const properties = obj.__properties || {};
781
- const collections = obj.__collections || {};
782
-
783
- // Try properties first
784
- if (Object.keys(properties).length > 0) {
785
- const firstProp = properties[Object.keys(properties)[0]];
786
- if (firstProp.through) {
787
- // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
788
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
789
- if (match) {
790
- namespace = match[1];
791
- }
792
- }
793
- }
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(/^([^:]+:\/\/)/);
799
- if (match) {
800
- namespace = match[1];
801
- }
802
- }
803
- }
804
-
805
- // Create SHACL shape
806
- const shapeUri = `${namespace}${subjectName}Shape`;
807
- const targetClass = `${namespace}${subjectName}`;
808
- const shape = new SHACLShape(shapeUri, targetClass);
809
-
810
- // === Extract Constructor Actions (same logic as generateSDNA) ===
811
- let constructorActions = [];
812
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
813
- constructorActions = constructorActions.concat(obj.subjectConstructor);
814
- }
815
-
816
- // === Extract Destructor Actions ===
817
- let destructorActions = [];
818
-
819
- // Convert properties to SHACL property shapes
820
- for (const propName in properties) {
821
- const propMeta = properties[propName];
822
-
823
- if (!propMeta.through) continue; // Skip properties without predicates
824
-
825
- const propShape: SHACLPropertyShape = {
826
- name: propName, // Property name for generating named URIs
827
- path: propMeta.through,
828
- };
829
-
830
- // Determine datatype from initial value or resolveLanguage
831
- if (propMeta.resolveLanguage === "literal") {
832
- // If it resolves via literal language, it's likely a string
833
- propShape.datatype = "xsd://string";
834
- } else if (propMeta.initial) {
835
- // Try to infer from initial value type
836
- const initialType = typeof obj[propName];
837
- if (initialType === "number") {
838
- propShape.datatype = "xsd://integer";
839
- } else if (initialType === "boolean") {
840
- propShape.datatype = "xsd://boolean";
841
- } else if (initialType === "string") {
842
- propShape.datatype = "xsd://string";
843
- }
844
- }
845
-
846
- // Cardinality constraints
847
- if (propMeta.required) {
848
- propShape.minCount = 1;
849
- }
850
-
851
- // Single-valued properties get maxCount 1
852
- // (collections are handled separately below)
853
- if (!propMeta.collection) {
854
- propShape.maxCount = 1;
855
- }
856
-
857
- // Flag properties have fixed value
858
- if (propMeta.flag && propMeta.initial) {
859
- propShape.hasValue = propMeta.initial;
860
- }
861
-
862
- // AD4M-specific metadata
863
- if (propMeta.local !== undefined) {
864
- propShape.local = propMeta.local;
865
- }
866
-
867
- if (propMeta.writable !== undefined) {
868
- propShape.writable = propMeta.writable;
869
- }
870
-
871
- if (propMeta.resolveLanguage) {
872
- propShape.resolveLanguage = propMeta.resolveLanguage;
873
- }
874
-
875
- // === Extract Setter Actions (same logic as generateSDNA) ===
876
- if (propMeta.setter) {
877
- // Custom setter defined - not yet supported in SHACL
878
- console.warn(
879
- `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
880
- `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
881
- );
882
- // TODO: Parse custom Prolog setter to extract actions
883
- } else if (propMeta.writable && propMeta.through) {
884
- let setter = obj[propertyNameToSetterName(propName)];
885
- if (typeof setter === "function") {
886
- propShape.setter = [{
887
- action: "setSingleTarget",
888
- source: "this",
889
- predicate: propMeta.through,
890
- target: "value",
891
- ...(propMeta.local && { local: true })
892
- }];
893
- }
894
- }
895
-
896
- // Add to constructor actions if property has initial value
897
- if (propMeta.initial) {
898
- constructorActions.push({
899
- action: "addLink",
900
- source: "this",
901
- predicate: propMeta.through,
902
- target: propMeta.initial,
903
- });
904
-
905
- // Add to destructor actions
906
- destructorActions.push({
907
- action: "removeLink",
908
- source: "this",
909
- predicate: propMeta.through,
910
- target: "*",
911
- });
912
- }
913
-
914
- shape.addProperty(propShape);
915
- }
916
-
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];
921
-
922
- if (!collMeta.through) continue;
923
-
924
- const collShape: SHACLPropertyShape = {
925
- name: collName, // Collection name for generating named URIs
926
- path: collMeta.through,
927
- // Collections have no maxCount (unlimited)
928
- // minCount defaults to 0 (optional)
929
- };
930
-
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
- }
942
-
943
- // AD4M-specific metadata
944
- if (collMeta.local !== undefined) {
945
- collShape.local = collMeta.local;
946
- }
947
-
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 = [{
955
- action: "addLink",
956
- source: "this",
957
- predicate: collMeta.through,
958
- target: "value",
959
- ...(collMeta.local && { local: true })
960
- }];
961
-
962
- // Remover action - removes a link from the collection
963
- collShape.remover = [{
964
- action: "removeLink",
965
- source: "this",
966
- predicate: collMeta.through,
967
- target: "value",
968
- ...(collMeta.local && { local: true })
969
- }];
970
-
971
- shape.addProperty(collShape);
972
- }
973
-
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
- }
981
-
982
- return {
983
- shape,
984
- name: subjectName
985
- };
986
- }
392
+ Object.defineProperty(target, key, { configurable: true, writable: true });
393
+ };
394
+ }
987
395
 
988
- Object.defineProperty(target, 'type', {configurable: true});
396
+ export function BelongsToOne(relatedModel: () => any, opts: RelationOptions) {
397
+ return function <T>(target: T, key: keyof T) {
398
+ if (!opts?.through) {
399
+ throw new Error(
400
+ `@BelongsToOne on "${String(key)}" requires a "through" predicate in RelationOptions`,
401
+ );
989
402
  }
403
+ const _b2oExisting =
404
+ relationRegistry.get((target as any).constructor) ?? {};
405
+ relationRegistry.set((target as any).constructor, {
406
+ ..._b2oExisting,
407
+ [key as string]: {
408
+ ...opts,
409
+ direction: "reverse" as const,
410
+ maxCount: 1,
411
+ relatedModel,
412
+ },
413
+ });
414
+
415
+ Object.defineProperty(target, key, { configurable: true, writable: true });
416
+ };
990
417
  }
991
418
 
992
- /**
993
- * Decorator for defining required and writable properties on model classes.
994
- *
995
- * @category Decorators
996
- *
997
- * @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`.
1000
- *
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
1005
- *
1006
- * @example
1007
- * ```typescript
1008
- * class User extends Ad4mModel {
1009
- * // Basic required property with default initial value
1010
- * @Property({
1011
- * through: "user://name"
1012
- * })
1013
- * name: string = "";
1014
- *
1015
- * // Required property with custom initial value
1016
- * @Property({
1017
- * through: "user://status",
1018
- * initial: "user://active"
1019
- * })
1020
- * status: string = "";
1021
- *
1022
- * // Required property with literal resolution
1023
- * @Property({
1024
- * through: "user://bio",
1025
- * resolveLanguage: "literal"
1026
- * })
1027
- * 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
- * }
1037
- * ```
1038
- *
1039
- * @param {PropertyOptions} opts - Property configuration
1040
- * @param {string} opts.through - The predicate URI for the property
1041
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
1042
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
1043
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
1044
- * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
1045
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
1046
- */
1047
- export function Property(opts: PropertyOptions) {
1048
- return Optional({
1049
- ...opts,
1050
- required: true,
1051
- writable: true,
1052
- initial: opts.initial || "literal://string:uninitialized"
419
+ export function BelongsToMany(relatedModel: () => any, opts: RelationOptions) {
420
+ return function <T>(target: T, key: keyof T) {
421
+ if (!opts?.through) {
422
+ throw new Error(
423
+ `@BelongsToMany on "${String(key)}" requires a "through" predicate in RelationOptions`,
424
+ );
425
+ }
426
+ const _b2mExisting =
427
+ relationRegistry.get((target as any).constructor) ?? {};
428
+ relationRegistry.set((target as any).constructor, {
429
+ ..._b2mExisting,
430
+ [key as string]: { ...opts, direction: "reverse" as const, relatedModel },
1053
431
  });
432
+
433
+ Object.defineProperty(target, key, { configurable: true, writable: true });
434
+ };
435
+ }
436
+
437
+ export function makeRandomId(length: number): string {
438
+ let result = "";
439
+ let characters = "abcdefghijklmnopqrstuvwxyz";
440
+ let charactersLength = characters.length;
441
+ for (let i = 0; i < length; i++) {
442
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
443
+ }
444
+ return result;
445
+ }
446
+
447
+ export interface ModelConfig {
448
+ /**
449
+ * The name of the entity.
450
+ */
451
+ name: string;
1054
452
  }
1055
453
 
1056
454
  /**
1057
- * Decorator for defining read-only properties on model classes.
1058
- *
1059
- * @category Decorators
1060
- *
1061
- * @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`.
1064
- *
1065
- * Read-only properties are ideal for:
1066
- * - Computed or derived values
1067
- * - Properties that should never change after creation
1068
- * - Properties that are set by the system
1069
- * - Properties that represent immutable data
1070
- *
455
+ * Registers the class as an AD4M SDNA subject, enabling `Ad4mModel` static query methods.
456
+ *
457
+ * Must be applied to every class that extends `Ad4mModel`.
458
+ *
1071
459
  * @example
1072
460
  * ```typescript
1073
- * class Post extends Ad4mModel {
1074
- * // Read-only property with custom getter for computed value
1075
- * @ReadOnly({
1076
- * through: "post://likes",
1077
- * getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
1078
- * })
1079
- * likeCount: number = 0;
1080
- *
1081
- * // Read-only property for creation timestamp
1082
- * @ReadOnly({
1083
- * through: "post://created_at",
1084
- * initial: new Date().toISOString()
1085
- * })
1086
- * createdAt: string = "";
1087
- *
1088
- * // Read-only property that resolves to a Literal
1089
- * @ReadOnly({
1090
- * through: "post://author",
1091
- * resolveLanguage: "literal"
1092
- * })
1093
- * author: string = "";
1094
- *
1095
- * // Read-only property for system-managed data
1096
- * @ReadOnly({
1097
- * through: "post://version",
1098
- * initial: "1.0.0"
1099
- * })
1100
- * version: string = "";
1101
- * }
461
+ * @Model({ name: "Recipe" })
462
+ * class Recipe extends Ad4mModel { ... }
1102
463
  * ```
1103
- *
1104
- * @param {PropertyOptions} opts - Property configuration
1105
- * @param {string} opts.through - The predicate URI for the property
1106
- * @param {string} [opts.initial] - Initial value (if property should have one)
1107
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
1108
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
1109
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
1110
464
  */
1111
- export function ReadOnly(opts: PropertyOptions) {
1112
- return Optional({
1113
- ...opts,
1114
- writable: false
1115
- });
1116
- }
465
+ export function Model(opts: ModelConfig) {
466
+ return function (target: any) {
467
+ target.prototype.className = opts.name;
468
+ target.className = opts.name;
469
+
470
+ // Generate SHACL shape (W3C standard + AD4M action definitions)
471
+ target.generateSHACL = function () {
472
+ const subjectName = opts.name;
473
+ const obj = target.prototype;
474
+
475
+ // Determine namespace from first property or relation, or use default
476
+ let namespace = "ad4m://";
477
+ const fields = getPropertiesMetadata(target);
478
+ const relations = getRelationsMetadata(target);
479
+
480
+ // Try fields first
481
+ if (Object.keys(fields).length > 0) {
482
+ const firstProp = fields[Object.keys(fields)[0]];
483
+ if (firstProp.through) {
484
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
485
+ if (match) {
486
+ namespace = match[1];
487
+ }
488
+ }
489
+ }
490
+ // Fall back to relations if no fields
491
+ else if (Object.keys(relations).length > 0) {
492
+ const firstRelation = relations[Object.keys(relations)[0]];
493
+ if (firstRelation.through) {
494
+ const match = firstRelation.through.match(/^([^:]+:\/\/)/);
495
+ if (match) {
496
+ namespace = match[1];
497
+ }
498
+ }
499
+ }
500
+
501
+ // Create SHACL shape
502
+ const shapeUri = `${namespace}${subjectName}Shape`;
503
+ const targetClass = `${namespace}${subjectName}`;
504
+ const shape = new SHACLShape(shapeUri, targetClass);
505
+
506
+ // ── Detect @Model parent for sh:node inheritance ──────────────────────
507
+ // If the immediate prototype constructor is also @Model-decorated,
508
+ // emit sh:node <ParentShape> and use only OWN properties/relations
509
+ // rather than duplicating the parent's properties in the child shape.
510
+ const parentCtor = Object.getPrototypeOf(target);
511
+ const parentClassName: string | undefined =
512
+ parentCtor?.prototype?.className;
513
+ const isParentModel =
514
+ parentClassName &&
515
+ parentClassName !== "Ad4mModel" &&
516
+ (propertyRegistry.has(parentCtor) || relationRegistry.has(parentCtor));
517
+
518
+ let shapeFields: Record<string, any>;
519
+ let shapeRelations: Record<string, any>;
520
+ if (isParentModel) {
521
+ // Own-only fields/relations — parent's are covered by sh:node
522
+ shapeFields = propertyRegistry.get(target) ?? {};
523
+ shapeRelations = relationRegistry.get(target) ?? {};
524
+
525
+ // Derive parent shape URI from parent's own properties' namespace
526
+ const parentOwnFields = Object.values(
527
+ propertyRegistry.get(parentCtor) ?? {},
528
+ ) as any[];
529
+ const parentOwnRelations = Object.values(
530
+ relationRegistry.get(parentCtor) ?? {},
531
+ ) as any[];
532
+ let parentNamespace = "ad4m://";
533
+ if (parentOwnFields.length > 0 && parentOwnFields[0].through) {
534
+ const m = (parentOwnFields[0].through as string).match(
535
+ /^([^:]+:\/\/)/,
536
+ );
537
+ if (m) parentNamespace = m[1];
538
+ } else if (
539
+ parentOwnRelations.length > 0 &&
540
+ parentOwnRelations[0].through
541
+ ) {
542
+ const m = (parentOwnRelations[0].through as string).match(
543
+ /^([^:]+:\/\/)/,
544
+ );
545
+ if (m) parentNamespace = m[1];
546
+ }
547
+ const parentShapeUri = `${parentNamespace}${parentClassName}Shape`;
548
+ shape.addParentShape(parentShapeUri);
549
+ } else {
550
+ // No @Model parent — include all inherited properties directly
551
+ shapeFields = fields;
552
+ shapeRelations = relations;
553
+ }
554
+ // ──────────────────────────────────────────────────────────────────────
555
+
556
+ // === Extract Constructor Actions (same logic as generateSDNA) ===
557
+ let constructorActions = [];
558
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
559
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
560
+ }
561
+
562
+ // === Extract Destructor Actions ===
563
+ let destructorActions = [];
564
+
565
+ // Convert fields to SHACL property shapes
566
+ for (const propName in shapeFields) {
567
+ const propMeta = shapeFields[propName];
568
+
569
+ if (!propMeta.through) continue; // Skip properties without predicates
570
+
571
+ const propShape: SHACLPropertyShape = {
572
+ name: propName, // Property name for generating named URIs
573
+ path: propMeta.through,
574
+ };
575
+
576
+ // Auto-derive a constructor placeholder for non-readOnly, non-flag properties
577
+ // that don't have an explicit initial. Only do this when the prototype
578
+ // has a defined default value — optional fields (title?: string) have
579
+ // no prototype default (undefined), and we must NOT write an empty
580
+ // literal link for them. The specific placeholder value doesn't matter
581
+ // for fields with an actual default — createSubject's initialValues
582
+ // mechanism overwrites it with the real value via the setter actions.
583
+ const protoDefault = obj[propName];
584
+ const effectiveInitial: string | undefined =
585
+ propMeta.initial ??
586
+ (!propMeta.readOnly && !propMeta.flag && protoDefault !== undefined
587
+ ? "literal://string:"
588
+ : undefined);
589
+
590
+ // Determine datatype from the TypeScript default value type.
591
+ // resolveLanguage: "literal" is now the implicit default — literal://
592
+ // URIs can carry any type (string/number/boolean), so always infer
593
+ // from the prototype's default value rather than forcing xsd://string.
594
+ const initialType = typeof obj[propName];
595
+ if (initialType === "number") {
596
+ propShape.datatype = "xsd://integer";
597
+ } else if (initialType === "boolean") {
598
+ propShape.datatype = "xsd://boolean";
599
+ } else if (initialType === "string") {
600
+ propShape.datatype = "xsd://string";
601
+ }
602
+
603
+ // Cardinality constraints
604
+ if (propMeta.required) {
605
+ propShape.minCount = 1;
606
+ }
607
+
608
+ // @Property fields are always single-valued; maxCount 1 is unconditional.
609
+ // Multi-valued relations live in relationRegistry and are handled below.
610
+ propShape.maxCount = 1;
611
+
612
+ // Flag properties have fixed value
613
+ if (propMeta.flag && propMeta.initial) {
614
+ propShape.hasValue = propMeta.initial;
615
+ }
616
+
617
+ // AD4M-specific metadata
618
+ if (propMeta.local !== undefined) {
619
+ propShape.local = propMeta.local;
620
+ }
621
+
622
+ if (propMeta.readOnly) {
623
+ propShape.readOnly = true;
624
+ }
625
+
626
+ if (propMeta.resolveLanguage) {
627
+ propShape.resolveLanguage = propMeta.resolveLanguage;
628
+ } else if (!propMeta.flag) {
629
+ // resolveLanguage: "literal" is the implicit default for scalar properties.
630
+ // The Rust executor requires this to be explicit in the SHACL shape to
631
+ // configure fn::parse_literal correctly in SurrealDB. The user doesn't
632
+ // need to write it in their @Property decorator, but the shape must have it.
633
+ propShape.resolveLanguage = "literal";
634
+ }
635
+
636
+ // === Extract Setter Actions (same logic as generateSDNA) ===
637
+ if (propMeta.setter) {
638
+ // Custom setter defined - not yet supported in SHACL
639
+ console.warn(
640
+ `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
641
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`,
642
+ );
643
+ // TODO: Parse custom Prolog setter to extract actions
644
+ } else if (!propMeta.readOnly && propMeta.through) {
645
+ let setter = obj[propertyNameToSetterName(propName)];
646
+ if (typeof setter === "function") {
647
+ propShape.setter = [
648
+ {
649
+ action: "setSingleTarget",
650
+ source: "this",
651
+ predicate: propMeta.through,
652
+ target: "value",
653
+ ...(propMeta.local && { local: true }),
654
+ },
655
+ ];
656
+ }
657
+ }
658
+
659
+ // Add to constructor actions (always for non-readOnly, non-flag, using the
660
+ // effective placeholder — createSubject's initialValues will override
661
+ // the target with the real instance value via the setter actions).
662
+ if (effectiveInitial) {
663
+ constructorActions.push({
664
+ action: "addLink",
665
+ source: "this",
666
+ predicate: propMeta.through,
667
+ target: effectiveInitial,
668
+ });
669
+ }
670
+
671
+ // Always add destructor action for non-readOnly, non-flag properties so
672
+ // delete() cleans them up regardless of whether initial was explicit.
673
+ if (!propMeta.readOnly && !propMeta.flag) {
674
+ destructorActions.push({
675
+ action: "removeLink",
676
+ source: "this",
677
+ predicate: propMeta.through,
678
+ target: "*",
679
+ });
680
+ }
681
+
682
+ shape.addProperty(propShape);
683
+ }
684
+
685
+ // Convert relations to SHACL property shapes
686
+ for (const relName in shapeRelations) {
687
+ const relMeta = shapeRelations[relName];
688
+
689
+ if (!relMeta.through) continue;
690
+
691
+ const relShape: SHACLPropertyShape = {
692
+ name: relName, // Relation name for generating named URIs
693
+ path: relMeta.through,
694
+ // Relations have no maxCount (unlimited)
695
+ // minCount defaults to 0 (optional)
696
+ };
697
+
698
+ // Relations contain references (IRIs) to other entities
699
+ relShape.nodeKind = "IRI";
700
+
701
+ // AD4M-specific metadata
702
+ if (relMeta.local !== undefined) {
703
+ relShape.local = relMeta.local;
704
+ }
705
+
706
+ // Relationship metadata
707
+ if (relMeta.maxCount !== undefined) {
708
+ relShape.maxCount = relMeta.maxCount;
709
+ }
710
+
711
+ if (relMeta.direction === "reverse") {
712
+ relShape.inversePath = true;
713
+ }
714
+
715
+ // === Extract Relation Actions (adder/remover) ===
716
+ // Adder action - adds a link to the relation
717
+ relShape.adder = [
718
+ {
719
+ action: "addLink",
720
+ source: "this",
721
+ predicate: relMeta.through,
722
+ target: "value",
723
+ ...(relMeta.local && { local: true }),
724
+ },
725
+ ];
726
+
727
+ // Remover action - removes a link from the relation
728
+ relShape.remover = [
729
+ {
730
+ action: "removeLink",
731
+ source: "this",
732
+ predicate: relMeta.through,
733
+ target: "value",
734
+ ...(relMeta.local && { local: true }),
735
+ },
736
+ ];
737
+
738
+ shape.addProperty(relShape);
739
+ }
740
+
741
+ // Set constructor and destructor actions on the shape.
742
+ // Always set constructor actions (even if empty) so the Rust SHACL parser
743
+ // emits an ad4m://constructor link — without it get_constructor_actions()
744
+ // throws "No SHACL constructor found" for classes with no @Flag or initial
745
+ // properties. An empty constructor is valid: it means "do nothing on creation".
746
+ shape.setConstructorActions(constructorActions);
747
+ if (destructorActions.length > 0) {
748
+ shape.setDestructorActions(destructorActions);
749
+ }
750
+
751
+ return {
752
+ shape,
753
+ name: subjectName,
754
+ };
755
+ };
756
+
757
+ Object.defineProperty(target, "type", { configurable: true });
758
+ };
759
+ }