@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
@@ -0,0 +1,461 @@
1
+ /**
2
+ * Mutation helpers for Ad4mModel — extracted Phase 3c.
3
+ *
4
+ * All persistence functions that previously lived as private methods on Ad4mModel.
5
+ * Each takes a `MutationContext` (perspective, id, instance)
6
+ * instead of using `this`, making them independently testable and composable.
7
+ *
8
+ * Functions exported here cover the full write path:
9
+ * - Pure action builders: `generatePropertySetterAction`, `generateRelationAction`
10
+ * - Per-field setters: `setProperty`, `setRelationSetter/Adder/Remover`
11
+ * - Instance-level persistence: `cleanCopy`, `innerUpdate`, `saveInstance`
12
+ */
13
+
14
+ import { Literal } from "../Literal";
15
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
16
+ import type { PropertyOptions, RelationOptions } from "./decorators";
17
+ import {
18
+ getPropertiesMetadata,
19
+ getRelationsMetadata,
20
+ propertyRegistry,
21
+ } from "./decorators";
22
+ import { formatSurrealValue } from "./query/surrealCompiler";
23
+ import { fetchInstanceData } from "./query/fetchInstance";
24
+ import { isDirty } from "./query/snapshot";
25
+ import { getModelMetadata as _getModelMetadata } from "./schema/metadata";
26
+
27
+ // ── Context ────────────────────────────────────────────────────────────────
28
+
29
+ /**
30
+ * Bundles the per-instance state needed by every mutation function,
31
+ * replacing the private `this.#*` fields from Ad4mModel.
32
+ */
33
+ export interface MutationContext {
34
+ /** The perspective that owns this instance. */
35
+ perspective: PerspectiveProxy;
36
+ /** URI of the instance's root node in the graph (the base expression). */
37
+ id: string;
38
+ /** The Ad4mModel instance itself (for `Object.entries`, prototype lookups, etc.) */
39
+ instance: any;
40
+ }
41
+
42
+ // ── Pure action builders ───────────────────────────────────────────────────
43
+
44
+ /**
45
+ * Builds a `setSingleTarget` action descriptor from property metadata.
46
+ * Throws if the property is a flag, read-only, or has no predicate.
47
+ */
48
+ export function generatePropertySetterAction(
49
+ key: string,
50
+ metadata: PropertyOptions,
51
+ ): any[] {
52
+ if (metadata.flag) {
53
+ throw new Error(
54
+ `Property "${key}" is a @Flag and cannot be set after creation`,
55
+ );
56
+ }
57
+ if (metadata.readOnly === true) {
58
+ throw new Error(`Property "${key}" is read-only and cannot be written`);
59
+ }
60
+ if (!metadata.through) {
61
+ throw new Error(`Property "${key}" has no 'through' predicate defined`);
62
+ }
63
+ return [
64
+ {
65
+ action: "setSingleTarget",
66
+ source: "this",
67
+ predicate: metadata.through,
68
+ target: "value",
69
+ ...(metadata.local && { local: true }),
70
+ },
71
+ ];
72
+ }
73
+
74
+ /**
75
+ * Builds an `addLink` / `removeLink` / `relationSetter` action descriptor
76
+ * from relation metadata.
77
+ */
78
+ export function generateRelationAction(
79
+ key: string,
80
+ metadata: RelationOptions,
81
+ actionType: "adder" | "remover" | "setter",
82
+ ): any[] {
83
+ if (!metadata.through) {
84
+ throw new Error(`Relation "${key}" has no 'through' predicate defined`);
85
+ }
86
+ const actionMap = {
87
+ adder: "addLink",
88
+ remover: "removeLink",
89
+ setter: "relationSetter",
90
+ };
91
+ return [
92
+ {
93
+ action: actionMap[actionType],
94
+ source: "this",
95
+ predicate: metadata.through,
96
+ target: "value",
97
+ ...(metadata.local && { local: true }),
98
+ },
99
+ ];
100
+ }
101
+
102
+ // ── Property / relation setters ────────────────────────────────────────────
103
+
104
+ /**
105
+ * Persists a single scalar property value for `ctx.instance`.
106
+ *
107
+ * Values that already carry a URI scheme are passed through unchanged.
108
+ * Raw scalars are encoded as `literal://` URIs.
109
+ * When a `resolveLanguage` is set, the value is first stored via `createExpression`.
110
+ */
111
+ export async function setProperty(
112
+ ctx: MutationContext,
113
+ key: string,
114
+ value: any,
115
+ batchId?: string,
116
+ ): Promise<void> {
117
+ const proto = Object.getPrototypeOf(ctx.instance);
118
+ const metadata = getPropertiesMetadata(proto.constructor)?.[key] as
119
+ | PropertyOptions
120
+ | undefined;
121
+ if (!metadata) {
122
+ throw new Error(
123
+ `setProperty called with unknown key "${key}" — ensure the field has a @Property decorator`,
124
+ );
125
+ }
126
+
127
+ const actions = generatePropertySetterAction(key, metadata);
128
+ const resolveLanguage = metadata.resolveLanguage;
129
+
130
+ // Skip empty/null/undefined to avoid storing invalid empty literals.
131
+ if (value === undefined || value === null || value === "") return;
132
+
133
+ if (resolveLanguage) {
134
+ value = await ctx.perspective.createExpression(value, resolveLanguage);
135
+ } else if (
136
+ typeof value !== "string" ||
137
+ !/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(value)
138
+ ) {
139
+ // Encode raw scalars as literal:// URIs — mirrors Rust's resolve_property_value.
140
+ value = Literal.from(value).toUrl();
141
+ }
142
+
143
+ await ctx.perspective.executeAction(
144
+ actions,
145
+ ctx.id,
146
+ [{ name: "value", value }],
147
+ batchId,
148
+ );
149
+ }
150
+
151
+ /** Normalises an Ad4mModel instance to its id URI, passing other values through unchanged. */
152
+ const toId = (v: any): any =>
153
+ v && typeof v === "object" && typeof v.id === "string" ? v.id : v;
154
+
155
+ /** Sets (replaces) the full set of targets for a relation. */
156
+ export async function setRelationSetter(
157
+ ctx: MutationContext,
158
+ key: string,
159
+ value: any,
160
+ batchId?: string,
161
+ ): Promise<void> {
162
+ const proto = Object.getPrototypeOf(ctx.instance);
163
+ const metadata = getRelationsMetadata(proto.constructor)?.[key] as
164
+ | RelationOptions
165
+ | undefined;
166
+ if (!metadata) {
167
+ console.warn(`Relation "${key}" has no metadata, skipping`);
168
+ return;
169
+ }
170
+
171
+ const actions = generateRelationAction(key, metadata, "setter");
172
+
173
+ if (value != null) {
174
+ if (Array.isArray(value)) {
175
+ await ctx.perspective.executeAction(
176
+ actions,
177
+ ctx.id,
178
+ value.map((v) => ({ name: "value", value: toId(v) })),
179
+ batchId,
180
+ );
181
+ } else {
182
+ await ctx.perspective.executeAction(
183
+ actions,
184
+ ctx.id,
185
+ [{ name: "value", value: toId(value) }],
186
+ batchId,
187
+ );
188
+ }
189
+ }
190
+ }
191
+
192
+ /** Adds one or more targets to a relation without removing existing ones. */
193
+ export async function setRelationAdder(
194
+ ctx: MutationContext,
195
+ key: string,
196
+ value: any,
197
+ batchId?: string,
198
+ ): Promise<void> {
199
+ const proto = Object.getPrototypeOf(ctx.instance);
200
+ const metadata = getRelationsMetadata(proto.constructor)?.[key] as
201
+ | RelationOptions
202
+ | undefined;
203
+ if (!metadata) {
204
+ console.warn(`Relation "${key}" has no metadata, skipping`);
205
+ return;
206
+ }
207
+
208
+ const actions = generateRelationAction(key, metadata, "adder");
209
+
210
+ if (value != null) {
211
+ if (Array.isArray(value)) {
212
+ await Promise.all(
213
+ value.map((v) =>
214
+ ctx.perspective.executeAction(
215
+ actions,
216
+ ctx.id,
217
+ [{ name: "value", value: toId(v) }],
218
+ batchId,
219
+ ),
220
+ ),
221
+ );
222
+ } else {
223
+ await ctx.perspective.executeAction(
224
+ actions,
225
+ ctx.id,
226
+ [{ name: "value", value: toId(value) }],
227
+ batchId,
228
+ );
229
+ }
230
+ }
231
+ }
232
+
233
+ /** Removes one or more targets from a relation. */
234
+ export async function setRelationRemover(
235
+ ctx: MutationContext,
236
+ key: string,
237
+ value: any,
238
+ batchId?: string,
239
+ ): Promise<void> {
240
+ const proto = Object.getPrototypeOf(ctx.instance);
241
+ const metadata = getRelationsMetadata(proto.constructor)?.[key] as
242
+ | RelationOptions
243
+ | undefined;
244
+ if (!metadata) {
245
+ console.warn(`Relation "${key}" has no metadata, skipping`);
246
+ return;
247
+ }
248
+
249
+ const actions = generateRelationAction(key, metadata, "remover");
250
+
251
+ if (value != null) {
252
+ if (Array.isArray(value)) {
253
+ await Promise.all(
254
+ value.map((v) =>
255
+ ctx.perspective.executeAction(
256
+ actions,
257
+ ctx.id,
258
+ [{ name: "value", value: toId(v) }],
259
+ batchId,
260
+ ),
261
+ ),
262
+ );
263
+ } else {
264
+ await ctx.perspective.executeAction(
265
+ actions,
266
+ ctx.id,
267
+ [{ name: "value", value: toId(value) }],
268
+ batchId,
269
+ );
270
+ }
271
+ }
272
+ }
273
+
274
+ // ── Persistence ────────────────────────────────────────────────────────────
275
+
276
+ /**
277
+ * Returns a shallow copy of `instance` with `null`, `undefined`,
278
+ * `author`, and `timestamp` fields omitted.
279
+ */
280
+ export function cleanCopy(instance: any): Record<string, any> {
281
+ const clean: Record<string, any> = {};
282
+ for (const [key, value] of Object.entries(instance)) {
283
+ if (
284
+ value !== undefined &&
285
+ value !== null &&
286
+ key !== "author" &&
287
+ key !== "timestamp"
288
+ ) {
289
+ clean[key] = value;
290
+ }
291
+ }
292
+ return clean;
293
+ }
294
+
295
+ /**
296
+ * Iterates all instance fields and persists each one according to its metadata.
297
+ *
298
+ * - Fields with an `.action` shape → dispatched to the matching relation mutator.
299
+ * - Arrays → treated as relation setters (including empty arrays to clear relations).
300
+ * - Scalar values → written via `setProperty` when `setProperties` is `true` and the
301
+ * field is not a relation or a flag.
302
+ *
303
+ * @note `#subjectClassName` was written here in the original implementation but
304
+ * is never read anywhere — the write is intentionally omitted.
305
+ */
306
+ export async function innerUpdate(
307
+ ctx: MutationContext,
308
+ setProperties: boolean = true,
309
+ batchId?: string,
310
+ ): Promise<void> {
311
+ const proto = Object.getPrototypeOf(ctx.instance);
312
+
313
+ for (const [key, value] of Object.entries(ctx.instance)) {
314
+ if (value !== undefined && value !== null) {
315
+ if ((value as any)?.action) {
316
+ switch ((value as any).action) {
317
+ case "setter":
318
+ await setRelationSetter(ctx, key, (value as any).value, batchId);
319
+ break;
320
+ case "adder":
321
+ await setRelationAdder(ctx, key, (value as any).value, batchId);
322
+ break;
323
+ case "remover":
324
+ await setRelationRemover(ctx, key, (value as any).value, batchId);
325
+ break;
326
+ default:
327
+ await setRelationSetter(ctx, key, (value as any).value, batchId);
328
+ break;
329
+ }
330
+ } else if (Array.isArray(value)) {
331
+ // All arrays (including empty) treated as relation setters.
332
+ // Skip if the set hasn't changed since the last hydration/save.
333
+ if (!isDirty(ctx.instance, key, value)) continue;
334
+ await setRelationSetter(ctx, key, value, batchId);
335
+ } else if (value !== undefined && value !== null && value !== "") {
336
+ if (setProperties) {
337
+ // Skip relation fields — they are not scalar properties.
338
+ if (getRelationsMetadata(proto.constructor)?.[key]) continue;
339
+ const propMeta = getPropertiesMetadata(proto.constructor)?.[key];
340
+ // No @Property decorator for this key — skip silently.
341
+ // This covers generated relation methods (addX / removeX / setX)
342
+ // that appear as own enumerable properties on the instance, and
343
+ // base-class fields like `author` / `createdAt` that have no
344
+ // associated predicate.
345
+ if (!propMeta) continue;
346
+ // Skip flag fields — flags are immutable, written once by createSubject.
347
+ if (propMeta.flag) continue;
348
+ // Skip if the value hasn't changed since the last hydration/save.
349
+ if (!isDirty(ctx.instance, key, value)) continue;
350
+ await setProperty(ctx, key, value, batchId);
351
+ }
352
+ }
353
+ }
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Persists `ctx.instance` to `ctx.perspective`.
359
+ *
360
+ * Auto-detects create vs update by checking whether any links already exist
361
+ * for `ctx.id`.
362
+ *
363
+ * - **Create path**: `createSubject` → `innerUpdate(false)` (relations only).
364
+ * - **Update path**: `innerUpdate(true)` (properties + relations).
365
+ *
366
+ * @param ctx - Mutation context (perspective, id, instance).
367
+ * @param batchId - Optional caller-managed batch. When omitted an internal batch
368
+ * is created, committed, and the instance is rehydrated automatically.
369
+ */
370
+ export async function saveInstance(
371
+ ctx: MutationContext,
372
+ batchId?: string,
373
+ alreadyExists?: boolean,
374
+ ): Promise<void> {
375
+ const safeBase = formatSurrealValue(ctx.id);
376
+ // Skip the DB round-trip when the caller already knows the instance was
377
+ // saved once (e.g. the second save() call inside the same uncommitted batch).
378
+ let isNew: boolean;
379
+ if (alreadyExists === true) {
380
+ isNew = false;
381
+ } else {
382
+ const existingLinks = await ctx.perspective.querySurrealDB(
383
+ `SELECT 1 FROM link WHERE in.uri = ${safeBase} LIMIT 1`,
384
+ );
385
+ isNew = !existingLinks || existingLinks.length === 0;
386
+ }
387
+
388
+ let batchCreatedHere = false;
389
+ if (!batchId) {
390
+ batchId = await ctx.perspective.createBatch();
391
+ batchCreatedHere = true;
392
+ }
393
+
394
+ if (isNew) {
395
+ // ── CREATE PATH ─────────────────────────────────────────────────────────
396
+ // Build initialValues from decorator-registered scalar properties only.
397
+ // We must NOT use Object.entries(ctx.instance) because TypeScript `private`
398
+ // fields (e.g. _perspective) are regular enumerable properties at runtime
399
+ // and would cause JSON.stringify to throw a circular-reference error when
400
+ // the PerspectiveProxy's Apollo InMemoryCache is encountered.
401
+ const proto = Object.getPrototypeOf(ctx.instance);
402
+ const ownPropKeys = new Set(
403
+ Object.keys(propertyRegistry.get(proto.constructor) ?? {}),
404
+ );
405
+ const allPropMeta = getPropertiesMetadata(proto.constructor);
406
+ const initialValues: Record<string, any> = {};
407
+ for (const key of ownPropKeys) {
408
+ const propMeta = allPropMeta[key];
409
+ if (!propMeta) continue;
410
+ if ((propMeta as PropertyOptions).flag) continue; // flags handled by constructor actions
411
+ const value = (ctx.instance as any)[key];
412
+ if (
413
+ value !== undefined &&
414
+ value !== null &&
415
+ !(Array.isArray(value) && (value as any[]).length > 0) &&
416
+ !(value as any)?.action
417
+ ) {
418
+ initialValues[key] = value;
419
+ }
420
+ }
421
+
422
+ const className =
423
+ await ctx.perspective.stringOrTemplateObjectToSubjectClassName(
424
+ ctx.instance,
425
+ );
426
+ await ctx.perspective.createSubject(
427
+ className,
428
+ ctx.id,
429
+ initialValues,
430
+ batchId,
431
+ );
432
+
433
+ await innerUpdate(ctx, false, batchId);
434
+
435
+ // Write inherited properties not present in the class's own SHACL shape.
436
+ // When a derived class uses sh:node to reference its parent shape, createSubject
437
+ // only writes properties defined in the derived shape. Inherited @Property fields
438
+ // (registered on the parent constructor) are silently ignored by the Rust backend.
439
+ // We detect them by comparing the full merged metadata against the own-only registry.
440
+ for (const [key, propMeta] of Object.entries(allPropMeta)) {
441
+ if (ownPropKeys.has(key)) continue; // already handled by createSubject
442
+ if ((propMeta as PropertyOptions).flag) continue; // flags are immutable
443
+ const value = (ctx.instance as any)[key];
444
+ if (value !== undefined && value !== null && value !== "") {
445
+ await setProperty(ctx, key, value, batchId);
446
+ }
447
+ }
448
+ } else {
449
+ // ── UPDATE PATH ─────────────────────────────────────────────────────────
450
+ // Instance already exists — update properties and relations only.
451
+ await innerUpdate(ctx, true, batchId);
452
+ }
453
+
454
+ if (batchCreatedHere) {
455
+ await ctx.perspective.commitBatch(batchId);
456
+
457
+ // Rehydrate the instance so callers see the persisted state.
458
+ const metadata = _getModelMetadata(ctx.instance.constructor);
459
+ await fetchInstanceData(ctx.instance, ctx.perspective, ctx.id, metadata);
460
+ }
461
+ }
@@ -0,0 +1,91 @@
1
+ import type { ModelMetadata, ParentQuery, ParentQueryByPredicate } from "./types";
2
+
3
+ /**
4
+ * Resolves the predicate URI for a parent→child relation, used by
5
+ * `Ad4mModel.create()` and the `useLiveQuery` hooks.
6
+ *
7
+ * If `field` is supplied, that exact relation is looked up on the parent.
8
+ * Otherwise, all forward relations on the parent whose `relatedModel()` factory
9
+ * returns `childCtor` are scanned; the result is used when exactly one match
10
+ * is found.
11
+ *
12
+ * @throws if the field doesn't exist, or inference is ambiguous / impossible.
13
+ *
14
+ * @example
15
+ * // Explicit field
16
+ * resolveParentPredicate(Channel.getModelMetadata(), Poll, 'polls')
17
+ *
18
+ * // Inferred — only one @HasMany on Channel points to Poll
19
+ * resolveParentPredicate(Channel.getModelMetadata(), Poll)
20
+ */
21
+ export function resolveParentPredicate(
22
+ parentMeta: ModelMetadata,
23
+ childCtor: (new (...args: any[]) => any) | undefined,
24
+ field?: string,
25
+ ): string {
26
+ if (field) {
27
+ const predicate = parentMeta.relations[field]?.predicate;
28
+ if (!predicate) {
29
+ throw new Error(
30
+ `resolveParentPredicate: field "${field}" not found in parent model ` +
31
+ `"${parentMeta.className}" relations. Check that @HasMany is declared on that field.`,
32
+ );
33
+ }
34
+ return predicate;
35
+ }
36
+
37
+ if (!childCtor) {
38
+ throw new Error(
39
+ `resolveParentPredicate: either "field" or a child model constructor must be provided.`,
40
+ );
41
+ }
42
+
43
+ const matches = Object.values(parentMeta.relations).filter(
44
+ (r) => r.direction !== "reverse" && r.relatedModel?.() === childCtor,
45
+ );
46
+
47
+ if (matches.length === 1) return matches[0].predicate;
48
+
49
+ if (matches.length === 0) {
50
+ throw new Error(
51
+ `resolveParentPredicate: no forward relation pointing to ` +
52
+ `"${(childCtor as any).name ?? String(childCtor)}" found on parent "${parentMeta.className}". ` +
53
+ `Provide "field" explicitly or add a typed @HasMany(() => ${(childCtor as any).name ?? "ChildModel"}) on the parent.`,
54
+ );
55
+ }
56
+
57
+ // matches.length > 1
58
+ const fieldNames = Object.entries(parentMeta.relations)
59
+ .filter((r) => r[1].direction !== "reverse" && r[1].relatedModel?.() === childCtor)
60
+ .map(([k]) => k)
61
+ .join(", ");
62
+ throw new Error(
63
+ `resolveParentPredicate: multiple relations on "${parentMeta.className}" point to ` +
64
+ `"${(childCtor as any).name ?? String(childCtor)}" (fields: ${fieldNames}). ` +
65
+ `Provide "field" to disambiguate.`,
66
+ );
67
+ }
68
+
69
+ /**
70
+ * Normalises a `Query.parent` option to its raw `{ id, predicate }` form.
71
+ *
72
+ * When the model-backed form `{ id, model, field? }` is supplied, the predicate
73
+ * is resolved via {@link resolveParentPredicate}. The raw `{ id, predicate }`
74
+ * form is returned as-is.
75
+ *
76
+ * @param lf - Either the raw or model-backed `parent` query value.
77
+ * @param childCtor - The child model constructor. Required when `field` is
78
+ * omitted (used for inference across `@HasMany` metadata).
79
+ */
80
+ export function normalizeParentQuery(
81
+ lf: ParentQuery,
82
+ childCtor?: new (...args: any[]) => any,
83
+ ): ParentQueryByPredicate {
84
+ if ("predicate" in lf) return lf;
85
+ const predicate = resolveParentPredicate(
86
+ lf.model.getModelMetadata(),
87
+ childCtor,
88
+ lf.field,
89
+ );
90
+ return { id: lf.id, predicate };
91
+ }