@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,6 +1,75 @@
1
- import { Subject } from "./Subject";
2
- import { capitalize, propertyNameToSetterName, stringifyObjectLiteral } from "./util";
1
+ import { capitalize, propertyNameToSetterName, } from "./util";
3
2
  import { SHACLShape } from "../shacl/SHACLShape";
3
+ // Module-level WeakMaps keyed on the constructor function (not the prototype).
4
+ // Each class constructor is a unique key, so subclass decorators write into their
5
+ // own entry rather than the parent prototype's — preventing silent metadata corruption
6
+ // across inherited classes (e.g. BaseBlock and PollBlock stay independent).
7
+ export const propertyRegistry = new WeakMap();
8
+ export const relationRegistry = new WeakMap();
9
+ /** Returns the own + inherited property metadata for a given constructor, with own values winning. */
10
+ export function getPropertiesMetadata(ctor) {
11
+ if (!ctor)
12
+ return {};
13
+ const own = propertyRegistry.get(ctor) ?? {};
14
+ const parent = Object.getPrototypeOf(ctor);
15
+ if (!parent || parent === Function.prototype)
16
+ return own;
17
+ return { ...getPropertiesMetadata(parent), ...own };
18
+ }
19
+ /** Returns the own + inherited relation metadata for a given constructor, with own values winning. */
20
+ export function getRelationsMetadata(ctor) {
21
+ if (!ctor)
22
+ return {};
23
+ const own = relationRegistry.get(ctor) ?? {};
24
+ const parent = Object.getPrototypeOf(ctor);
25
+ if (!parent || parent === Function.prototype)
26
+ return own;
27
+ return { ...getRelationsMetadata(parent), ...own };
28
+ }
29
+ /**
30
+ * Builds a plain, JSON-safe object from a model instance.
31
+ *
32
+ * Only includes `id` (if present) and decorator-registered \@Property keys.
33
+ * All other own enumerable properties are stripped — most importantly the
34
+ * TypeScript `private _perspective` field which is stored as a regular
35
+ * enumerable property at runtime and holds a PerspectiveProxy whose Apollo
36
+ * InMemoryCache creates a circular reference in `JSON.stringify`.
37
+ *
38
+ * Falls back to a shallow spread for plain objects with no registered props
39
+ * (e.g. raw link objects passed through before model hydration).
40
+ */
41
+ export function instanceToSerializable(instance) {
42
+ if (!instance || typeof instance !== "object")
43
+ return {};
44
+ const ctor = Object.getPrototypeOf(instance)?.constructor;
45
+ const registeredProps = ctor ? getPropertiesMetadata(ctor) : null;
46
+ const registeredRels = ctor ? getRelationsMetadata(ctor) : null;
47
+ const propKeys = registeredProps ? Object.keys(registeredProps) : null;
48
+ const relKeys = registeredRels ? Object.keys(registeredRels) : null;
49
+ const allKeys = (propKeys ?? relKeys) ? [...(propKeys ?? []), ...(relKeys ?? [])] : null;
50
+ if (!allKeys || allKeys.length === 0) {
51
+ // Plain object / no @Property decorators — safe to spread.
52
+ return { ...instance };
53
+ }
54
+ const obj = {};
55
+ if (instance.id !== undefined) {
56
+ obj.id = instance.id;
57
+ }
58
+ for (const key of allKeys) {
59
+ const val = instance[key];
60
+ // For relation arrays containing model instances, serialize only their IDs
61
+ // to avoid circular references and keep the fingerprint lightweight.
62
+ if (Array.isArray(val)) {
63
+ obj[key] = val.map((item) => item && typeof item === "object" && item.id !== undefined
64
+ ? item.id
65
+ : item);
66
+ }
67
+ else {
68
+ obj[key] = val;
69
+ }
70
+ }
71
+ return obj;
72
+ }
4
73
  export class PerspectiveAction {
5
74
  }
