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

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