@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0-rc2

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 (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -1,8 +1,9 @@
1
- import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
2
- import { SHACLShape, SHACLPropertyShape, ConformanceCondition } from "../shacl/SHACLShape";
1
+ import { capitalize } from "./util";
2
+ import type { Where } from "./types";
3
+ import { buildSDNA } from "./sdna";
4
+ import { buildSHACL } from "./shacl-gen";
3
5
  import { escapeSurrealString } from "../utils";
4
- import type { Where } from "./Ad4mModel";
5
- import { compileWhereClause } from "./surreal-utils";
6
+ import type { ConformanceCondition } from "../shacl/SHACLShape";
6
7
 
7
8
  // ============================================================================
8
9
  // WeakMap-based metadata registry
@@ -194,55 +195,6 @@ export function buildConformanceFilter(
194
195
  }
195
196
  }
196
197
 
197
- /**
198
- * Convert a model instance to a plain serializable object.
199
- * Reads the property metadata and extracts values from the instance.
200
- */
201
- export function instanceToSerializable(instance: any): Record<string, any> {
202
- const ctor = instance.constructor;
203
- const props = getPropertiesMetadata(ctor);
204
- const result: Record<string, any> = {};
205
- for (const [key, _meta] of Object.entries(props)) {
206
- result[key] = instance[key];
207
- }
208
- return result;
209
- }
210
-
211
- /**
212
- * Generate a random identifier string (lowercase alpha).
213
- * Generate a random identifier string of the given length (lowercase alpha).
214
- */
215
- export function makeRandomId(length: number): string {
216
- let result = '';
217
- const characters = 'abcdefghijklmnopqrstuvwxyz';
218
- const charactersLength = characters.length;
219
- for (let i = 0; i < length; i++) {
220
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
221
- }
222
- return result;
223
- }
224
-
225
- export class PerspectiveAction {
226
- action: string
227
- source: string
228
- predicate: string
229
- target: string
230
- }
231
-
232
- export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
233
- return {
234
- action: "addLink",
235
- source,
236
- predicate,
237
- target,
238
- };
239
- }
240
-
241
- export function hasLink(predicate: string): string {
242
- return `triple(this, "${predicate}", _)`
243
- }
244
-
245
-
246
198
  export interface PropertyOptions {
247
199
  /**
248
200
  * The predicate of the property. All properties must have this option.
@@ -531,432 +483,22 @@ export function Model(opts: ModelConfig) {
531
483
  target.className = opts.name;
532
484
 
533
485
  target.generateSDNA = function() {
534
- let sdna = ""
535
- let subjectName = opts.name
536
- let obj = target.prototype;
537
-
538
- let uuid = makeRandomId(8)
539
-
540
- sdna += `subject_class("${subjectName}", ${uuid}).\n`
541
-
542
-
543
- let classRemoverActions = []
544
-
545
- let constructorActions = []
546
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
547
- constructorActions = constructorActions.concat(obj.subjectConstructor)
548
- }
549
-
550
- let instanceConditions = []
551
- if(obj.isSubjectInstance && obj.isSubjectInstance.length) {
552
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance)
553
- }
554
-
555
- let propertiesCode = []
556
- let properties = getPropertiesMetadata(target)
557
- for(let property in properties) {
558
- let propertyCode = `property(${uuid}, "${property}").\n`
559
-
560
- let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property]
561
-
562
- if(resolveLanguage) {
563
- propertyCode += `property_resolve(${uuid}, "${property}").\n`
564
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
565
- }
566
-
567
- if(prologGetter) {
568
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`
569
- } else if(through) {
570
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
571
-
572
- if(required) {
573
- if(flag) {
574
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`)
575
- } else {
576
- instanceConditions.push(`triple(Base, "${through}", _)`)
577
- }
578
- }
579
- }
580
-
581
- if(prologSetter) {
582
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`
583
- } else if (writable && through) {
584
- let setter = obj[propertyNameToSetterName(property)]
585
- if(typeof setter === "function") {
586
- let action = [{
587
- action: "setSingleTarget",
588
- source: "this",
589
- predicate: through,
590
- target: "value",
591
- ...(local && { local: true })
592
- }]
593
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`
594
- }
595
- }
596
-
597
- propertiesCode.push(propertyCode)
598
-
599
- // Auto-derive effectiveInitial for required, writable, non-flag properties
600
- // so constructor/destructor always handle the property link.
601
- // Optional properties (required: false) are excluded — they should
602
- // remain unset (undefined) until explicitly assigned.
603
- const effectiveInitial = initial
604
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
605
-
606
- if(effectiveInitial) {
607
- constructorActions.push({
608
- action: "addLink",
609
- source: "this",
610
- predicate: through,
611
- target: effectiveInitial,
612
- })
613
-
614
- classRemoverActions.push({
615
- action: "removeLink",
616
- source: "this",
617
- predicate: through,
618
- target: "*",
619
- })
620
- }
621
- }
622
-
623
- let relationsCode = []
624
- const allRelationsMeta = getRelationsMetadata(target)
625
- const relations = Object.fromEntries(
626
- Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
627
- )
628
- for(let relation in relations) {
629
- let relationCode = `collection(${uuid}, "${relation}").\n`
630
-
631
- let { predicate: through, local} = relations[relation]
632
-
633
- if(through) {
634
- relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
635
-
636
- let relationAdderAction = [{
637
- action: "addLink",
638
- source: "this",
639
- predicate: through,
640
- target: "value",
641
- ...(local && { local: true })
642
- }]
643
-
644
- let relationRemoverAction = [{
645
- action: "removeLink",
646
- source: "this",
647
- predicate: through,
648
- target: "value",
649
- }]
650
-
651
- let relationSetterAction = [{
652
- action: "collectionSetter",
653
- source: "this",
654
- predicate: through,
655
- target: "value",
656
- ...(local && { local: true })
657
- }]
658
- relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`
659
- relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`
660
- relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`
661
- }
662
-
663
- relationsCode.push(relationCode)
664
- }
665
-
666
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions)
667
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`
668
- if(instanceConditions.length > 0) {
669
- let instanceConditionProlog = instanceConditions.join(", ")
670
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`
671
- sdna += "\n"
672
- }
673
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`
674
- sdna += "\n"
675
- sdna += propertiesCode.join("\n")
676
- sdna += "\n"
677
- sdna += relationsCode.join("\n")
678
-
679
- return {
680
- sdna,
681
- name: subjectName
682
- }
486
+ return buildSDNA(
487
+ opts.name,
488
+ target.prototype,
489
+ getPropertiesMetadata(target),
490
+ getRelationsMetadata(target),
491
+ );
683
492
  }
684
493
 
685
- // Generate SHACL shape (W3C standard + AD4M action definitions)
686
494
  target.generateSHACL = function() {
687
- const subjectName = opts.name;
688
- const obj = target.prototype;
689
-
690
- // Determine namespace from first property or relation, or use default
691
- let namespace = "ad4m://";
692
- const properties = getPropertiesMetadata(target);
693
- const allRelationsMeta2 = getRelationsMetadata(target);
694
- const relations = Object.fromEntries(
695
- Object.entries(allRelationsMeta2).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany')
495
+ return buildSHACL(
496
+ opts.name,
497
+ target,
498
+ getPropertiesMetadata(target),
499
+ getRelationsMetadata(target),
500
+ buildConformanceFilter,
696
501
  );
697
-
698
- // Try properties first
699
- if (Object.keys(properties).length > 0) {
700
- const firstProp = properties[Object.keys(properties)[0]];
701
- if (firstProp.through) {
702
- // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
703
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
704
- if (match) {
705
- namespace = match[1];
706
- }
707
- }
708
- }
709
- // Fall back to relations if no properties
710
- else if (Object.keys(relations).length > 0) {
711
- const firstRel = relations[Object.keys(relations)[0]];
712
- if (firstRel.predicate) {
713
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
714
- if (match) {
715
- namespace = match[1];
716
- }
717
- }
718
- }
719
-
720
- // Create SHACL shape
721
- const shapeUri = `${namespace}${subjectName}Shape`;
722
- const targetClass = `${namespace}${subjectName}`;
723
- const shape = new SHACLShape(shapeUri, targetClass);
724
-
725
- // Detect @Model inheritance — if the parent class also has
726
- // generateSHACL it is itself a @Model and we reference its shape
727
- // via sh:node so SHACL validators can walk the hierarchy.
728
- const parentCtor = Object.getPrototypeOf(target);
729
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
730
- const parentSHACL = parentCtor.generateSHACL();
731
- if (parentSHACL?.shape?.nodeShapeUri) {
732
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
733
- }
734
- }
735
-
736
- // === Extract Constructor Actions (same logic as generateSDNA) ===
737
- let constructorActions = [];
738
- if(obj.subjectConstructor && obj.subjectConstructor.length) {
739
- constructorActions = constructorActions.concat(obj.subjectConstructor);
740
- }
741
-
742
- // === Extract Destructor Actions ===
743
- let destructorActions = [];
744
-
745
- // Convert properties to SHACL property shapes
746
- for (const propName in properties) {
747
- const propMeta = properties[propName];
748
-
749
- if (!propMeta.through) continue; // Skip properties without predicates
750
-
751
- const propShape: SHACLPropertyShape = {
752
- name: propName, // Property name for generating named URIs
753
- path: propMeta.through,
754
- };
755
-
756
- // Determine datatype from initial value or resolveLanguage
757
- if (propMeta.resolveLanguage === "literal") {
758
- // If it resolves via literal language, it's likely a string
759
- propShape.datatype = "xsd://string";
760
- } else if (propMeta.initial) {
761
- // Try to infer from initial value type
762
- const initialType = typeof obj[propName];
763
- if (initialType === "number") {
764
- propShape.datatype = "xsd://integer";
765
- } else if (initialType === "boolean") {
766
- propShape.datatype = "xsd://boolean";
767
- } else if (initialType === "string") {
768
- propShape.datatype = "xsd://string";
769
- }
770
- }
771
-
772
- // Cardinality constraints
773
- if (propMeta.required) {
774
- propShape.minCount = 1;
775
- }
776
-
777
- // Single-valued properties get maxCount 1
778
- // (relations are handled separately below)
779
- propShape.maxCount = 1;
780
-
781
- // Flag properties have fixed value
782
- if (propMeta.flag && propMeta.initial) {
783
- propShape.hasValue = propMeta.initial;
784
- }
785
-
786
- // AD4M-specific metadata
787
- if (propMeta.local !== undefined) {
788
- propShape.local = propMeta.local;
789
- }
790
-
791
- if (propMeta.writable !== undefined) {
792
- propShape.writable = propMeta.writable;
793
- }
794
-
795
- if (propMeta.resolveLanguage) {
796
- propShape.resolveLanguage = propMeta.resolveLanguage;
797
- }
798
-
799
- // === Extract Setter Actions (same logic as generateSDNA) ===
800
- if (propMeta.prologSetter) {
801
- // Custom Prolog setter defined - not yet supported in SHACL
802
- console.warn(
803
- `[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
804
- `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`
805
- );
806
- // TODO: Parse custom Prolog setter to extract actions
807
- } else if (propMeta.writable && propMeta.through) {
808
- let setter = obj[propertyNameToSetterName(propName)];
809
- if (typeof setter === "function") {
810
- propShape.setter = [{
811
- action: "setSingleTarget",
812
- source: "this",
813
- predicate: propMeta.through,
814
- target: "value",
815
- ...(propMeta.local && { local: true })
816
- }];
817
- }
818
- }
819
-
820
- // Add to constructor actions if property has initial value
821
- // Auto-derive effectiveInitial for required, writable, non-flag properties.
822
- // Optional properties (required: false) are excluded — they should
823
- // remain unset (undefined) until explicitly assigned.
824
- const effectiveInitial = propMeta.initial
825
- ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
826
- ? "literal://string:" : undefined);
827
-
828
- if (effectiveInitial) {
829
- constructorActions.push({
830
- action: "addLink",
831
- source: "this",
832
- predicate: propMeta.through,
833
- target: effectiveInitial,
834
- });
835
-
836
- // Add to destructor actions
837
- destructorActions.push({
838
- action: "removeLink",
839
- source: "this",
840
- predicate: propMeta.through,
841
- target: "*",
842
- });
843
- }
844
-
845
- shape.addProperty(propShape);
846
- }
847
-
848
- // Convert relations to SHACL property shapes
849
- // (relations variable already declared above for namespace inference)
850
- for (const relName in relations) {
851
- const relMeta = relations[relName];
852
-
853
- if (!relMeta.predicate) continue;
854
-
855
- const relShape: SHACLPropertyShape = {
856
- name: relName, // Relation name for generating named URIs
857
- path: relMeta.predicate,
858
- // Relations have no maxCount (unlimited)
859
- // minCount defaults to 0 (optional)
860
- };
861
-
862
- // Determine node kind — relations typically contain IRIs
863
- relShape.nodeKind = 'IRI';
864
-
865
- // AD4M-specific metadata
866
- if (relMeta.local !== undefined) {
867
- relShape.local = relMeta.local;
868
- }
869
-
870
- // === Extract Relation Actions (adder/remover) ===
871
- // Adder action - adds a link to the relation
872
- relShape.adder = [{
873
- action: "addLink",
874
- source: "this",
875
- predicate: relMeta.predicate,
876
- target: "value",
877
- ...(relMeta.local && { local: true })
878
- }];
879
-
880
- // Remover action - removes a link from the relation
881
- relShape.remover = [{
882
- action: "removeLink",
883
- source: "this",
884
- predicate: relMeta.predicate,
885
- target: "value",
886
- ...(relMeta.local && { local: true })
887
- }];
888
-
889
- // === Build Getter (conformance filter) ===
890
- // Priority chain:
891
- // 1. Explicit getter string → use verbatim
892
- // 2. `where` clause → compile DSL to SurrealQL getter
893
- // 3. target + filter !== false → auto-derive from shape
894
- if (relMeta.getter) {
895
- relShape.getter = relMeta.getter;
896
- } else if (relMeta.where) {
897
- // Compile Where DSL → SurrealQL getter
898
- try {
899
- const TargetClass = relMeta.target?.();
900
- const targetMetadata = TargetClass
901
- ? (TargetClass as any).getModelMetadata?.() ?? null
902
- : null;
903
-
904
- const conditions = compileWhereClause(
905
- relMeta.where,
906
- targetMetadata,
907
- );
908
-
909
- if (conditions.length > 0) {
910
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
911
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
912
- }
913
- } catch (e) {
914
- // Target metadata may not be available yet
915
- }
916
- } else if (relMeta.target && relMeta.filter !== false) {
917
- try {
918
- const TargetClass = relMeta.target();
919
- const filter = buildConformanceFilter(relMeta.predicate, TargetClass);
920
- if (filter) {
921
- relShape.getter = filter.getter;
922
- relShape.conformanceConditions = filter.conformanceConditions;
923
- }
924
- } catch (e) {
925
- // Target class may not be available yet — getter will be
926
- // absent and runtime will fall back to unfiltered get_links
927
- }
928
- }
929
-
930
- // === sh:class — target shape reference ===
931
- // Always set when a target model is declared, regardless of filter.
932
- // This enables typed construction on the Rust/MCP side.
933
- if (relMeta.target) {
934
- try {
935
- const TargetClass = relMeta.target();
936
- const targetSHACL = (TargetClass as any).generateSHACL?.();
937
- if (targetSHACL?.shape?.nodeShapeUri) {
938
- relShape.class = targetSHACL.shape.nodeShapeUri;
939
- }
940
- } catch (e) {
941
- // Target class may not be available yet
942
- }
943
- }
944
-
945
- shape.addProperty(relShape);
946
- }
947
-
948
- // Always set constructor and destructor actions on the shape, even
949
- // when empty. An empty array serialises to `literal://string:[]`
950
- // which the Rust executor parses as a valid (no-op) command list,
951
- // avoiding "No SHACL constructor found" errors for models whose
952
- // properties are all optional and have no @Flag.
953
- shape.setConstructorActions(constructorActions);
954
- shape.setDestructorActions(destructorActions);
955
-
956
- return {
957
- shape,
958
- name: subjectName
959
- };
960
502
  }
961
503
 
962
504
  Object.defineProperty(target, 'type', {configurable: true});