6
75
  export function addLink(source, predicate, target) {
@@ -15,202 +84,29 @@ export function hasLink(predicate) {
15
84
  return `triple(this, "${predicate}", _)`;
16
85
  }
17
86
  /**
18
- * Decorator for querying instances of a model class.
19
- *
20
- * @category Decorators
21
- *
22
- * @description
23
- * Allows you to define static query methods on your model class to retrieve instances based on custom conditions.
24
- * This decorator can only be applied to static async methods that return a Promise of an array of model instances.
25
- *
26
- * The query can be constrained using either:
27
- * - A `where` clause that matches property values
28
- * - A custom Prolog `condition` for more complex queries
29
- *
30
- * @example
31
- * ```typescript
32
- * class Recipe extends Ad4mModel {
33
- * @Property({ through: "recipe://name" })
34
- * name: string = "";
35
- *
36
- * @Property({ through: "recipe://rating" })
37
- * rating: number = 0;
38
- *
39
- * // Get all recipes
40
- * @InstanceQuery()
41
- * static async all(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
42
- *
43
- * // Get recipes by name
44
- * @InstanceQuery({ where: { name: "Chocolate Cake" }})
45
- * static async findByName(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
46
- *
47
- * // Get highly rated recipes using a custom condition
48
- * @InstanceQuery({ prologCondition: "triple(Instance, 'recipe://rating', Rating), Rating > 4" })
49
- * static async topRated(perspective: PerspectiveProxy): Promise<Recipe[]> { return [] }
50
- * }
51
- * ```
52
- *
53
- * @param {Object} [options] - Query options
54
- * @param {object} [options.where] - Object with property-value pairs to match
55
- * @param {string} [options.prologCondition] - Custom Prolog condition for more complex queries
87
+ * Declares a typed property backed by a single link triple in the perspective.
88
+ *
89
+ * @param opts.through - Predicate URI (required)
90
+ * @param opts.initial - Default value written by the constructor action (auto-derived for non-readOnly properties; only needed for custom URIs)
91
+ * @param opts.required - Adds `sh:minCount 1` to the SHACL shape
92
+ * @param opts.readOnly - Skips setter generation; property cannot be updated after creation (default: false)
93
+ * @param opts.resolveLanguage - Language for value resolution (`"literal"`, etc.)
94
+ * @param opts.local - Store only in local perspective, not shared with the network
95
+ * @param opts.getter - Custom SurrealQL expression for computed / read-only properties
96
+ * @param opts.transform - Post-fetch transform applied to the raw value
56
97
  */
57
- export function InstanceQuery(options) {
58
- return function (target, key, descriptor) {
59
- const originalMethod = descriptor.value;
60
- if (typeof originalMethod !== "function") {
61
- throw new Error("InstanceQuery decorator can only be applied to methods");
62
- }
63
- descriptor.value = async function (perspective) {
64
- let instances = [];
65
- //@ts-ignore
66
- let subjectClassName = target.name;
67
- let query = `subject_class("${subjectClassName}", C), instance(C, Instance)`;
68
- if (options && options.where) {
69
- for (let prop in options.where) {
70
- let value = options.where[prop];
71
- query += `, property_getter(C, Instance, "${prop}", "${value}")`;
72
- }
73
- }
74
- if (options && options.prologCondition) {
75
- query += ', ' + options.prologCondition;
76
- }
77
- // Try Prolog first
78
- try {
79
- let results = await perspective.infer(query);
80
- if (results && results !== false && typeof results !== "string" && results.length > 0) {
81
- for (let result of results) {
82
- let instance = result.Instance;
83
- let subject = new Subject(perspective, instance, subjectClassName);
84
- await subject.init();
85
- instances.push(subject);
86
- }
87
- return instances;
88
- }
89
- }
90
- catch (e) {
91
- // Prolog failed, fall through to SurrealDB
92
- }
93
- // Fallback to SurrealDB (SdnaOnly mode)
94
- // Get all instances first - pass the class constructor, not just the name
95
- let allInstances = await perspective.getAllSubjectInstances(target);
96
- // Filter by where clause if provided
97
- if (options && options.where) {
98
- let filtered = [];
99
- for (let instance of allInstances) {
100
- let matches = true;
101
- for (let prop in options.where) {
102
- let expectedValue = options.where[prop];
103
- //@ts-ignore
104
- let actualValue = await instance[prop];
105
- if (actualValue !== expectedValue) {
106
- matches = false;
107
- break;
108
- }
109
- }
110
- if (matches) {
111
- filtered.push(instance);
112
- }
113
- }
114
- return filtered;
115
- }
116
- return allInstances;
117
- };
118
- };
119
- }
120
- /**
121
- * Decorator for defining optional properties on model classes.
122
- *
123
- * @category Decorators
124
- *
125
- * @description
126
- * The most flexible property decorator that allows you to define properties with full control over:
127
- * - Whether the property is required
128
- * - Whether the property is writable
129
- * - How values are stored and retrieved
130
- * - Custom getter/setter logic
131
- * - Local vs network storage
132
- *
133
- * Both @Property and @ReadOnly are specialized versions of @Optional with preset configurations.
134
- *
135
- * @example
136
- * ```typescript
137
- * class Recipe extends Ad4mModel {
138
- * // Basic optional property
139
- * @Optional({
140
- * through: "recipe://description"
141
- * })
142
- * description?: string;
143
- *
144
- * // Optional property with custom initial value
145
- * @Optional({
146
- * through: "recipe://status",
147
- * initial: "recipe://draft",
148
- * required: true
149
- * })
150
- * status: string = "";
151
- *
152
- * // Read-only property with custom getter
153
- * @Optional({
154
- * through: "recipe://rating",
155
- * writable: false,
156
- * getter: `
157
- * findall(Rating, triple(Base, "recipe://user_rating", Rating), Ratings),
158
- * sum_list(Ratings, Sum),
159
- * length(Ratings, Count),
160
- * Value is Sum / Count
161
- * `
162
- * })
163
- * averageRating: number = 0;
164
- *
165
- * // Property that resolves to a Literal and is stored locally
166
- * @Optional({
167
- * through: "recipe://notes",
168
- * resolveLanguage: "literal",
169
- * local: true
170
- * })
171
- * notes?: string;
172
- *
173
- * // Property with custom getter and setter logic
174
- * @Optional({
175
- * through: "recipe://ingredients",
176
- * getter: `
177
- * triple(Base, "recipe://ingredients", RawValue),
178
- * atom_json_term(RawValue, Value)
179
- * `,
180
- * setter: `
181
- * atom_json_term(Value, JsonValue),
182
- * Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "recipe://ingredients", "target": JsonValue}]
183
- * `
184
- * })
185
- * ingredients: string[] = [];
186
- * }
187
- * ```
188
- *
189
- * @param {PropertyOptions} opts - Property configuration options
190
- * @param {string} opts.through - The predicate URI for the property
191
- * @param {string} [opts.initial] - Initial value (required if property is required)
192
- * @param {boolean} [opts.required] - Whether the property must have a value
193
- * @param {boolean} [opts.writable=true] - Whether the property can be modified
194
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
195
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
196
- * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
197
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
198
- */
199
- export function Optional(opts) {
98
+ export function Property(opts) {
200
99
  return function (target, key) {
201
- if (typeof opts.writable === "undefined" && opts.through) {
202
- opts.writable = true;
203
- }
204
- if (opts.required && !opts.initial) {
205
- throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
206
- }
207
- if (!opts.through && !opts.prologGetter) {
208
- throw new Error("SubjectProperty requires either 'through' or 'prologGetter' option");
100
+ if (!opts.through) {
101
+ throw new Error("@Property requires a 'through' option");
209
102
  }
210
- target["__properties"] = target["__properties"] || {};
211
- target["__properties"][key] = target["__properties"][key] || {};
212
- target["__properties"][key] = { ...target["__properties"][key], ...opts };
213
- if (opts.writable) {
103
+ const _propertyExisting = propertyRegistry.get(target.constructor) ?? {};
104
+ const _propertyExistingKey = _propertyExisting[key] ?? {};
105
+ propertyRegistry.set(target.constructor, {
106
+ ..._propertyExisting,
107
+ [key]: { ..._propertyExistingKey, ...opts },
108
+ });
109
+ if (!opts.readOnly) {
214
110
  const value = key;
215
111
  target[`set${capitalize(value)}`] = () => { };
216
112
  }
@@ -218,57 +114,16 @@ export function Optional(opts) {
218
114
  };
219
115
  }
220
116
  /**
221
- * Decorator for defining flags on model classes.
222
- *
223
- * @category Decorators
224
- *
225
- * @description
226
- * A specialized property decorator for defining immutable type flags or markers on model instances.
227
- * Flags are always required properties with a fixed value that cannot be changed after creation.
228
- *
229
- * Common uses for flags:
230
- * - Type discrimination between different kinds of models
231
- * - Marking models with specific capabilities or features
232
- * - Versioning or compatibility markers
117
+ * Immutable type-marker property: written once at creation and never modified.
233
118
  *
234
- * Note: Use of Flag is discouraged unless you specifically need type-based filtering or
235
- * discrimination between different kinds of models. For most cases, regular properties
236
- * with @Property or @Optional are more appropriate.
119
+ * Use for type-discrimination predicates (e.g. `ad4m://type = "ad4m://message"`).
120
+ * For mutable data prefer `@Property`.
237
121
  *
238
122
  * @example
239
123
  * ```typescript
240
- * class Message extends Ad4mModel {
241
- * // Type flag to identify message models
242
- * @Flag({
243
- * through: "ad4m://type",
244
- * value: "ad4m://message"
245
- * })
246
- * type: string = "";
247
- *
248
- * // Version flag for compatibility
249
- * @Flag({
250
- * through: "ad4m://version",
251
- * value: "1.0.0"
252
- * })
253
- * version: string = "";
254
- *
255
- * // Feature flag
256
- * @Flag({
257
- * through: "message://feature",
258
- * value: "message://encrypted"
259
- * })
260
- * feature: string = "";
261
- * }
262
- *
263
- * // Later you can query for specific types:
264
- * const messages = await Message.query(perspective)
265
- * .where({ type: "ad4m://message" })
266
- * .run();
124
+ * @Flag({ through: "ad4m://type", value: "ad4m://message" })
125
+ * type: string = "";
267
126
  * ```
268
- *
269
- * @param {FlagOptions} opts - Flag configuration
270
- * @param {string} opts.through - The predicate URI for the flag
271
- * @param {string} opts.value - The fixed value for the flag
272
127
  */
273
128
  export function Flag(opts) {
274
129
  return function (target, key) {
@@ -281,106 +136,104 @@ export function Flag(opts) {
281
136
  if (!opts.value) {
282
137
  throw new Error("SubjectFlag requires a 'value' option");
283
138
  }
284
- target["__properties"] = target["__properties"] || {};
285
- target["__properties"][key] = target["__properties"][key] || {};
286
- target["__properties"][key] = {
287
- ...target["__properties"][key],
288
- through: opts.through,
289
- required: true,
290
- initial: opts.value,
291
- flag: true
292
- };
139
+ const _flagExisting = propertyRegistry.get(target.constructor) ?? {};
140
+ propertyRegistry.set(target.constructor, {
141
+ ..._flagExisting,
142
+ [key]: {
143
+ ...(_flagExisting[key] ?? {}),
144
+ through: opts.through,
145
+ required: true,
146
+ initial: opts.value,
147
+ flag: true,
148
+ readOnly: true, // Flags are always immutable after creation
149
+ },
150
+ });
293
151
  // @ts-ignore
294
152
  target[key] = opts.value;
295
153
  Object.defineProperty(target, key, { configurable: true, writable: true });
296
154
  };
297
155
  }
298
- /**
299
- * Decorator for defining collections on model classes.
300
- *
301
- * @category Decorators
302
- *
303
- * @description
304
- * Defines a property that represents a collection of values linked to the model instance.
305
- * Collections are always arrays and support operations for adding, removing, and setting values.
306
- *
307
- * For each collection property, the following methods are automatically generated:
308
- * - `addX(value)` - Add a value to the collection
309
- * - `removeX(value)` - Remove a value from the collection
310
- * - `setCollectionX(values)` - Replace all values in the collection
311
- *
312
- * Where X is the capitalized property name.
313
- *
314
- * Collections can be filtered using the `where` option to only include values that:
315
- * - Are instances of a specific model class
316
- * - Match a custom Prolog condition
317
- *
318
- * @example
319
- * ```typescript
320
- * class Recipe extends Ad4mModel {
321
- * // Basic collection of ingredients
322
- * @Collection({
323
- * through: "recipe://ingredient"
324
- * })
325
- * ingredients: string[] = [];
326
- *
327
- * // Collection that only includes instances of another model
328
- * @Collection({
329
- * through: "recipe://comment",
330
- * where: { isInstance: Comment }
331
- * })
332
- * comments: string[] = [];
333
- *
334
- * // Collection with custom Prolog filter condition
335
- * @Collection({
336
- * through: "recipe://step",
337
- * where: { prologCondition: `triple(Target, "step://order", Order), Order < 3` }
338
- * })
339
- * firstSteps: string[] = [];
340
- *
341
- * // Collection with custom SurrealDB filter condition
342
- * @Collection({
343
- * through: "recipe://entries",
344
- * where: { condition: `WHERE in.uri = Target AND predicate = 'recipe://has_ingredient' AND out.uri = 'recipe://test')`
345
- * })
346
- * ingredients: string[] = [];
347
- *
348
- * // Local-only collection not shared with network
349
- * @Collection({
350
- * through: "recipe://note",
351
- * local: true
352
- * })
353
- * privateNotes: string[] = [];
354
- * }
355
- *
356
- * // Using the generated methods:
357
- * const recipe = new Recipe(perspective);
358
- * await recipe.addIngredients("ingredient://flour");
359
- * await recipe.removeIngredients("ingredient://sugar");
360
- * await recipe.setCollectionIngredients(["ingredient://butter", "ingredient://eggs"]);
361
- * ```
362
- *
363
- * @param {CollectionOptions} opts - Collection configuration
364
- * @param {string} opts.through - The predicate URI for collection links
365
- * @param {WhereOptions} [opts.where] - Filter conditions for collection values
366
- * @param {any} [opts.where.isInstance] - Model class to filter instances by
367
- * @param {string} [opts.where.prologCondition] - Custom Prolog condition for filtering
368
- * @param {boolean} [opts.local] - Whether collection links are stored locally only
369
- */
370
- export function Collection(opts) {
156
+ export function HasMany(relatedModelOrOpts, opts) {
157
+ const resolvedOpts = typeof relatedModelOrOpts === "function" ? opts : relatedModelOrOpts;
158
+ const relatedModel = typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
371
159
  return function (target, key) {
372
- target["__collections"] = target["__collections"] || {};
373
- target["__collections"][key] = opts;
160
+ if (!resolvedOpts?.through) {
161
+ throw new Error(`@HasMany on "${String(key)}" requires a "through" predicate in RelationOptions`);
162
+ }
163
+ const _hasManyExisting = relationRegistry.get(target.constructor) ?? {};
164
+ relationRegistry.set(target.constructor, {
165
+ ..._hasManyExisting,
166
+ [key]: {
167
+ ...resolvedOpts,
168
+ direction: "forward",
169
+ ...(relatedModel ? { relatedModel } : {}),
170
+ },
171
+ });
374
172
  const value = key;
375
173
  target[`add${capitalize(value)}`] = () => { };
376
174
  target[`remove${capitalize(value)}`] = () => { };
377
- target[`setCollection${capitalize(value)}`] = () => { };
175
+ target[`set${capitalize(value)}`] = () => { };
378
176
  Object.defineProperty(target, key, { configurable: true, writable: true });
379
177
  };
380
178
  }
381
- export function makeRandomPrologAtom(length) {
382
- let result = '';
383
- let characters = 'abcdefghijklmnopqrstuvwxyz';
179
+ export function HasOne(relatedModelOrOpts, opts) {
180
+ const resolvedOpts = typeof relatedModelOrOpts === "function" ? opts : relatedModelOrOpts;
181
+ const relatedModel = typeof relatedModelOrOpts === "function" ? relatedModelOrOpts : undefined;
182
+ return function (target, key) {
183
+ if (!resolvedOpts?.through) {
184
+ throw new Error(`@HasOne on "${String(key)}" requires a "through" predicate in RelationOptions`);
185
+ }
186
+ const _hasOneExisting = relationRegistry.get(target.constructor) ?? {};
187
+ relationRegistry.set(target.constructor, {
188
+ ..._hasOneExisting,
189
+ [key]: {
190
+ ...resolvedOpts,
191
+ direction: "forward",
192
+ maxCount: 1,
193
+ ...(relatedModel ? { relatedModel } : {}),
194
+ },
195
+ });
196
+ const value = key;
197
+ target[`add${capitalize(value)}`] = () => { };
198
+ target[`remove${capitalize(value)}`] = () => { };
199
+ target[`set${capitalize(value)}`] = () => { };
200
+ Object.defineProperty(target, key, { configurable: true, writable: true });
201
+ };
202
+ }
203
+ export function BelongsToOne(relatedModel, opts) {
204
+ return function (target, key) {
205
+ if (!opts?.through) {
206
+ throw new Error(`@BelongsToOne on "${String(key)}" requires a "through" predicate in RelationOptions`);
207
+ }
208
+ const _b2oExisting = relationRegistry.get(target.constructor) ?? {};
209
+ relationRegistry.set(target.constructor, {
210
+ ..._b2oExisting,
211
+ [key]: {
212
+ ...opts,
213
+ direction: "reverse",
214
+ maxCount: 1,
215
+ relatedModel,
216
+ },
217
+ });
218
+ Object.defineProperty(target, key, { configurable: true, writable: true });
219
+ };
220
+ }
221
+ export function BelongsToMany(relatedModel, opts) {
222
+ return function (target, key) {
223
+ if (!opts?.through) {
224
+ throw new Error(`@BelongsToMany on "${String(key)}" requires a "through" predicate in RelationOptions`);
225
+ }
226
+ const _b2mExisting = relationRegistry.get(target.constructor) ?? {};
227
+ relationRegistry.set(target.constructor, {
228
+ ..._b2mExisting,
229
+ [key]: { ...opts, direction: "reverse", relatedModel },
230
+ });
231
+ Object.defineProperty(target, key, { configurable: true, writable: true });
232
+ };
233
+ }
234
+ export function makeRandomId(length) {
235
+ let result = "";
236
+ let characters = "abcdefghijklmnopqrstuvwxyz";
384
237
  let charactersLength = characters.length;
385
238
  for (let i = 0; i < length; i++) {
386
239
  result += characters.charAt(Math.floor(Math.random() * charactersLength));
@@ -388,238 +241,43 @@ export function makeRandomPrologAtom(length) {
388
241
  return result;
389
242
  }
390
243
  /**
391
- * Decorator for defining model classes in AD4M.
244
+ * Registers the class as an AD4M SDNA subject, enabling `Ad4mModel` static query methods.
392
245
  *
393
- * @category Decorators
394
- *
395
- * @description
396
- * The root decorator that must be applied to any class that represents a model in AD4M.
397
- * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure
398
- * for storing and retrieving instances.
399
- *
400
- * This decorator:
401
- * - Registers the class with a unique name in the AD4M system
402
- * - Generates the necessary SDNA code for the model's properties and collections
403
- * - Enables the use of other model decorators (@Property, @Collection, etc.)
404
- * - Provides static query methods through the Ad4mModel base class
246
+ * Must be applied to every class that extends `Ad4mModel`.
405
247
  *
406
248
  * @example
407
249
  * ```typescript
408
- * @ModelOptions({ name: "Recipe" })
409
- * class Recipe extends Ad4mModel {
410
- * @Property({
411
- * through: "recipe://name",
412
- * resolveLanguage: "literal"
413
- * })
414
- * name: string = "";
415
- *
416
- * @Collection({ through: "recipe://ingredient" })
417
- * ingredients: string[] = [];
418
- *
419
- * // Static query methods from Ad4mModel:
420
- * static async findByName(perspective: PerspectiveProxy, name: string) {
421
- * return Recipe.query(perspective)
422
- * .where({ name })
423
- * .run();
424
- * }
425
- * }
426
- *
427
- * // Using the model:
428
- * const recipe = new Recipe(perspective);
429
- * recipe.name = "Chocolate Cake";
430
- * await recipe.save();
431
- *
432
- * // Querying instances:
433
- * const recipes = await Recipe.query(perspective)
434
- * .where({ name: "Chocolate Cake" })
435
- * .run();
436
- *
437
- * // Using with PerspectiveProxy:
438
- * await perspective.ensureSDNASubjectClass(Recipe);
250
+ * @Model({ name: "Recipe" })
251
+ * class Recipe extends Ad4mModel { ... }
439
252
  * ```
440
- *
441
- * @param {ModelOptionsOptions} opts - Model configuration
442
- * @param {string} opts.name - Unique name for the model class in AD4M
443
253
  */
444
- export function ModelOptions(opts) {
254
+ export function Model(opts) {
445
255
  return function (target) {
446
256
  target.prototype.className = opts.name;
447
257
  target.className = opts.name;
448
- target.generateSDNA = function () {
449
- let sdna = "";
450
- let subjectName = opts.name;
451
- let obj = target.prototype;
452
- let uuid = makeRandomPrologAtom(8);
453
- sdna += `subject_class("${subjectName}", ${uuid}).\n`;
454
- let classRemoverActions = [];
455
- let constructorActions = [];
456
- if (obj.subjectConstructor && obj.subjectConstructor.length) {
457
- constructorActions = constructorActions.concat(obj.subjectConstructor);
458
- }
459
- let instanceConditions = [];
460
- if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
461
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
462
- }
463
- let propertiesCode = [];
464
- let properties = obj.__properties || {};
465
- for (let property in properties) {
466
- let propertyCode = `property(${uuid}, "${property}").\n`;
467
- let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
468
- if (resolveLanguage) {
469
- propertyCode += `property_resolve(${uuid}, "${property}").\n`;
470
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
471
- }
472
- if (prologGetter) {
473
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
474
- }
475
- else if (through) {
476
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
477
- if (required) {
478
- if (flag) {
479
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
480
- }
481
- else {
482
- instanceConditions.push(`triple(Base, "${through}", _)`);
483
- }
484
- }
485
- }
486
- if (prologSetter) {
487
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
488
- }
489
- else if (writable && through) {
490
- let setter = obj[propertyNameToSetterName(property)];
491
- if (typeof setter === "function") {
492
- let action = [{
493
- action: "setSingleTarget",
494
- source: "this",
495
- predicate: through,
496
- target: "value",
497
- ...(local && { local: true })
498
- }];
499
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
500
- }
501
- }
502
- propertiesCode.push(propertyCode);
503
- if (initial) {
504
- constructorActions.push({
505
- action: "addLink",
506
- source: "this",
507
- predicate: through,
508
- target: initial,
509
- });
510
- classRemoverActions.push({
511
- action: "removeLink",
512
- source: "this",
513
- predicate: through,
514
- target: "*",
515
- });
516
- }
517
- }
518
- let collectionsCode = [];
519
- let collections = obj.__collections || {};
520
- for (let collection in collections) {
521
- let collectionCode = `collection(${uuid}, "${collection}").\n`;
522
- let { through, where, local } = collections[collection];
523
- if (through) {
524
- if (where) {
525
- if (!where.isInstance && !where.prologCondition && !where.condition) {
526
- throw "'where' needs one of 'isInstance', 'prologCondition', or 'condition'";
527
- }
528
- let conditions = [];
529
- if (where.isInstance) {
530
- let otherClass;
531
- if (where.isInstance.name) {
532
- otherClass = where.isInstance.name;
533
- }
534
- else {
535
- otherClass = where.isInstance;
536
- }
537
- conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
538
- }
539
- if (where.prologCondition) {
540
- conditions.push(where.prologCondition);
541
- }
542
- // If there are Prolog conditions (isInstance or prologCondition), use setof with conditions
543
- // If only condition is present, use simple findall (SurrealDB will filter later)
544
- if (conditions.length > 0) {
545
- const conditionString = conditions.join(", ");
546
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
547
- }
548
- else {
549
- // Only SurrealDB condition present (no Prolog filtering)
550
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
551
- }
552
- }
553
- else {
554
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
555
- }
556
- let collectionAdderAction = [{
557
- action: "addLink",
558
- source: "this",
559
- predicate: through,
560
- target: "value",
561
- ...(local && { local: true })
562
- }];
563
- let collectionRemoverAction = [{
564
- action: "removeLink",
565
- source: "this",
566
- predicate: through,
567
- target: "value",
568
- }];
569
- let collectionSetterAction = [{
570
- action: "collectionSetter",
571
- source: "this",
572
- predicate: through,
573
- target: "value",
574
- ...(local && { local: true })
575
- }];
576
- collectionCode += `collection_adder(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`;
577
- collectionCode += `collection_remover(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`;
578
- collectionCode += `collection_setter(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`;
579
- }
580
- collectionsCode.push(collectionCode);
581
- }
582
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
583
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
584
- if (instanceConditions.length > 0) {
585
- let instanceConditionProlog = instanceConditions.join(", ");
586
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
587
- sdna += "\n";
588
- }
589
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
590
- sdna += "\n";
591
- sdna += propertiesCode.join("\n");
592
- sdna += "\n";
593
- sdna += collectionsCode.join("\n");
594
- return {
595
- sdna,
596
- name: subjectName
597
- };
598
- };
599
258
  // Generate SHACL shape (W3C standard + AD4M action definitions)
600
259
  target.generateSHACL = function () {
601
260
  const subjectName = opts.name;
602
261
  const obj = target.prototype;
603
- // Determine namespace from first property or collection, or use default
262
+ // Determine namespace from first property or relation, or use default
604
263
  let namespace = "ad4m://";
605
- const properties = obj.__properties || {};
606
- const collections = obj.__collections || {};
607
- // Try properties first
608
- if (Object.keys(properties).length > 0) {
609
- const firstProp = properties[Object.keys(properties)[0]];
264
+ const fields = getPropertiesMetadata(target);
265
+ const relations = getRelationsMetadata(target);
266
+ // Try fields first
267
+ if (Object.keys(fields).length > 0) {
268
+ const firstProp = fields[Object.keys(fields)[0]];
610
269
  if (firstProp.through) {
611
- // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
612
270
  const match = firstProp.through.match(/^([^:]+:\/\/)/);
613
271
  if (match) {
614
272
  namespace = match[1];
615
273
  }
616
274
  }
617
275
  }
618
- // Fall back to collections if no properties
619
- else if (Object.keys(collections).length > 0) {
620
- const firstColl = collections[Object.keys(collections)[0]];
621
- if (firstColl.through) {
622
- const match = firstColl.through.match(/^([^:]+:\/\/)/);
276
+ // Fall back to relations if no fields
277
+ else if (Object.keys(relations).length > 0) {
278
+ const firstRelation = relations[Object.keys(relations)[0]];
279
+ if (firstRelation.through) {
280
+ const match = firstRelation.through.match(/^([^:]+:\/\/)/);
623
281
  if (match) {
624
282
  namespace = match[1];
625
283
  }
@@ -629,6 +287,45 @@ export function ModelOptions(opts) {
629
287
  const shapeUri = `${namespace}${subjectName}Shape`;
630
288
  const targetClass = `${namespace}${subjectName}`;
631
289
  const shape = new SHACLShape(shapeUri, targetClass);
290
+ // ── Detect @Model parent for sh:node inheritance ──────────────────────
291
+ // If the immediate prototype constructor is also @Model-decorated,
292
+ // emit sh:node <ParentShape> and use only OWN properties/relations
293
+ // rather than duplicating the parent's properties in the child shape.
294
+ const parentCtor = Object.getPrototypeOf(target);
295
+ const parentClassName = parentCtor?.prototype?.className;
296
+ const isParentModel = parentClassName &&
297
+ parentClassName !== "Ad4mModel" &&
298
+ (propertyRegistry.has(parentCtor) || relationRegistry.has(parentCtor));
299
+ let shapeFields;
300
+ let shapeRelations;
301
+ if (isParentModel) {
302
+ // Own-only fields/relations — parent's are covered by sh:node
303
+ shapeFields = propertyRegistry.get(target) ?? {};
304
+ shapeRelations = relationRegistry.get(target) ?? {};
305
+ // Derive parent shape URI from parent's own properties' namespace
306
+ const parentOwnFields = Object.values(propertyRegistry.get(parentCtor) ?? {});
307
+ const parentOwnRelations = Object.values(relationRegistry.get(parentCtor) ?? {});
308
+ let parentNamespace = "ad4m://";
309
+ if (parentOwnFields.length > 0 && parentOwnFields[0].through) {
310
+ const m = parentOwnFields[0].through.match(/^([^:]+:\/\/)/);
311
+ if (m)
312
+ parentNamespace = m[1];
313
+ }
314
+ else if (parentOwnRelations.length > 0 &&
315
+ parentOwnRelations[0].through) {
316
+ const m = parentOwnRelations[0].through.match(/^([^:]+:\/\/)/);
317
+ if (m)
318
+ parentNamespace = m[1];
319
+ }
320
+ const parentShapeUri = `${parentNamespace}${parentClassName}Shape`;
321
+ shape.addParentShape(parentShapeUri);
322
+ }
323
+ else {
324
+ // No @Model parent — include all inherited properties directly
325
+ shapeFields = fields;
326
+ shapeRelations = relations;
327
+ }
328
+ // ──────────────────────────────────────────────────────────────────────
632
329
  // === Extract Constructor Actions (same logic as generateSDNA) ===
633
330
  let constructorActions = [];
634
331
  if (obj.subjectConstructor && obj.subjectConstructor.length) {
@@ -636,42 +333,48 @@ export function ModelOptions(opts) {
636
333
  }
637
334
  // === Extract Destructor Actions ===
638
335
  let destructorActions = [];
639
- // Convert properties to SHACL property shapes
640
- for (const propName in properties) {
641
- const propMeta = properties[propName];
336
+ // Convert fields to SHACL property shapes
337
+ for (const propName in shapeFields) {
338
+ const propMeta = shapeFields[propName];
642
339
  if (!propMeta.through)
643
340
  continue; // Skip properties without predicates
644
341
  const propShape = {
645
342
  name: propName,
646
343
  path: propMeta.through,
647
344
  };
648
- // Determine datatype from initial value or resolveLanguage
649
- if (propMeta.resolveLanguage === "literal") {
650
- // If it resolves via literal language, it's likely a string
651
- propShape.datatype = "xsd://string";
345
+ // Auto-derive a constructor placeholder for non-readOnly, non-flag properties
346
+ // that don't have an explicit initial. Only do this when the prototype
347
+ // has a defined default value — optional fields (title?: string) have
348
+ // no prototype default (undefined), and we must NOT write an empty
349
+ // literal link for them. The specific placeholder value doesn't matter
350
+ // for fields with an actual default — createSubject's initialValues
351
+ // mechanism overwrites it with the real value via the setter actions.
352
+ const protoDefault = obj[propName];
353
+ const effectiveInitial = propMeta.initial ??
354
+ (!propMeta.readOnly && !propMeta.flag && protoDefault !== undefined
355
+ ? "literal://string:"
356
+ : undefined);
357
+ // Determine datatype from the TypeScript default value type.
358
+ // resolveLanguage: "literal" is now the implicit default — literal://
359
+ // URIs can carry any type (string/number/boolean), so always infer
360
+ // from the prototype's default value rather than forcing xsd://string.
361
+ const initialType = typeof obj[propName];
362
+ if (initialType === "number") {
363
+ propShape.datatype = "xsd://integer";
652
364
  }
653
- else if (propMeta.initial) {
654
- // Try to infer from initial value type
655
- const initialType = typeof obj[propName];
656
- if (initialType === "number") {
657
- propShape.datatype = "xsd://integer";
658
- }
659
- else if (initialType === "boolean") {
660
- propShape.datatype = "xsd://boolean";
661
- }
662
- else if (initialType === "string") {
663
- propShape.datatype = "xsd://string";
664
- }
365
+ else if (initialType === "boolean") {
366
+ propShape.datatype = "xsd://boolean";
367
+ }
368
+ else if (initialType === "string") {
369
+ propShape.datatype = "xsd://string";
665
370
  }
666
371
  // Cardinality constraints
667
372
  if (propMeta.required) {
668
373
  propShape.minCount = 1;
669
374
  }
670
- // Single-valued properties get maxCount 1
671
- // (collections are handled separately below)
672
- if (!propMeta.collection) {
673
- propShape.maxCount = 1;
674
- }
375
+ // @Property fields are always single-valued; maxCount 1 is unconditional.
376
+ // Multi-valued relations live in relationRegistry and are handled below.
377
+ propShape.maxCount = 1;
675
378
  // Flag properties have fixed value
676
379
  if (propMeta.flag && propMeta.initial) {
677
380
  propShape.hasValue = propMeta.initial;
@@ -680,12 +383,19 @@ export function ModelOptions(opts) {
680
383
  if (propMeta.local !== undefined) {
681
384
  propShape.local = propMeta.local;
682
385
  }
683
- if (propMeta.writable !== undefined) {
684
- propShape.writable = propMeta.writable;
386
+ if (propMeta.readOnly) {
387
+ propShape.readOnly = true;
685
388
  }
686
389
  if (propMeta.resolveLanguage) {
687
390
  propShape.resolveLanguage = propMeta.resolveLanguage;
688
391
  }
392
+ else if (!propMeta.flag) {
393
+ // resolveLanguage: "literal" is the implicit default for scalar properties.
394
+ // The Rust executor requires this to be explicit in the SHACL shape to
395
+ // configure fn::parse_literal correctly in SurrealDB. The user doesn't
396
+ // need to write it in their @Property decorator, but the shape must have it.
397
+ propShape.resolveLanguage = "literal";
398
+ }
689
399
  // === Extract Setter Actions (same logic as generateSDNA) ===
690
400
  if (propMeta.setter) {
691
401
  // Custom setter defined - not yet supported in SHACL
@@ -693,27 +403,34 @@ export function ModelOptions(opts) {
693
403
  `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
694
404
  // TODO: Parse custom Prolog setter to extract actions
695
405
  }
696
- else if (propMeta.writable && propMeta.through) {
406
+ else if (!propMeta.readOnly && propMeta.through) {
697
407
  let setter = obj[propertyNameToSetterName(propName)];
698
408
  if (typeof setter === "function") {
699
- propShape.setter = [{
409
+ propShape.setter = [
410
+ {
700
411
  action: "setSingleTarget",
701
412
  source: "this",
702
413
  predicate: propMeta.through,
703
414
  target: "value",
704
- ...(propMeta.local && { local: true })
705
- }];
415
+ ...(propMeta.local && { local: true }),
416
+ },
417
+ ];
706
418
  }
707
419
  }
708
- // Add to constructor actions if property has initial value
709
- if (propMeta.initial) {
420
+ // Add to constructor actions (always for non-readOnly, non-flag, using the
421
+ // effective placeholder — createSubject's initialValues will override
422
+ // the target with the real instance value via the setter actions).
423
+ if (effectiveInitial) {
710
424
  constructorActions.push({
711
425
  action: "addLink",
712
426
  source: "this",
713
427
  predicate: propMeta.through,
714
- target: propMeta.initial,
428
+ target: effectiveInitial,
715
429
  });
716
- // Add to destructor actions
430
+ }
431
+ // Always add destructor action for non-readOnly, non-flag properties so
432
+ // delete() cleans them up regardless of whether initial was explicit.
433
+ if (!propMeta.readOnly && !propMeta.flag) {
717
434
  destructorActions.push({
718
435
  action: "removeLink",
719
436
  source: "this",
@@ -723,192 +440,67 @@ export function ModelOptions(opts) {
723
440
  }
724
441
  shape.addProperty(propShape);
725
442
  }
726
- // Convert collections to SHACL property shapes
727
- // (collections variable already declared above for namespace inference)
728
- for (const collName in collections) {
729
- const collMeta = collections[collName];
730
- if (!collMeta.through)
443
+ // Convert relations to SHACL property shapes
444
+ for (const relName in shapeRelations) {
445
+ const relMeta = shapeRelations[relName];
446
+ if (!relMeta.through)
731
447
  continue;
732
- const collShape = {
733
- name: collName,
734
- path: collMeta.through,
735
- // Collections have no maxCount (unlimited)
448
+ const relShape = {
449
+ name: relName,
450
+ path: relMeta.through,
451
+ // Relations have no maxCount (unlimited)
736
452
  // minCount defaults to 0 (optional)
737
453
  };
738
- // Determine if it's a reference (IRI) or literal
739
- // Collections typically contain references (IRIs) to other entities
740
- // They're literals only if explicitly marked or contain primitive values
741
- if (collMeta.where?.isInstance) {
742
- // Collection of typed entities - definitely IRIs
743
- collShape.nodeKind = 'IRI';
744
- }
745
- else {
746
- // Default to IRI for collections (most common case)
747
- // Literal collections are rare and would need explicit marking
748
- collShape.nodeKind = 'IRI';
749
- }
454
+ // Relations contain references (IRIs) to other entities
455
+ relShape.nodeKind = "IRI";
750
456
  // AD4M-specific metadata
751
- if (collMeta.local !== undefined) {
752
- collShape.local = collMeta.local;
457
+ if (relMeta.local !== undefined) {
458
+ relShape.local = relMeta.local;
459
+ }
460
+ // Relationship metadata
461
+ if (relMeta.maxCount !== undefined) {
462
+ relShape.maxCount = relMeta.maxCount;
753
463
  }
754
- if (collMeta.writable !== undefined) {
755
- collShape.writable = collMeta.writable;
464
+ if (relMeta.direction === "reverse") {
465
+ relShape.inversePath = true;
756
466
  }
757
- // === Extract Collection Actions (adder/remover) ===
758
- // Adder action - adds a link to the collection
759
- collShape.adder = [{
467
+ // === Extract Relation Actions (adder/remover) ===
468
+ // Adder action - adds a link to the relation
469
+ relShape.adder = [
470
+ {
760
471
  action: "addLink",
761
472
  source: "this",
762
- predicate: collMeta.through,
473
+ predicate: relMeta.through,
763
474
  target: "value",
764
- ...(collMeta.local && { local: true })
765
- }];
766
- // Remover action - removes a link from the collection
767
- collShape.remover = [{
475
+ ...(relMeta.local && { local: true }),
476
+ },
477
+ ];
478
+ // Remover action - removes a link from the relation
479
+ relShape.remover = [
480
+ {
768
481
  action: "removeLink",
769
482
  source: "this",
770
- predicate: collMeta.through,
483
+ predicate: relMeta.through,
771
484
  target: "value",
772
- ...(collMeta.local && { local: true })
773
- }];
774
- shape.addProperty(collShape);
775
- }
776
- // Set constructor and destructor actions on the shape
777
- if (constructorActions.length > 0) {
778
- shape.setConstructorActions(constructorActions);
485
+ ...(relMeta.local && { local: true }),
486
+ },
487
+ ];
488
+ shape.addProperty(relShape);
779
489
  }
490
+ // Set constructor and destructor actions on the shape.
491
+ // Always set constructor actions (even if empty) so the Rust SHACL parser
492
+ // emits an ad4m://constructor link — without it get_constructor_actions()
493
+ // throws "No SHACL constructor found" for classes with no @Flag or initial
494
+ // properties. An empty constructor is valid: it means "do nothing on creation".
495
+ shape.setConstructorActions(constructorActions);
780
496
  if (destructorActions.length > 0) {
781
497
  shape.setDestructorActions(destructorActions);
782
498
  }
783
499
  return {
784
500
  shape,
785
- name: subjectName
501
+ name: subjectName,
786
502
  };
787
503
  };
788
- Object.defineProperty(target, 'type', { configurable: true });
504
+ Object.defineProperty(target, "type", { configurable: true });
789
505
  };
790
506
  }
791
- /**
792
- * Decorator for defining required and writable properties on model classes.
793
- *
794
- * @category Decorators
795
- *
796
- * @description
797
- * A convenience decorator that defines a required property that must have an initial value and is writable by default.
798
- * This is equivalent to using @Optional with `required: true` and `writable: true`.
799
- *
800
- * Properties defined with this decorator:
801
- * - Must have a value (required)
802
- * - Can be modified after creation (writable)
803
- * - Default to "literal://string:uninitialized" if no initial value is provided
804
- *
805
- * @example
806
- * ```typescript
807
- * class User extends Ad4mModel {
808
- * // Basic required property with default initial value
809
- * @Property({
810
- * through: "user://name"
811
- * })
812
- * name: string = "";
813
- *
814
- * // Required property with custom initial value
815
- * @Property({
816
- * through: "user://status",
817
- * initial: "user://active"
818
- * })
819
- * status: string = "";
820
- *
821
- * // Required property with literal resolution
822
- * @Property({
823
- * through: "user://bio",
824
- * resolveLanguage: "literal"
825
- * })
826
- * bio: string = "";
827
- *
828
- * // Required property with custom getter/setter
829
- * @Property({
830
- * through: "user://age",
831
- * getter: `triple(Base, "user://birthYear", Year), Value is 2024 - Year`,
832
- * setter: `Year is 2024 - Value, Actions = [{"action": "setSingleTarget", "source": "this", "predicate": "user://birthYear", "target": Year}]`
833
- * })
834
- * age: number = 0;
835
- * }
836
- * ```
837
- *
838
- * @param {PropertyOptions} opts - Property configuration
839
- * @param {string} opts.through - The predicate URI for the property
840
- * @param {string} [opts.initial] - Initial value (defaults to "literal://string:uninitialized")
841
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
842
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
843
- * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value
844
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
845
- */
846
- export function Property(opts) {
847
- return Optional({
848
- ...opts,
849
- required: true,
850
- writable: true,
851
- initial: opts.initial || "literal://string:uninitialized"
852
- });
853
- }
854
- /**
855
- * Decorator for defining read-only properties on model classes.
856
- *
857
- * @category Decorators
858
- *
859
- * @description
860
- * A convenience decorator that defines a property that can only be read and cannot be modified after initialization.
861
- * This is equivalent to using @Optional with `writable: false`.
862
- *
863
- * Read-only properties are ideal for:
864
- * - Computed or derived values
865
- * - Properties that should never change after creation
866
- * - Properties that are set by the system
867
- * - Properties that represent immutable data
868
- *
869
- * @example
870
- * ```typescript
871
- * class Post extends Ad4mModel {
872
- * // Read-only property with custom getter for computed value
873
- * @ReadOnly({
874
- * through: "post://likes",
875
- * getter: `findall(User, triple(Base, "post://liked_by", User), Users), length(Users, Value)`
876
- * })
877
- * likeCount: number = 0;
878
- *
879
- * // Read-only property for creation timestamp
880
- * @ReadOnly({
881
- * through: "post://created_at",
882
- * initial: new Date().toISOString()
883
- * })
884
- * createdAt: string = "";
885
- *
886
- * // Read-only property that resolves to a Literal
887
- * @ReadOnly({
888
- * through: "post://author",
889
- * resolveLanguage: "literal"
890
- * })
891
- * author: string = "";
892
- *
893
- * // Read-only property for system-managed data
894
- * @ReadOnly({
895
- * through: "post://version",
896
- * initial: "1.0.0"
897
- * })
898
- * version: string = "";
899
- * }
900
- * ```
901
- *
902
- * @param {PropertyOptions} opts - Property configuration
903
- * @param {string} opts.through - The predicate URI for the property
904
- * @param {string} [opts.initial] - Initial value (if property should have one)
905
- * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. "literal")
906
- * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value
907
- * @param {boolean} [opts.local] - Whether the property should only be stored locally
908
- */
909
- export function ReadOnly(opts) {
910
- return Optional({
911
- ...opts,
912
- writable: false
913
- });
914
- }