@coasys/ad4m 0.12.0-dev-whisper-lang → 0.12.0-rc1-dev.1

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 (42) hide show
  1. package/lib/index.cjs +1746 -322
  2. package/lib/index.js +1745 -323
  3. package/lib/src/ai/AIClient.d.ts +1 -1
  4. package/lib/src/ai/AIClient.js +4 -5
  5. package/lib/src/ai/AIResolver.d.ts +1 -1
  6. package/lib/src/ai/AIResolver.js +2 -3
  7. package/lib/src/index.d.ts +2 -0
  8. package/lib/src/index.js +2 -0
  9. package/lib/src/model/Ad4mModel.js +21 -7
  10. package/lib/src/model/decorators.js +196 -6
  11. package/lib/src/model/util.d.ts +1 -1
  12. package/lib/src/model/util.js +15 -12
  13. package/lib/src/perspectives/PerspectiveClient.d.ts +11 -1
  14. package/lib/src/perspectives/PerspectiveClient.js +15 -4
  15. package/lib/src/perspectives/PerspectiveProxy.d.ts +124 -8
  16. package/lib/src/perspectives/PerspectiveProxy.js +573 -274
  17. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -1
  18. package/lib/src/perspectives/PerspectiveResolver.js +5 -4
  19. package/lib/src/schema.gql +2 -2
  20. package/lib/src/shacl/SHACLFlow.d.ts +171 -0
  21. package/lib/src/shacl/SHACLFlow.js +370 -0
  22. package/lib/src/shacl/SHACLFlow.test.d.ts +1 -0
  23. package/lib/src/shacl/SHACLFlow.test.js +205 -0
  24. package/lib/src/shacl/SHACLShape.d.ts +108 -0
  25. package/lib/src/shacl/SHACLShape.js +566 -0
  26. package/lib/src/shacl/SHACLShape.test.d.ts +1 -0
  27. package/lib/src/shacl/SHACLShape.test.js +336 -0
  28. package/lib/src/typeDefs.js +2 -2
  29. package/package.json +1 -2
  30. package/src/ai/AIClient.ts +4 -6
  31. package/src/ai/AIResolver.ts +1 -2
  32. package/src/index.ts +2 -0
  33. package/src/model/Ad4mModel.ts +23 -7
  34. package/src/model/decorators.ts +221 -5
  35. package/src/model/util.ts +15 -12
  36. package/src/perspectives/PerspectiveClient.ts +15 -4
  37. package/src/perspectives/PerspectiveProxy.ts +588 -304
  38. package/src/perspectives/PerspectiveResolver.ts +1 -1
  39. package/src/shacl/SHACLFlow.test.ts +237 -0
  40. package/src/shacl/SHACLFlow.ts +503 -0
  41. package/src/shacl/SHACLShape.test.ts +400 -0
  42. package/src/shacl/SHACLShape.ts +755 -0
package/lib/index.js CHANGED
@@ -4371,14 +4371,6 @@ function capitalize$1(str) {
4371
4371
  function propertyNameToSetterName(property) {
4372
4372
  return `set${capitalize$1(property)}`;
4373
4373
  }
4374
- function singularToPlural(singular) {
4375
- if (singular.endsWith("y")) {
4376
- return singular.slice(0, -1) + "ies";
4377
- }
4378
- else {
4379
- return singular + "s";
4380
- }
4381
- }
4382
4374
  function pluralToSingular(plural) {
4383
4375
  if (plural.endsWith("ies")) {
4384
4376
  return plural.slice(0, -3) + "y";
@@ -4394,27 +4386,10 @@ function pluralToSingular(plural) {
4394
4386
  function collectionToAdderName(collection) {
4395
4387
  return `add${capitalize$1(pluralToSingular(collection))}`;
4396
4388
  }
4397
- // e.g. "addEntry" -> "entries"
4398
- function collectionAdderToName(adderName) {
4399
- let singular = adderName.substring(3);
4400
- let plural = singularToPlural(singular);
4401
- return plural.charAt(0).toLowerCase() + plural.slice(1);
4402
- }
4403
4389
  // e.g. "comments" -> "removeComment"
4404
4390
  function collectionToRemoverName(collection) {
4405
4391
  return `remove${capitalize$1(pluralToSingular(collection))}`;
4406
4392
  }
4407
- // e.g. "removeEntry" -> "entries"
4408
- function collectionRemoverToName(removerName) {
4409
- let singular = removerName.substring(6);
4410
- let plural = singularToPlural(singular);
4411
- return plural.charAt(0).toLowerCase() + plural.slice(1);
4412
- }
4413
- function collectionSetterToName(adderName) {
4414
- let singular = adderName.substring(13);
4415
- let plural = singularToPlural(singular);
4416
- return plural.charAt(0).toLowerCase() + plural.slice(1);
4417
- }
4418
4393
  // e.g. "comments" -> "addComment"
4419
4394
  function collectionToSetterName(collection) {
4420
4395
  return `setCollection${capitalize$1(pluralToSingular(collection))}`;
@@ -4650,6 +4625,943 @@ function escapeSurrealString(value) {
4650
4625
  .replace(/\t/g, '\\t'); // Tab -> \t
4651
4626
  }
4652
4627
 
4628
+ /**
4629
+ * Extract namespace from a URI
4630
+ * Examples:
4631
+ * - "recipe://name" -> "recipe://"
4632
+ * - "https://example.com/vocab#term" -> "https://example.com/vocab#"
4633
+ * - "https://example.com/vocab/term" -> "https://example.com/vocab/"
4634
+ * - "recipe:Recipe" -> "recipe:"
4635
+ */
4636
+ function extractNamespace(uri) {
4637
+ // Handle hash fragments first (highest priority)
4638
+ const hashIndex = uri.lastIndexOf('#');
4639
+ if (hashIndex !== -1) {
4640
+ return uri.substring(0, hashIndex + 1);
4641
+ }
4642
+ // Handle protocol-style URIs with paths
4643
+ const protocolMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)(.*)$/);
4644
+ if (protocolMatch) {
4645
+ const afterScheme = protocolMatch[2];
4646
+ const lastSlash = afterScheme.lastIndexOf('/');
4647
+ if (lastSlash !== -1) {
4648
+ // Has path segments - namespace includes up to last slash
4649
+ return protocolMatch[1] + afterScheme.substring(0, lastSlash + 1);
4650
+ }
4651
+ // Simple protocol URI without path (e.g., "recipe://name")
4652
+ return protocolMatch[1];
4653
+ }
4654
+ // Handle colon-separated (namespace:localName)
4655
+ const colonMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)/);
4656
+ if (colonMatch) {
4657
+ return colonMatch[1];
4658
+ }
4659
+ // Fallback: no clear namespace
4660
+ return '';
4661
+ }
4662
+ /**
4663
+ * Escape special characters for Turtle string literals
4664
+ * Handles backslashes, quotes, newlines, and other control characters
4665
+ */
4666
+ function escapeTurtleString(value) {
4667
+ return value
4668
+ .replace(/\\/g, '\\\\') // Backslash must be first
4669
+ .replace(/"/g, '\\"') // Double quotes
4670
+ .replace(/\n/g, '\\n') // Newlines
4671
+ .replace(/\r/g, '\\r') // Carriage returns
4672
+ .replace(/\t/g, '\\t') // Tabs
4673
+ .replace(/\b/g, '\\b') // Backspace
4674
+ .replace(/\f/g, '\\f'); // Form feed
4675
+ }
4676
+ /**
4677
+ * Extract local name from a URI
4678
+ * Examples:
4679
+ * - "recipe://name" -> "name"
4680
+ * - "https://example.com/vocab#term" -> "term"
4681
+ * - "https://example.com/vocab/term" -> "term"
4682
+ * - "recipe:Recipe" -> "Recipe"
4683
+ */
4684
+ function extractLocalName(uri) {
4685
+ // Handle hash fragments
4686
+ const hashIndex = uri.lastIndexOf('#');
4687
+ if (hashIndex !== -1) {
4688
+ return uri.substring(hashIndex + 1);
4689
+ }
4690
+ // Handle slash-based namespaces
4691
+ const lastSlash = uri.lastIndexOf('/');
4692
+ if (lastSlash !== -1 && lastSlash < uri.length - 1) {
4693
+ return uri.substring(lastSlash + 1);
4694
+ }
4695
+ // Handle colon-separated
4696
+ const colonMatch = uri.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:(.+)$/);
4697
+ if (colonMatch) {
4698
+ return colonMatch[1];
4699
+ }
4700
+ // Fallback: entire URI
4701
+ return uri;
4702
+ }
4703
+ /**
4704
+ * SHACL Node Shape
4705
+ * Defines constraints for instances of a class
4706
+ */
4707
+ class SHACLShape {
4708
+ /**
4709
+ * Create a new SHACL Shape
4710
+ * @param targetClassOrShapeUri - If one argument: the target class (shape URI auto-derived as {class}Shape)
4711
+ * If two arguments: first is shape URI, second is target class
4712
+ * @param targetClass - Optional target class when first arg is shape URI
4713
+ */
4714
+ constructor(targetClassOrShapeUri, targetClass) {
4715
+ if (targetClass !== undefined) {
4716
+ // Two arguments: explicit shape URI and target class
4717
+ this.nodeShapeUri = targetClassOrShapeUri;
4718
+ this.targetClass = targetClass;
4719
+ }
4720
+ else {
4721
+ // One argument: derive shape URI from target class
4722
+ this.targetClass = targetClassOrShapeUri;
4723
+ // Derive shape URI by appending "Shape" to the local name
4724
+ const namespace = extractNamespace(targetClassOrShapeUri);
4725
+ const localName = extractLocalName(targetClassOrShapeUri);
4726
+ this.nodeShapeUri = `${namespace}${localName}Shape`;
4727
+ }
4728
+ this.properties = [];
4729
+ }
4730
+ /**
4731
+ * Add a property constraint to this shape
4732
+ */
4733
+ addProperty(prop) {
4734
+ this.properties.push(prop);
4735
+ }
4736
+ /**
4737
+ * Set constructor actions for this shape
4738
+ */
4739
+ setConstructorActions(actions) {
4740
+ this.constructor_actions = actions;
4741
+ }
4742
+ /**
4743
+ * Set destructor actions for this shape
4744
+ */
4745
+ setDestructorActions(actions) {
4746
+ this.destructor_actions = actions;
4747
+ }
4748
+ /**
4749
+ * Serialize shape to Turtle (RDF) format
4750
+ */
4751
+ toTurtle() {
4752
+ let turtle = `@prefix sh: <http://www.w3.org/ns/shacl#> .\n`;
4753
+ turtle += `@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n`;
4754
+ turtle += `@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n`;
4755
+ turtle += `@prefix ad4m: <ad4m://> .\n\n`;
4756
+ turtle += `<${this.nodeShapeUri}>\n`;
4757
+ turtle += ` a sh:NodeShape ;\n`;
4758
+ if (this.targetClass) {
4759
+ turtle += ` sh:targetClass <${this.targetClass}> ;\n`;
4760
+ }
4761
+ // Add property shapes
4762
+ for (let i = 0; i < this.properties.length; i++) {
4763
+ const prop = this.properties[i];
4764
+ const isLast = i === this.properties.length - 1;
4765
+ turtle += ` sh:property [\n`;
4766
+ turtle += ` sh:path <${prop.path}> ;\n`;
4767
+ if (prop.datatype) {
4768
+ turtle += ` sh:datatype <${prop.datatype}> ;\n`;
4769
+ }
4770
+ if (prop.nodeKind) {
4771
+ turtle += ` sh:nodeKind sh:${prop.nodeKind} ;\n`;
4772
+ }
4773
+ if (prop.minCount !== undefined) {
4774
+ turtle += ` sh:minCount ${prop.minCount} ;\n`;
4775
+ }
4776
+ if (prop.maxCount !== undefined) {
4777
+ turtle += ` sh:maxCount ${prop.maxCount} ;\n`;
4778
+ }
4779
+ if (prop.pattern) {
4780
+ turtle += ` sh:pattern "${escapeTurtleString(prop.pattern)}" ;\n`;
4781
+ }
4782
+ if (prop.minInclusive !== undefined) {
4783
+ turtle += ` sh:minInclusive ${prop.minInclusive} ;\n`;
4784
+ }
4785
+ if (prop.maxInclusive !== undefined) {
4786
+ turtle += ` sh:maxInclusive ${prop.maxInclusive} ;\n`;
4787
+ }
4788
+ if (prop.hasValue) {
4789
+ turtle += ` sh:hasValue "${escapeTurtleString(prop.hasValue)}" ;\n`;
4790
+ }
4791
+ // AD4M-specific metadata
4792
+ if (prop.local !== undefined) {
4793
+ turtle += ` ad4m:local ${prop.local} ;\n`;
4794
+ }
4795
+ if (prop.writable !== undefined) {
4796
+ turtle += ` ad4m:writable ${prop.writable} ;\n`;
4797
+ }
4798
+ // Remove trailing semicolon and close bracket
4799
+ turtle = turtle.slice(0, -2) + '\n';
4800
+ turtle += isLast ? ` ] .\n` : ` ] ;\n`;
4801
+ }
4802
+ return turtle;
4803
+ }
4804
+ /**
4805
+ * Serialize shape to AD4M Links (RDF triples)
4806
+ * Stores the shape as a graph of links in a Perspective
4807
+ */
4808
+ toLinks() {
4809
+ const links = [];
4810
+ // Shape type declaration
4811
+ links.push({
4812
+ source: this.nodeShapeUri,
4813
+ predicate: "rdf://type",
4814
+ target: "sh://NodeShape"
4815
+ });
4816
+ // Target class
4817
+ if (this.targetClass) {
4818
+ links.push({
4819
+ source: this.nodeShapeUri,
4820
+ predicate: "sh://targetClass",
4821
+ target: this.targetClass
4822
+ });
4823
+ }
4824
+ // Constructor actions
4825
+ if (this.constructor_actions && this.constructor_actions.length > 0) {
4826
+ links.push({
4827
+ source: this.nodeShapeUri,
4828
+ predicate: "ad4m://constructor",
4829
+ target: `literal://string:${JSON.stringify(this.constructor_actions)}`
4830
+ });
4831
+ }
4832
+ // Destructor actions
4833
+ if (this.destructor_actions && this.destructor_actions.length > 0) {
4834
+ links.push({
4835
+ source: this.nodeShapeUri,
4836
+ predicate: "ad4m://destructor",
4837
+ target: `literal://string:${JSON.stringify(this.destructor_actions)}`
4838
+ });
4839
+ }
4840
+ // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})
4841
+ for (let i = 0; i < this.properties.length; i++) {
4842
+ const prop = this.properties[i];
4843
+ // Generate named property shape URI
4844
+ let propShapeId;
4845
+ if (prop.name && this.targetClass) {
4846
+ // Extract namespace from targetClass
4847
+ const namespace = extractNamespace(this.targetClass);
4848
+ const className = extractLocalName(this.targetClass);
4849
+ // Use format: {namespace}{ClassName}.{propertyName}
4850
+ propShapeId = `${namespace}${className}.${prop.name}`;
4851
+ }
4852
+ else {
4853
+ // Fallback to blank node if name is missing
4854
+ propShapeId = `_:propShape${i}`;
4855
+ }
4856
+ // Link shape to property shape
4857
+ links.push({
4858
+ source: this.nodeShapeUri,
4859
+ predicate: "sh://property",
4860
+ target: propShapeId
4861
+ });
4862
+ // Property path
4863
+ links.push({
4864
+ source: propShapeId,
4865
+ predicate: "sh://path",
4866
+ target: prop.path
4867
+ });
4868
+ // Constraints
4869
+ if (prop.datatype) {
4870
+ links.push({
4871
+ source: propShapeId,
4872
+ predicate: "sh://datatype",
4873
+ target: prop.datatype
4874
+ });
4875
+ }
4876
+ if (prop.nodeKind) {
4877
+ links.push({
4878
+ source: propShapeId,
4879
+ predicate: "sh://nodeKind",
4880
+ target: `sh://${prop.nodeKind}`
4881
+ });
4882
+ }
4883
+ if (prop.minCount !== undefined) {
4884
+ links.push({
4885
+ source: propShapeId,
4886
+ predicate: "sh://minCount",
4887
+ target: `literal://${prop.minCount}^^xsd:integer`
4888
+ });
4889
+ }
4890
+ if (prop.maxCount !== undefined) {
4891
+ links.push({
4892
+ source: propShapeId,
4893
+ predicate: "sh://maxCount",
4894
+ target: `literal://${prop.maxCount}^^xsd:integer`
4895
+ });
4896
+ }
4897
+ if (prop.pattern) {
4898
+ links.push({
4899
+ source: propShapeId,
4900
+ predicate: "sh://pattern",
4901
+ target: `literal://${prop.pattern}`
4902
+ });
4903
+ }
4904
+ if (prop.minInclusive !== undefined) {
4905
+ links.push({
4906
+ source: propShapeId,
4907
+ predicate: "sh://minInclusive",
4908
+ target: `literal://${prop.minInclusive}`
4909
+ });
4910
+ }
4911
+ if (prop.maxInclusive !== undefined) {
4912
+ links.push({
4913
+ source: propShapeId,
4914
+ predicate: "sh://maxInclusive",
4915
+ target: `literal://${prop.maxInclusive}`
4916
+ });
4917
+ }
4918
+ if (prop.hasValue) {
4919
+ links.push({
4920
+ source: propShapeId,
4921
+ predicate: "sh://hasValue",
4922
+ target: `literal://${prop.hasValue}`
4923
+ });
4924
+ }
4925
+ // AD4M-specific metadata
4926
+ if (prop.local !== undefined) {
4927
+ links.push({
4928
+ source: propShapeId,
4929
+ predicate: "ad4m://local",
4930
+ target: `literal://${prop.local}`
4931
+ });
4932
+ }
4933
+ if (prop.writable !== undefined) {
4934
+ links.push({
4935
+ source: propShapeId,
4936
+ predicate: "ad4m://writable",
4937
+ target: `literal://${prop.writable}`
4938
+ });
4939
+ }
4940
+ if (prop.resolveLanguage) {
4941
+ links.push({
4942
+ source: propShapeId,
4943
+ predicate: "ad4m://resolveLanguage",
4944
+ target: `literal://string:${prop.resolveLanguage}`
4945
+ });
4946
+ }
4947
+ // AD4M-specific actions
4948
+ if (prop.setter && prop.setter.length > 0) {
4949
+ links.push({
4950
+ source: propShapeId,
4951
+ predicate: "ad4m://setter",
4952
+ target: `literal://string:${JSON.stringify(prop.setter)}`
4953
+ });
4954
+ }
4955
+ if (prop.adder && prop.adder.length > 0) {
4956
+ links.push({
4957
+ source: propShapeId,
4958
+ predicate: "ad4m://adder",
4959
+ target: `literal://string:${JSON.stringify(prop.adder)}`
4960
+ });
4961
+ }
4962
+ if (prop.remover && prop.remover.length > 0) {
4963
+ links.push({
4964
+ source: propShapeId,
4965
+ predicate: "ad4m://remover",
4966
+ target: `literal://string:${JSON.stringify(prop.remover)}`
4967
+ });
4968
+ }
4969
+ }
4970
+ return links;
4971
+ }
4972
+ /**
4973
+ * Reconstruct shape from AD4M Links
4974
+ */
4975
+ static fromLinks(links, shapeUri) {
4976
+ // Find target class
4977
+ const targetClassLink = links.find(l => l.source === shapeUri && l.predicate === "sh://targetClass");
4978
+ const shape = new SHACLShape(shapeUri, targetClassLink?.target);
4979
+ // Find constructor actions
4980
+ const constructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://constructor");
4981
+ if (constructorLink) {
4982
+ try {
4983
+ const jsonStr = constructorLink.target.replace('literal://string:', '');
4984
+ shape.constructor_actions = JSON.parse(jsonStr);
4985
+ }
4986
+ catch (e) {
4987
+ // Ignore parse errors
4988
+ }
4989
+ }
4990
+ // Find destructor actions
4991
+ const destructorLink = links.find(l => l.source === shapeUri && l.predicate === "ad4m://destructor");
4992
+ if (destructorLink) {
4993
+ try {
4994
+ const jsonStr = destructorLink.target.replace('literal://string:', '');
4995
+ shape.destructor_actions = JSON.parse(jsonStr);
4996
+ }
4997
+ catch (e) {
4998
+ // Ignore parse errors
4999
+ }
5000
+ }
5001
+ // Find all property shapes
5002
+ const propShapeLinks = links.filter(l => l.source === shapeUri && l.predicate === "sh://property");
5003
+ for (const propLink of propShapeLinks) {
5004
+ const propShapeId = propLink.target;
5005
+ // Reconstruct property from its links
5006
+ const pathLink = links.find(l => l.source === propShapeId && l.predicate === "sh://path");
5007
+ if (!pathLink)
5008
+ continue;
5009
+ // Extract property name from propShapeId if it's a named URI
5010
+ // Format: {namespace}{ClassName}.{propertyName}
5011
+ let propertyName;
5012
+ if (!propShapeId.startsWith('_:')) {
5013
+ const lastDotIndex = propShapeId.lastIndexOf('.');
5014
+ if (lastDotIndex !== -1) {
5015
+ propertyName = propShapeId.substring(lastDotIndex + 1);
5016
+ }
5017
+ }
5018
+ const prop = {
5019
+ name: propertyName,
5020
+ path: pathLink.target
5021
+ };
5022
+ // Extract constraints
5023
+ const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === "sh://datatype");
5024
+ if (datatypeLink)
5025
+ prop.datatype = datatypeLink.target;
5026
+ const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === "sh://nodeKind");
5027
+ if (nodeKindLink) {
5028
+ prop.nodeKind = nodeKindLink.target.replace('sh://', '');
5029
+ }
5030
+ const minCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minCount");
5031
+ if (minCountLink) {
5032
+ // Handle both formats: literal://5^^xsd:integer and literal://number:5
5033
+ let val = minCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5034
+ if (val.startsWith('number:'))
5035
+ val = val.substring(7);
5036
+ prop.minCount = parseInt(val);
5037
+ }
5038
+ const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxCount");
5039
+ if (maxCountLink) {
5040
+ // Handle both formats: literal://5^^xsd:integer and literal://number:5
5041
+ let val = maxCountLink.target.replace('literal://', '').replace(/\^\^.*$/, '');
5042
+ if (val.startsWith('number:'))
5043
+ val = val.substring(7);
5044
+ prop.maxCount = parseInt(val);
5045
+ }
5046
+ const patternLink = links.find(l => l.source === propShapeId && l.predicate === "sh://pattern");
5047
+ if (patternLink) {
5048
+ prop.pattern = patternLink.target.replace('literal://', '');
5049
+ }
5050
+ const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://minInclusive");
5051
+ if (minInclusiveLink) {
5052
+ // Handle both formats: literal://5 and literal://number:5
5053
+ let val = minInclusiveLink.target.replace('literal://', '');
5054
+ if (val.startsWith('number:'))
5055
+ val = val.substring(7);
5056
+ prop.minInclusive = parseFloat(val);
5057
+ }
5058
+ const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === "sh://maxInclusive");
5059
+ if (maxInclusiveLink) {
5060
+ // Handle both formats: literal://5 and literal://number:5
5061
+ let val = maxInclusiveLink.target.replace('literal://', '');
5062
+ if (val.startsWith('number:'))
5063
+ val = val.substring(7);
5064
+ prop.maxInclusive = parseFloat(val);
5065
+ }
5066
+ const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === "sh://hasValue");
5067
+ if (hasValueLink) {
5068
+ prop.hasValue = hasValueLink.target.replace('literal://', '');
5069
+ }
5070
+ // AD4M-specific
5071
+ const localLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://local");
5072
+ if (localLink) {
5073
+ // Handle both formats: literal://true and literal://boolean:true
5074
+ let val = localLink.target.replace('literal://', '');
5075
+ if (val.startsWith('boolean:'))
5076
+ val = val.substring(8);
5077
+ prop.local = val === 'true';
5078
+ }
5079
+ const writableLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://writable");
5080
+ if (writableLink) {
5081
+ // Handle both formats: literal://true and literal://boolean:true
5082
+ let val = writableLink.target.replace('literal://', '');
5083
+ if (val.startsWith('boolean:'))
5084
+ val = val.substring(8);
5085
+ prop.writable = val === 'true';
5086
+ }
5087
+ const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://resolveLanguage");
5088
+ if (resolveLangLink) {
5089
+ prop.resolveLanguage = resolveLangLink.target.replace('literal://string:', '');
5090
+ }
5091
+ // Parse action arrays
5092
+ const setterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://setter");
5093
+ if (setterLink) {
5094
+ try {
5095
+ const jsonStr = setterLink.target.replace('literal://string:', '');
5096
+ prop.setter = JSON.parse(jsonStr);
5097
+ }
5098
+ catch (e) {
5099
+ // Ignore parse errors
5100
+ }
5101
+ }
5102
+ const adderLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://adder");
5103
+ if (adderLink) {
5104
+ try {
5105
+ const jsonStr = adderLink.target.replace('literal://string:', '');
5106
+ prop.adder = JSON.parse(jsonStr);
5107
+ }
5108
+ catch (e) {
5109
+ // Ignore parse errors
5110
+ }
5111
+ }
5112
+ const removerLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://remover");
5113
+ if (removerLink) {
5114
+ try {
5115
+ const jsonStr = removerLink.target.replace('literal://string:', '');
5116
+ prop.remover = JSON.parse(jsonStr);
5117
+ }
5118
+ catch (e) {
5119
+ // Ignore parse errors
5120
+ }
5121
+ }
5122
+ shape.addProperty(prop);
5123
+ }
5124
+ return shape;
5125
+ }
5126
+ /**
5127
+ * Convert the shape to a JSON-serializable object.
5128
+ * Useful for passing to addSdna() as shaclJson parameter.
5129
+ *
5130
+ * @returns JSON-serializable object representing the shape
5131
+ */
5132
+ toJSON() {
5133
+ return {
5134
+ node_shape_uri: this.nodeShapeUri,
5135
+ target_class: this.targetClass,
5136
+ properties: this.properties.map(p => ({
5137
+ path: p.path,
5138
+ name: p.name,
5139
+ datatype: p.datatype,
5140
+ node_kind: p.nodeKind,
5141
+ min_count: p.minCount,
5142
+ max_count: p.maxCount,
5143
+ min_inclusive: p.minInclusive,
5144
+ max_inclusive: p.maxInclusive,
5145
+ pattern: p.pattern,
5146
+ has_value: p.hasValue,
5147
+ local: p.local,
5148
+ writable: p.writable,
5149
+ resolve_language: p.resolveLanguage,
5150
+ setter: p.setter,
5151
+ adder: p.adder,
5152
+ remover: p.remover,
5153
+ })),
5154
+ constructor_actions: this.constructor_actions,
5155
+ destructor_actions: this.destructor_actions,
5156
+ };
5157
+ }
5158
+ /**
5159
+ * Create a shape from a JSON object (inverse of toJSON)
5160
+ */
5161
+ static fromJSON(json) {
5162
+ const shape = json.node_shape_uri
5163
+ ? new SHACLShape(json.node_shape_uri, json.target_class)
5164
+ : new SHACLShape(json.target_class);
5165
+ for (const p of json.properties || []) {
5166
+ shape.addProperty({
5167
+ path: p.path,
5168
+ name: p.name,
5169
+ datatype: p.datatype,
5170
+ nodeKind: p.node_kind,
5171
+ minCount: p.min_count,
5172
+ maxCount: p.max_count,
5173
+ minInclusive: p.min_inclusive,
5174
+ maxInclusive: p.max_inclusive,
5175
+ pattern: p.pattern,
5176
+ hasValue: p.has_value,
5177
+ local: p.local,
5178
+ writable: p.writable,
5179
+ resolveLanguage: p.resolve_language,
5180
+ setter: p.setter,
5181
+ adder: p.adder,
5182
+ remover: p.remover,
5183
+ });
5184
+ }
5185
+ if (json.constructor_actions) {
5186
+ shape.constructor_actions = json.constructor_actions;
5187
+ }
5188
+ if (json.destructor_actions) {
5189
+ shape.destructor_actions = json.destructor_actions;
5190
+ }
5191
+ return shape;
5192
+ }
5193
+ }
5194
+
5195
+ /**
5196
+ * SHACL Flow - represents a state machine for AD4M expressions
5197
+ *
5198
+ * Flows define:
5199
+ * - Which expressions can enter the flow (flowable condition)
5200
+ * - What states exist and how to detect them (via link patterns)
5201
+ * - How to transition between states (via actions)
5202
+ *
5203
+ * @example
5204
+ * ```typescript
5205
+ * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');
5206
+ *
5207
+ * // Any expression can become a TODO
5208
+ * todoFlow.flowable = 'any';
5209
+ *
5210
+ * // Define states
5211
+ * todoFlow.addState({
5212
+ * name: 'ready',
5213
+ * value: 0,
5214
+ * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }
5215
+ * });
5216
+ * todoFlow.addState({
5217
+ * name: 'doing',
5218
+ * value: 0.5,
5219
+ * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }
5220
+ * });
5221
+ * todoFlow.addState({
5222
+ * name: 'done',
5223
+ * value: 1,
5224
+ * stateCheck: { predicate: 'todo://state', target: 'todo://done' }
5225
+ * });
5226
+ *
5227
+ * // Define start action
5228
+ * todoFlow.startAction = [{
5229
+ * action: 'addLink',
5230
+ * source: 'this',
5231
+ * predicate: 'todo://state',
5232
+ * target: 'todo://ready'
5233
+ * }];
5234
+ *
5235
+ * // Define transitions
5236
+ * todoFlow.addTransition({
5237
+ * actionName: 'Start',
5238
+ * fromState: 'ready',
5239
+ * toState: 'doing',
5240
+ * actions: [
5241
+ * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },
5242
+ * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
5243
+ * ]
5244
+ * });
5245
+ *
5246
+ * // Store in perspective
5247
+ * await perspective.addFlow('TODO', todoFlow);
5248
+ * ```
5249
+ */
5250
+ class SHACLFlow {
5251
+ /**
5252
+ * Create a new SHACL Flow
5253
+ * @param name - Flow name (e.g., "TODO")
5254
+ * @param namespace - Namespace for URIs (e.g., "todo://")
5255
+ */
5256
+ constructor(name, namespace) {
5257
+ /** Condition for which expressions can start this flow */
5258
+ this.flowable = "any";
5259
+ /** Actions to execute when starting the flow */
5260
+ this.startAction = [];
5261
+ /** States in this flow */
5262
+ this._states = [];
5263
+ /** Transitions between states */
5264
+ this._transitions = [];
5265
+ this.name = name;
5266
+ this.namespace = namespace;
5267
+ }
5268
+ /** Get all states */
5269
+ get states() {
5270
+ return [...this._states];
5271
+ }
5272
+ /** Get all transitions */
5273
+ get transitions() {
5274
+ return [...this._transitions];
5275
+ }
5276
+ /**
5277
+ * Add a state to the flow
5278
+ * @param state - State definition
5279
+ */
5280
+ addState(state) {
5281
+ this._states.push(state);
5282
+ }
5283
+ /**
5284
+ * Add a transition to the flow
5285
+ * @param transition - Transition definition
5286
+ */
5287
+ addTransition(transition) {
5288
+ this._transitions.push(transition);
5289
+ }
5290
+ /**
5291
+ * Get the flow shape URI
5292
+ */
5293
+ get flowUri() {
5294
+ return `${this.namespace}${this.name}Flow`;
5295
+ }
5296
+ /**
5297
+ * Get a state URI
5298
+ */
5299
+ stateUri(stateName) {
5300
+ return `${this.namespace}${this.name}.${stateName}`;
5301
+ }
5302
+ /**
5303
+ * Get a transition URI
5304
+ */
5305
+ transitionUri(fromState, toState) {
5306
+ return `${this.namespace}${this.name}.${fromState}To${toState}`;
5307
+ }
5308
+ /**
5309
+ * Serialize the flow to AD4M links
5310
+ * These links can be stored in a perspective and queried via SurrealDB
5311
+ *
5312
+ * @returns Array of Link objects representing the flow
5313
+ */
5314
+ toLinks() {
5315
+ const links = [];
5316
+ const flowUri = this.flowUri;
5317
+ // Flow type
5318
+ links.push({
5319
+ source: flowUri,
5320
+ predicate: "rdf://type",
5321
+ target: "ad4m://Flow"
5322
+ });
5323
+ // Flow name
5324
+ links.push({
5325
+ source: flowUri,
5326
+ predicate: "ad4m://flowName",
5327
+ target: Literal.from(this.name).toUrl()
5328
+ });
5329
+ // Flowable condition
5330
+ if (this.flowable === "any") {
5331
+ links.push({
5332
+ source: flowUri,
5333
+ predicate: "ad4m://flowable",
5334
+ target: "ad4m://any"
5335
+ });
5336
+ }
5337
+ else {
5338
+ links.push({
5339
+ source: flowUri,
5340
+ predicate: "ad4m://flowable",
5341
+ target: `literal://string:${encodeURIComponent(JSON.stringify(this.flowable))}`
5342
+ });
5343
+ }
5344
+ // Start action
5345
+ if (this.startAction.length > 0) {
5346
+ links.push({
5347
+ source: flowUri,
5348
+ predicate: "ad4m://startAction",
5349
+ target: `literal://string:${encodeURIComponent(JSON.stringify(this.startAction))}`
5350
+ });
5351
+ }
5352
+ // States
5353
+ for (const state of this._states) {
5354
+ const stateUri = this.stateUri(state.name);
5355
+ // Link flow to state
5356
+ links.push({
5357
+ source: flowUri,
5358
+ predicate: "ad4m://hasState",
5359
+ target: stateUri
5360
+ });
5361
+ // State type
5362
+ links.push({
5363
+ source: stateUri,
5364
+ predicate: "rdf://type",
5365
+ target: "ad4m://FlowState"
5366
+ });
5367
+ // State name
5368
+ links.push({
5369
+ source: stateUri,
5370
+ predicate: "ad4m://stateName",
5371
+ target: Literal.from(state.name).toUrl()
5372
+ });
5373
+ // State value
5374
+ links.push({
5375
+ source: stateUri,
5376
+ predicate: "ad4m://stateValue",
5377
+ target: Literal.from(state.value).toUrl()
5378
+ });
5379
+ // State check pattern
5380
+ links.push({
5381
+ source: stateUri,
5382
+ predicate: "ad4m://stateCheck",
5383
+ target: `literal://string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`
5384
+ });
5385
+ }
5386
+ // Transitions
5387
+ for (const transition of this._transitions) {
5388
+ const transitionUri = this.transitionUri(transition.fromState, transition.toState);
5389
+ const fromStateUri = this.stateUri(transition.fromState);
5390
+ const toStateUri = this.stateUri(transition.toState);
5391
+ // Link flow to transition
5392
+ links.push({
5393
+ source: flowUri,
5394
+ predicate: "ad4m://hasTransition",
5395
+ target: transitionUri
5396
+ });
5397
+ // Transition type
5398
+ links.push({
5399
+ source: transitionUri,
5400
+ predicate: "rdf://type",
5401
+ target: "ad4m://FlowTransition"
5402
+ });
5403
+ // Action name
5404
+ links.push({
5405
+ source: transitionUri,
5406
+ predicate: "ad4m://actionName",
5407
+ target: Literal.from(transition.actionName).toUrl()
5408
+ });
5409
+ // From state
5410
+ links.push({
5411
+ source: transitionUri,
5412
+ predicate: "ad4m://fromState",
5413
+ target: fromStateUri
5414
+ });
5415
+ // To state
5416
+ links.push({
5417
+ source: transitionUri,
5418
+ predicate: "ad4m://toState",
5419
+ target: toStateUri
5420
+ });
5421
+ // Transition actions
5422
+ links.push({
5423
+ source: transitionUri,
5424
+ predicate: "ad4m://transitionActions",
5425
+ target: `literal://string:${encodeURIComponent(JSON.stringify(transition.actions))}`
5426
+ });
5427
+ }
5428
+ return links;
5429
+ }
5430
+ /**
5431
+ * Reconstruct a SHACLFlow from links
5432
+ *
5433
+ * @param links - Array of links containing the flow definition
5434
+ * @param flowUri - The URI of the flow to reconstruct
5435
+ * @returns Reconstructed SHACLFlow
5436
+ */
5437
+ static fromLinks(links, flowUri) {
5438
+ // Extract namespace and name from flowUri
5439
+ // Format: {namespace}{Name}Flow
5440
+ const flowSuffix = "Flow";
5441
+ if (!flowUri.endsWith(flowSuffix)) {
5442
+ throw new Error(`Invalid flow URI: ${flowUri} (must end with 'Flow')`);
5443
+ }
5444
+ const withoutSuffix = flowUri.slice(0, -flowSuffix.length);
5445
+ const lastSlashOrColon = Math.max(withoutSuffix.lastIndexOf('/'), withoutSuffix.lastIndexOf(':'));
5446
+ const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);
5447
+ const name = withoutSuffix.slice(lastSlashOrColon + 1);
5448
+ const flow = new SHACLFlow(name, namespace);
5449
+ // Find flowable condition
5450
+ const flowableLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://flowable");
5451
+ if (flowableLink) {
5452
+ if (flowableLink.target === "ad4m://any") {
5453
+ flow.flowable = "any";
5454
+ }
5455
+ else {
5456
+ try {
5457
+ const jsonStr = flowableLink.target.replace('literal://string:', '');
5458
+ flow.flowable = JSON.parse(decodeURIComponent(jsonStr));
5459
+ }
5460
+ catch {
5461
+ flow.flowable = "any";
5462
+ }
5463
+ }
5464
+ }
5465
+ // Find start action
5466
+ const startActionLink = links.find(l => l.source === flowUri && l.predicate === "ad4m://startAction");
5467
+ if (startActionLink) {
5468
+ try {
5469
+ const jsonStr = startActionLink.target.replace('literal://string:', '');
5470
+ flow.startAction = JSON.parse(decodeURIComponent(jsonStr));
5471
+ }
5472
+ catch {
5473
+ // Ignore parse errors
5474
+ }
5475
+ }
5476
+ // Find states
5477
+ const stateLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasState");
5478
+ // Build a map from state URI to state name for later lookup
5479
+ const stateUriToName = new Map();
5480
+ for (const stateLink of stateLinks) {
5481
+ const stateUri = stateLink.target;
5482
+ // Get state name
5483
+ const nameLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateName");
5484
+ const stateName = nameLink ? Literal.fromUrl(nameLink.target).get() : "";
5485
+ // Store mapping for transition lookup
5486
+ stateUriToName.set(stateUri, stateName);
5487
+ // Get state value
5488
+ const valueLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateValue");
5489
+ const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;
5490
+ // Get state check
5491
+ const checkLink = links.find(l => l.source === stateUri && l.predicate === "ad4m://stateCheck");
5492
+ let stateCheck = { predicate: "", target: "" };
5493
+ if (checkLink) {
5494
+ try {
5495
+ const jsonStr = checkLink.target.replace('literal://string:', '');
5496
+ stateCheck = JSON.parse(decodeURIComponent(jsonStr));
5497
+ }
5498
+ catch {
5499
+ // Ignore parse errors
5500
+ }
5501
+ }
5502
+ flow.addState({ name: stateName, value: stateValue, stateCheck });
5503
+ }
5504
+ // Find transitions
5505
+ const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === "ad4m://hasTransition");
5506
+ for (const transitionLink of transitionLinks) {
5507
+ const transitionUri = transitionLink.target;
5508
+ // Get action name
5509
+ const actionNameLink = links.find(l => l.source === transitionUri && l.predicate === "ad4m://actionName");
5510
+ const actionName = actionNameLink ? Literal.fromUrl(actionNameLink.target).get() : "";
5511
+ // Get from state
5512
+ const fromStateLink = links.find(l => l.source === transitionUri && l.predicate === "ad4m://fromState");
5513
+ const fromStateUri = fromStateLink?.target || "";
5514
+ const fromState = stateUriToName.get(fromStateUri) || "";
5515
+ // Get to state
5516
+ const toStateLink = links.find(l => l.source === transitionUri && l.predicate === "ad4m://toState");
5517
+ const toStateUri = toStateLink?.target || "";
5518
+ const toState = stateUriToName.get(toStateUri) || "";
5519
+ // Get actions
5520
+ const actionsLink = links.find(l => l.source === transitionUri && l.predicate === "ad4m://transitionActions");
5521
+ let actions = [];
5522
+ if (actionsLink) {
5523
+ try {
5524
+ const jsonStr = actionsLink.target.replace('literal://string:', '');
5525
+ actions = JSON.parse(decodeURIComponent(jsonStr));
5526
+ }
5527
+ catch {
5528
+ // Ignore parse errors
5529
+ }
5530
+ }
5531
+ flow.addTransition({ actionName, fromState, toState, actions });
5532
+ }
5533
+ return flow;
5534
+ }
5535
+ /**
5536
+ * Convert to JSON representation
5537
+ */
5538
+ toJSON() {
5539
+ return {
5540
+ name: this.name,
5541
+ namespace: this.namespace,
5542
+ flowable: this.flowable,
5543
+ startAction: this.startAction,
5544
+ states: this._states,
5545
+ transitions: this._transitions
5546
+ };
5547
+ }
5548
+ /**
5549
+ * Create from JSON representation
5550
+ */
5551
+ static fromJSON(json) {
5552
+ const flow = new SHACLFlow(json.name, json.namespace);
5553
+ flow.flowable = json.flowable || "any";
5554
+ flow.startAction = json.startAction || [];
5555
+ for (const state of json.states || []) {
5556
+ flow.addState(state);
5557
+ }
5558
+ for (const transition of json.transitions || []) {
5559
+ flow.addTransition(transition);
5560
+ }
5561
+ return flow;
5562
+ }
5563
+ }
5564
+
4653
5565
  var __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
4654
5566
  if (kind === "m") throw new TypeError("Private method is not writable");
4655
5567
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
@@ -5424,42 +6336,129 @@ class PerspectiveProxy {
5424
6336
  }
5425
6337
  /** Returns all the Social DNA flows defined in this perspective */
5426
6338
  async sdnaFlows() {
5427
- const allFlows = await this.infer("register_sdna_flow(X, _)");
5428
- return allFlows.map(x => x.X);
6339
+ // Query for all flow registration links
6340
+ const flowLinks = await this.get(new LinkQuery({
6341
+ source: "ad4m://self",
6342
+ predicate: "ad4m://has_flow"
6343
+ }));
6344
+ return flowLinks.map(l => {
6345
+ try {
6346
+ return Literal.fromUrl(l.data.target).get();
6347
+ }
6348
+ catch {
6349
+ return l.data.target;
6350
+ }
6351
+ });
5429
6352
  }
5430
6353
  /** Returns all Social DNA flows that can be started from the given expression */
5431
6354
  async availableFlows(exprAddr) {
5432
- const availableFlows = await this.infer(`flowable("${exprAddr}", F), register_sdna_flow(X, F)`);
5433
- return availableFlows.map(x => x.X);
6355
+ const allFlowNames = await this.sdnaFlows();
6356
+ const available = [];
6357
+ for (const name of allFlowNames) {
6358
+ const flow = await this.getFlow(name);
6359
+ if (!flow)
6360
+ continue;
6361
+ if (flow.flowable === "any") {
6362
+ available.push(name);
6363
+ }
6364
+ else {
6365
+ // Check if the expression matches the flowable link pattern
6366
+ const pattern = flow.flowable;
6367
+ const source = pattern.source || exprAddr;
6368
+ const links = await this.get(new LinkQuery({
6369
+ source,
6370
+ predicate: pattern.predicate,
6371
+ target: pattern.target
6372
+ }));
6373
+ if (links.length > 0) {
6374
+ available.push(name);
6375
+ }
6376
+ }
6377
+ }
6378
+ return available;
5434
6379
  }
5435
6380
  /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
5436
6381
  async startFlow(flowName, exprAddr) {
5437
- let startAction = await this.infer(`start_action(Action, F), register_sdna_flow("${flowName}", F)`);
5438
- // should always return one solution...
5439
- startAction = eval(startAction[0].Action);
5440
- await this.executeAction(startAction, exprAddr, undefined);
6382
+ const flow = await this.getFlow(flowName);
6383
+ if (!flow)
6384
+ throw `Flow "${flowName}" not found`;
6385
+ if (flow.startAction.length === 0)
6386
+ throw `Flow "${flowName}" has no start action`;
6387
+ await this.executeAction(flow.startAction, exprAddr, undefined);
5441
6388
  }
5442
6389
  /** Returns all expressions in the given state of given Social DNA flow */
5443
6390
  async expressionsInFlowState(flowName, flowState) {
5444
- let expressions = await this.infer(`register_sdna_flow("${flowName}", F), flow_state(X, ${flowState}, F)`);
5445
- return expressions.map(r => r.X);
6391
+ const flow = await this.getFlow(flowName);
6392
+ if (!flow)
6393
+ return [];
6394
+ // Find the state with the matching value
6395
+ const state = flow.states.find(s => s.value === flowState);
6396
+ if (!state)
6397
+ return [];
6398
+ // Query for expressions matching this state's check pattern
6399
+ const pattern = state.stateCheck;
6400
+ const links = await this.get(new LinkQuery({
6401
+ predicate: pattern.predicate,
6402
+ target: pattern.target
6403
+ }));
6404
+ // Return the sources (expression addresses) - use source if pattern has no explicit source
6405
+ return links.map(l => pattern.source ? l.data.target : l.data.source);
5446
6406
  }
5447
6407
  /** Returns the given expression's flow state with regard to given Social DNA flow */
5448
6408
  async flowState(flowName, exprAddr) {
5449
- let state = await this.infer(`register_sdna_flow("${flowName}", F), flow_state("${exprAddr}", X, F)`);
5450
- return state[0].X;
6409
+ const flow = await this.getFlow(flowName);
6410
+ if (!flow)
6411
+ throw `Flow "${flowName}" not found`;
6412
+ // Check each state to find which one the expression is in
6413
+ for (const state of flow.states) {
6414
+ const pattern = state.stateCheck;
6415
+ const source = pattern.source || exprAddr;
6416
+ const links = await this.get(new LinkQuery({
6417
+ source,
6418
+ predicate: pattern.predicate,
6419
+ target: pattern.target
6420
+ }));
6421
+ if (links.length > 0)
6422
+ return state.value;
6423
+ }
6424
+ throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
5451
6425
  }
5452
6426
  /** Returns available action names, with regard to Social DNA flow and expression's flow state */
5453
6427
  async flowActions(flowName, exprAddr) {
5454
- let actionNames = await this.infer(`register_sdna_flow("${flowName}", Flow), flow_state("${exprAddr}", State, Flow), action(State, Name, _, _)`);
5455
- return actionNames.map(r => r.Name);
6428
+ const flow = await this.getFlow(flowName);
6429
+ if (!flow)
6430
+ return [];
6431
+ // Determine current state
6432
+ let currentStateName = null;
6433
+ for (const state of flow.states) {
6434
+ const pattern = state.stateCheck;
6435
+ const source = pattern.source || exprAddr;
6436
+ const links = await this.get(new LinkQuery({
6437
+ source,
6438
+ predicate: pattern.predicate,
6439
+ target: pattern.target
6440
+ }));
6441
+ if (links.length > 0) {
6442
+ currentStateName = state.name;
6443
+ break;
6444
+ }
6445
+ }
6446
+ if (!currentStateName)
6447
+ return [];
6448
+ // Return transitions available from current state
6449
+ return flow.transitions
6450
+ .filter(t => t.fromState === currentStateName)
6451
+ .map(t => t.actionName);
5456
6452
  }
5457
6453
  /** Runs given Social DNA flow action */
5458
6454
  async runFlowAction(flowName, exprAddr, actionName) {
5459
- let action = await this.infer(`register_sdna_flow("${flowName}", Flow), flow_state("${exprAddr}", State, Flow), action(State, "${actionName}", _, Action)`);
5460
- // should find only one
5461
- action = eval(action[0].Action);
5462
- await this.executeAction(action, exprAddr, undefined);
6455
+ const flow = await this.getFlow(flowName);
6456
+ if (!flow)
6457
+ throw `Flow "${flowName}" not found`;
6458
+ const transition = flow.transitions.find(t => t.actionName === actionName);
6459
+ if (!transition)
6460
+ throw `Action "${actionName}" not found in flow "${flowName}"`;
6461
+ await this.executeAction(transition.actions, exprAddr, undefined);
5463
6462
  }
5464
6463
  /** Returns the perspective's Social DNA code
5465
6464
  * This will return all SDNA code elements in an array.
@@ -5523,16 +6522,253 @@ class PerspectiveProxy {
5523
6522
  const code = Literal.fromUrl(sdnaLinks[0].data.target).get();
5524
6523
  return typeof code === 'string' ? code : null;
5525
6524
  }
5526
- /** Adds the given Social DNA code to the perspective's SDNA code */
5527
- async addSdna(name, sdnaCode, sdnaType) {
5528
- return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType);
6525
+ /**
6526
+ * Adds Social DNA code to the perspective.
6527
+ *
6528
+ * **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.
6529
+ * This method is primarily for the GraphQL layer and legacy Prolog code.
6530
+ *
6531
+ * @param name - Unique name for this SDNA definition
6532
+ * @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)
6533
+ * @param sdnaType - Type of SDNA: "subject_class", "flow", or "custom"
6534
+ * @param shaclJson - SHACL JSON string (use addShacl() for type-safe alternative)
6535
+ *
6536
+ * @example
6537
+ * // Recommended: Use addShacl() with SHACLShape type
6538
+ * const shape = new SHACLShape('recipe://Recipe');
6539
+ * shape.addProperty({ name: 'title', path: 'recipe://title', datatype: 'xsd:string' });
6540
+ * await perspective.addShacl('Recipe', shape);
6541
+ *
6542
+ * // Legacy: Prolog code is auto-converted to SHACL
6543
+ * await perspective.addSdna('Recipe', prologCode, 'subject_class');
6544
+ */
6545
+ async addSdna(name, sdnaCode, sdnaType, shaclJson) {
6546
+ return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
6547
+ }
6548
+ /**
6549
+ * **Recommended way to add SDNA schemas.**
6550
+ *
6551
+ * Store a SHACL shape in this Perspective using the type-safe `SHACLShape` class.
6552
+ * The shape is serialized as RDF triples (links) for native AD4M storage and querying.
6553
+ *
6554
+ * @param name - Unique name for this schema (e.g., 'Recipe', 'Task')
6555
+ * @param shape - SHACLShape instance defining the schema
6556
+ *
6557
+ * @example
6558
+ * import { SHACLShape } from '@coasys/ad4m';
6559
+ *
6560
+ * const shape = new SHACLShape('recipe://Recipe');
6561
+ * shape.addProperty({
6562
+ * name: 'title',
6563
+ * path: 'recipe://title',
6564
+ * datatype: 'xsd:string',
6565
+ * minCount: 1
6566
+ * });
6567
+ * shape.addProperty({
6568
+ * name: 'ingredients',
6569
+ * path: 'recipe://has_ingredient',
6570
+ * // No maxCount = collection
6571
+ * });
6572
+ *
6573
+ * await perspective.addShacl('Recipe', shape);
6574
+ */
6575
+ async addShacl(name, shape) {
6576
+ // Serialize shape to links
6577
+ const shapeLinks = shape.toLinks();
6578
+ // Create name -> shape mapping links
6579
+ const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
6580
+ const allLinks = [
6581
+ ...shapeLinks.map(l => new Link({
6582
+ source: l.source,
6583
+ predicate: l.predicate,
6584
+ target: l.target
6585
+ })),
6586
+ new Link({
6587
+ source: "ad4m://self",
6588
+ predicate: "ad4m://has_shacl",
6589
+ target: nameMapping.toUrl()
6590
+ }),
6591
+ new Link({
6592
+ source: nameMapping.toUrl(),
6593
+ predicate: "ad4m://shacl_shape_uri",
6594
+ target: shape.nodeShapeUri
6595
+ })
6596
+ ];
6597
+ // Batch add all links at once
6598
+ await this.addLinks(allLinks);
6599
+ }
6600
+ /**
6601
+ * Retrieve a SHACL shape by name from this Perspective
6602
+ */
6603
+ async getShacl(name) {
6604
+ // Find the shape URI from the name mapping
6605
+ const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
6606
+ const shapeUriLinks = await this.get(new LinkQuery({
6607
+ source: nameMapping.toUrl(),
6608
+ predicate: "ad4m://shacl_shape_uri"
6609
+ }));
6610
+ if (shapeUriLinks.length === 0) {
6611
+ return null;
6612
+ }
6613
+ const shapeUri = shapeUriLinks[0].data.target;
6614
+ escapeSurrealString(shapeUri);
6615
+ // First get property shape URIs so we can query everything in one go
6616
+ const propertyLinks = await this.get(new LinkQuery({
6617
+ source: shapeUri,
6618
+ predicate: "sh://property"
6619
+ }));
6620
+ // Build a single surreal query that fetches all relevant links
6621
+ const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
6622
+ const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
6623
+ const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
6624
+ const result = await this.querySurrealDB(query);
6625
+ const shapeLinks = (result || []).map((r) => ({
6626
+ source: r.source,
6627
+ predicate: r.predicate,
6628
+ target: r.target
6629
+ }));
6630
+ return SHACLShape.fromLinks(shapeLinks, shapeUri);
6631
+ }
6632
+ /**
6633
+ * Get all SHACL shapes stored in this Perspective
6634
+ */
6635
+ async getAllShacl() {
6636
+ const nameLinks = await this.get(new LinkQuery({
6637
+ source: "ad4m://self",
6638
+ predicate: "ad4m://has_shacl"
6639
+ }));
6640
+ const shapes = [];
6641
+ for (const nameLink of nameLinks) {
6642
+ const nameUrl = nameLink.data.target;
6643
+ const name = Literal.fromUrl(nameUrl).get();
6644
+ const shapeName = name.replace('shacl://', '');
6645
+ const shape = await this.getShacl(shapeName);
6646
+ if (shape) {
6647
+ shapes.push({ name: shapeName, shape });
6648
+ }
6649
+ }
6650
+ return shapes;
6651
+ }
6652
+ /**
6653
+ * **Recommended way to add Flow definitions.**
6654
+ *
6655
+ * Store a SHACL Flow (state machine) in this Perspective using the type-safe `SHACLFlow` class.
6656
+ * The flow is serialized as RDF triples (links) for native AD4M storage and querying.
6657
+ *
6658
+ * @param name - Flow name (e.g., 'TODO', 'Approval')
6659
+ * @param flow - SHACLFlow instance defining the state machine
6660
+ *
6661
+ * @example
6662
+ * ```typescript
6663
+ * import { SHACLFlow } from '@coasys/ad4m';
6664
+ *
6665
+ * const todoFlow = new SHACLFlow('TODO', 'todo://');
6666
+ * todoFlow.flowable = 'any';
6667
+ *
6668
+ * // Define states
6669
+ * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
6670
+ * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
6671
+ *
6672
+ * // Define start action
6673
+ * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
6674
+ *
6675
+ * // Define transitions
6676
+ * todoFlow.addTransition({
6677
+ * actionName: 'Complete',
6678
+ * fromState: 'ready',
6679
+ * toState: 'done',
6680
+ * actions: [
6681
+ * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
6682
+ * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
6683
+ * ]
6684
+ * });
6685
+ *
6686
+ * await perspective.addFlow('TODO', todoFlow);
6687
+ * ```
6688
+ */
6689
+ async addFlow(name, flow) {
6690
+ // Serialize flow to links
6691
+ const flowLinks = flow.toLinks();
6692
+ // Create registration and mapping links
6693
+ const flowNameLiteral = Literal.from(name).toUrl();
6694
+ const allLinks = [
6695
+ ...flowLinks.map(l => new Link({
6696
+ source: l.source,
6697
+ predicate: l.predicate,
6698
+ target: l.target
6699
+ })),
6700
+ new Link({
6701
+ source: "ad4m://self",
6702
+ predicate: "ad4m://has_flow",
6703
+ target: flowNameLiteral
6704
+ }),
6705
+ new Link({
6706
+ source: flowNameLiteral,
6707
+ predicate: "ad4m://flow_uri",
6708
+ target: flow.flowUri
6709
+ })
6710
+ ];
6711
+ // Batch add all links at once
6712
+ await this.addLinks(allLinks);
6713
+ }
6714
+ /**
6715
+ * Retrieve a Flow definition by name from this Perspective
6716
+ *
6717
+ * @param name - Flow name to retrieve
6718
+ * @returns The SHACLFlow or null if not found
6719
+ */
6720
+ async getFlow(name) {
6721
+ const flowNameLiteral = Literal.from(name).toUrl();
6722
+ // Find flow URI from name mapping
6723
+ const flowUriLinks = await this.get(new LinkQuery({
6724
+ source: flowNameLiteral,
6725
+ predicate: "ad4m://flow_uri"
6726
+ }));
6727
+ if (flowUriLinks.length === 0) {
6728
+ return null;
6729
+ }
6730
+ const flowUri = flowUriLinks[0].data.target;
6731
+ const escapedFlowUri = escapeSurrealString(flowUri);
6732
+ // Compute alternate prefix for state/transition URIs
6733
+ const alternatePrefix = flowUri.endsWith('Flow')
6734
+ ? flowUri.slice(0, -4) + '.'
6735
+ : flowUri + '.';
6736
+ const escapedAltPrefix = escapeSurrealString(alternatePrefix);
6737
+ // Single surreal query to get all flow-related links
6738
+ const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri = '${escapedFlowUri}' OR string::starts_with(in.uri, '${escapedAltPrefix}')`;
6739
+ const result = await this.querySurrealDB(query);
6740
+ const flowLinks = (result || []).map((r) => ({
6741
+ source: r.source,
6742
+ predicate: r.predicate,
6743
+ target: r.target
6744
+ }));
6745
+ return SHACLFlow.fromLinks(flowLinks, flowUri);
5529
6746
  }
5530
- /** Returns all the Subject classes defined in this perspectives SDNA */
6747
+ /** Returns all the Subject classes defined in this perspectives SDNA
6748
+ *
6749
+ * Uses SHACL-based lookup (Prolog-free implementation).
6750
+ */
5531
6751
  async subjectClasses() {
5532
6752
  try {
5533
- return (await this.infer("subject_class(X, _)")).map(x => x.X);
6753
+ // Query SHACL class links directly — no need for a separate GraphQL endpoint
6754
+ const classLinks = await this.get(new LinkQuery({
6755
+ predicate: "rdf://type",
6756
+ target: "ad4m://SubjectClass"
6757
+ }));
6758
+ const classNames = classLinks
6759
+ .map(l => {
6760
+ const source = l.data.source;
6761
+ // Extract class name from URI like "recipe://Recipe" or "flux://Channel"
6762
+ const parts = source.split("://");
6763
+ const lastPart = parts[parts.length - 1];
6764
+ return lastPart.split('/').pop() || '';
6765
+ })
6766
+ .filter(name => name.length > 0);
6767
+ // Deduplicate
6768
+ return [...new Set(classNames)];
5534
6769
  }
5535
6770
  catch (e) {
6771
+ console.warn('subjectClasses: SHACL lookup failed:', e);
5536
6772
  return [];
5537
6773
  }
5538
6774
  }
@@ -5572,9 +6808,14 @@ class PerspectiveProxy {
5572
6808
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
5573
6809
  }
5574
6810
  else {
5575
- let query = this.buildQueryFromTemplate(subjectClass);
6811
+ const obj = subjectClass;
6812
+ const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
6813
+ || await this.findClassByProperties(obj);
6814
+ if (!resolvedClassName) {
6815
+ throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
6816
+ }
5576
6817
  await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
5577
- query,
6818
+ className: resolvedClassName,
5578
6819
  initialValues
5579
6820
  }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
5580
6821
  }
@@ -5588,8 +6829,47 @@ class PerspectiveProxy {
5588
6829
  if (typeof subjectClass === "string") {
5589
6830
  return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
5590
6831
  }
5591
- let query = this.buildQueryFromTemplate(subjectClass);
5592
- return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ query }), exprAddr));
6832
+ const obj = subjectClass;
6833
+ const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
6834
+ || await this.findClassByProperties(obj);
6835
+ if (!resolvedClassName) {
6836
+ throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
6837
+ }
6838
+ return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
6839
+ }
6840
+ /**
6841
+ * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
6842
+ * Returns the parsed action array if found, or null if not found.
6843
+ */
6844
+ async getActionsFromSHACL(className, predicate) {
6845
+ // Use regex to match exact class name followed by "Shape" at end of URI
6846
+ // This prevents "RecipeShape" from matching "MyRecipeShape"
6847
+ const escaped = this.escapeRegExp(className);
6848
+ const shapePattern = new RegExp(`[/:#]${escaped}Shape$`);
6849
+ const links = await this.get(new LinkQuery({ predicate }));
6850
+ for (const link of links) {
6851
+ if (shapePattern.test(link.data.source)) {
6852
+ // Parse actions from literal://string:{json}
6853
+ const prefix = "literal://string:";
6854
+ if (link.data.target.startsWith(prefix)) {
6855
+ const jsonStr = link.data.target.slice(prefix.length);
6856
+ // Decode URL-encoded JSON if needed, with fallback for raw % characters
6857
+ let decoded = jsonStr;
6858
+ try {
6859
+ decoded = decodeURIComponent(jsonStr);
6860
+ }
6861
+ catch { }
6862
+ try {
6863
+ return JSON.parse(decoded);
6864
+ }
6865
+ catch (e) {
6866
+ console.warn(`Failed to parse SHACL actions JSON for ${className}:`, e);
6867
+ return null;
6868
+ }
6869
+ }
6870
+ }
6871
+ }
6872
+ return null;
5593
6873
  }
5594
6874
  /** Removes a subject instance by running its (SDNA defined) destructor,
5595
6875
  * which means removing links around the given expression address
@@ -5603,12 +6883,12 @@ class PerspectiveProxy {
5603
6883
  */
5604
6884
  async removeSubject(subjectClass, exprAddr, batchId) {
5605
6885
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
5606
- let result = await this.infer(`subject_class("${className}", C), destructor(C, Actions)`);
5607
- if (!result.length) {
5608
- throw "No destructor found for given subject class: " + className;
6886
+ // Get destructor actions from SHACL links (Prolog-free)
6887
+ let actions = await this.getActionsFromSHACL(className, "ad4m://destructor");
6888
+ if (!actions) {
6889
+ throw `No destructor found for subject class: ${className}. Make sure the class was registered with SHACL.`;
5609
6890
  }
5610
- let actions = result.map(x => eval(x.Actions));
5611
- await this.executeAction(actions[0], exprAddr, undefined, batchId);
6891
+ await this.executeAction(actions, exprAddr, undefined, batchId);
5612
6892
  }
5613
6893
  /** Checks if the given expression is a subject instance of the given subject class
5614
6894
  * @param expression The expression to be checked
@@ -5618,21 +6898,11 @@ class PerspectiveProxy {
5618
6898
  */
5619
6899
  async isSubjectInstance(expression, subjectClass) {
5620
6900
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
5621
- // Get metadata from SDNA using Prolog metaprogramming
6901
+ // Get metadata from SHACL links
5622
6902
  const metadata = await this.getSubjectClassMetadataFromSDNA(className);
5623
6903
  if (!metadata) {
5624
- // Fallback to Prolog check if SDNA metadata isn't available
5625
- // This handles cases where classes exist in Prolog but not in SDNA
5626
- try {
5627
- const escapedClassName = className.replace(/"/g, '\\"');
5628
- const escapedExpression = expression.replace(/"/g, '\\"');
5629
- const result = await this.infer(`subject_class("${escapedClassName}", C), instance(C, "${escapedExpression}")`);
5630
- return result && result.length > 0;
5631
- }
5632
- catch (e) {
5633
- console.warn(`Failed to check instance via Prolog for class ${className}:`, e);
5634
- return false;
5635
- }
6904
+ console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);
6905
+ return false;
5636
6906
  }
5637
6907
  // If no required triples, any expression with links is an instance
5638
6908
  if (metadata.requiredTriples.length === 0) {
@@ -5689,160 +6959,59 @@ class PerspectiveProxy {
5689
6959
  return subject;
5690
6960
  }
5691
6961
  /**
5692
- * Extracts subject class metadata from SDNA by parsing the Prolog text.
5693
- * Parses the instance rule to extract required predicates.
5694
- * Returns required predicates that define what makes something an instance,
5695
- * plus a map of property/collection names to their predicates.
6962
+ * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
6963
+ * Retrieves the SHACL shape and extracts metadata for instance queries.
5696
6964
  */
5697
6965
  async getSubjectClassMetadataFromSDNA(className) {
5698
6966
  try {
5699
- // Get SDNA code from perspective - it's stored as a link
5700
- // Use canonical Literal.from() to construct the source URL
5701
- const sdnaLinks = await this.get(new LinkQuery({
5702
- source: Literal.from(className).toUrl(),
5703
- predicate: "ad4m://sdna"
5704
- }));
5705
- //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
5706
- if (!sdnaLinks || sdnaLinks.length === 0) {
5707
- console.warn(`No SDNA found for class ${className}`);
5708
- return null;
5709
- }
5710
- if (!sdnaLinks[0].data.target) {
5711
- console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
6967
+ // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
6968
+ const shape = await this.getShacl(className);
6969
+ if (!shape) {
6970
+ console.warn(`No SHACL metadata found for ${className}`);
5712
6971
  return null;
5713
6972
  }
5714
- // Extract SDNA code from the literal
5715
- const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
5716
- //console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
5717
- // Store required triples as {predicate, target?}
5718
- // target is only set for flags (exact matches), otherwise undefined
6973
+ const requiredPredicates = [];
5719
6974
  const requiredTriples = [];
5720
- // Parse the instance rule from the SDNA code
5721
- // Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
5722
- // Use a more robust pattern that handles complex rule bodies
5723
- // Match from "instance(" to the closing "." using non-greedy matching
5724
- const instanceRulePattern = /instance\([^)]+\)\s*:-\s*([^.]+)\./g;
5725
- let instanceRuleMatch;
5726
- let foundInstanceRule = false;
5727
- while ((instanceRuleMatch = instanceRulePattern.exec(sdnaCode)) !== null) {
5728
- foundInstanceRule = true;
5729
- const ruleBody = instanceRuleMatch[1];
5730
- // Extract all triple(Base, "predicate", Target) patterns
5731
- // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
5732
- const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
5733
- let match;
5734
- while ((match = tripleRegex.exec(ruleBody)) !== null) {
5735
- const predicate = match[1];
5736
- const target = match[2]; // undefined if matched "_"
5737
- requiredTriples.push({ predicate, target });
5738
- }
5739
- }
5740
- if (!foundInstanceRule) {
5741
- console.warn(`No instance rule found in SDNA for ${className}`);
5742
- }
5743
- // For backward compatibility, also maintain requiredPredicates array
5744
- const requiredPredicates = requiredTriples.map(t => t.predicate);
5745
- // Extract property metadata
5746
6975
  const properties = new Map();
5747
- const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
5748
- //console.log("propertyResults", propertyResults);
5749
- if (propertyResults) {
5750
- for (const result of propertyResults) {
5751
- const propName = result.P;
5752
- let predicate = null;
5753
- // Try to extract predicate from property_setter first
5754
- const setterResults = await this.infer(`subject_class("${className}", C), property_setter(C, "${propName}", Setter)`);
5755
- if (setterResults && setterResults.length > 0) {
5756
- const setterString = setterResults[0].Setter;
5757
- const predicateMatch = setterString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5758
- if (predicateMatch) {
5759
- predicate = predicateMatch[1] || predicateMatch[2];
5760
- }
5761
- }
5762
- // If no setter, try to extract from SDNA property_getter Prolog code
5763
- if (!predicate) {
5764
- // Parse the SDNA code for property_getter definition
5765
- // Escape propName to prevent regex injection and ReDoS attacks
5766
- const escapedPropName = this.escapeRegExp(propName);
5767
- const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedPropName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
5768
- if (getterMatch) {
5769
- predicate = getterMatch[1];
5770
- }
5771
- }
5772
- if (predicate) {
5773
- // Check if property has resolveLanguage
5774
- const resolveResults = await this.infer(`subject_class("${className}", C), property_resolve_language(C, "${propName}", Lang)`);
5775
- const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
5776
- properties.set(propName, { predicate, resolveLanguage });
5777
- }
6976
+ const collections = new Map();
6977
+ // Build property/collection maps and track writable predicates from shape properties
6978
+ const writablePredicates = new Set();
6979
+ for (const prop of shape.properties) {
6980
+ if (!prop.path || !prop.name)
6981
+ continue;
6982
+ if (prop.writable) {
6983
+ writablePredicates.add(prop.path);
6984
+ }
6985
+ const isCollection = prop.adder && prop.adder.length > 0;
6986
+ if (isCollection) {
6987
+ collections.set(prop.name, { predicate: prop.path });
6988
+ }
6989
+ else {
6990
+ properties.set(prop.name, {
6991
+ predicate: prop.path,
6992
+ resolveLanguage: prop.resolveLanguage
6993
+ });
5778
6994
  }
5779
6995
  }
5780
- //console.log("properties", properties);
5781
- // Extract collection metadata
5782
- const collections = new Map();
5783
- const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
5784
- //console.log("collectionResults", collectionResults);
5785
- if (collectionResults) {
5786
- for (const result of collectionResults) {
5787
- const collName = result.Coll;
5788
- let predicate = null;
5789
- let instanceFilter = undefined;
5790
- let condition = undefined;
5791
- // Try to extract predicate from collection_adder first
5792
- const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
5793
- if (adderResults && adderResults.length > 0) {
5794
- const adderString = adderResults[0].Adder;
5795
- const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
5796
- if (predicateMatch) {
5797
- predicate = predicateMatch[1] || predicateMatch[2];
6996
+ // Extract required predicates/triples from constructor actions
6997
+ if (shape.constructor_actions) {
6998
+ for (const action of shape.constructor_actions) {
6999
+ if (action.predicate) {
7000
+ requiredPredicates.push(action.predicate);
7001
+ const isWritableProperty = writablePredicates.has(action.predicate);
7002
+ if (action.target && action.target !== 'value' && !isWritableProperty) {
7003
+ requiredTriples.push({ predicate: action.predicate, target: action.target });
5798
7004
  }
5799
- }
5800
- // Note: condition is not stored in SDNA, it's read from class metadata
5801
- // It will be populated by augmentMetadataWithCollectionOptions() when needed
5802
- // Parse collection_getter from SDNA to extract predicate and instanceFilter
5803
- // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
5804
- // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
5805
- // Use a line-based match to avoid capturing multiple collections
5806
- // Escape collName to prevent regex injection and ReDoS attacks
5807
- const escapedCollName = this.escapeRegExp(collName);
5808
- const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedCollName}"[^)]*\\)\\s*:-[^.]+\\.`);
5809
- const getterLineMatch = sdnaCode.match(getterLinePattern);
5810
- if (getterLineMatch) {
5811
- const getterLine = getterLineMatch[0];
5812
- // Extract the body between setof/findall and the final ).
5813
- // Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
5814
- const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
5815
- const bodyMatch = getterLine.match(bodyPattern);
5816
- if (bodyMatch) {
5817
- let getterBody = bodyMatch[1];
5818
- // Remove outer parentheses if present (setof case)
5819
- if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
5820
- getterBody = getterBody.substring(1, getterBody.length - 1);
5821
- }
5822
- // Extract predicate from triple(Base, "predicate", Target)
5823
- if (!predicate) {
5824
- const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
5825
- if (tripleMatch) {
5826
- predicate = tripleMatch[1];
5827
- }
5828
- }
5829
- // Check for instance filter: subject_class("ClassName", OtherClass)
5830
- const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
5831
- if (instanceMatch) {
5832
- instanceFilter = instanceMatch[1];
5833
- }
7005
+ else {
7006
+ requiredTriples.push({ predicate: action.predicate });
5834
7007
  }
5835
7008
  }
5836
- if (predicate) {
5837
- collections.set(collName, { predicate, instanceFilter, condition });
5838
- }
5839
7009
  }
5840
7010
  }
5841
- //console.log("collections", collections);
5842
7011
  return { requiredPredicates, requiredTriples, properties, collections };
5843
7012
  }
5844
7013
  catch (e) {
5845
- console.error(`Error getting metadata for ${className}:`, e);
7014
+ console.error(`Error getting SHACL metadata for ${className}:`, e);
5846
7015
  return null;
5847
7016
  }
5848
7017
  }
@@ -6041,9 +7210,15 @@ class PerspectiveProxy {
6041
7210
  */
6042
7211
  async getAllSubjectInstances(subjectClass) {
6043
7212
  let classes = [];
7213
+ let isClassConstructor = typeof subjectClass === "function";
6044
7214
  if (typeof subjectClass === "string") {
6045
7215
  classes = [subjectClass];
6046
7216
  }
7217
+ else if (isClassConstructor) {
7218
+ // It's an Ad4mModel class constructor
7219
+ //@ts-ignore
7220
+ classes = [subjectClass.name];
7221
+ }
6047
7222
  else {
6048
7223
  classes = await this.subjectClassesByTemplate(subjectClass);
6049
7224
  }
@@ -6060,9 +7235,20 @@ class PerspectiveProxy {
6060
7235
  for (const result of results || []) {
6061
7236
  //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
6062
7237
  try {
6063
- let subject = new Subject(this, result.base, className);
6064
- await subject.init();
6065
- instances.push(subject);
7238
+ let instance;
7239
+ if (isClassConstructor) {
7240
+ // Create an instance of the actual Ad4mModel class
7241
+ //@ts-ignore
7242
+ instance = new subjectClass(this, result.base);
7243
+ // Load the instance data from links
7244
+ await instance.get();
7245
+ }
7246
+ else {
7247
+ // Legacy: Create a Subject proxy
7248
+ instance = new Subject(this, result.base, className);
7249
+ await instance.init();
7250
+ }
7251
+ instances.push(instance);
6066
7252
  //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
6067
7253
  }
6068
7254
  catch (e) {
@@ -6108,87 +7294,85 @@ class PerspectiveProxy {
6108
7294
  }
6109
7295
  return instances;
6110
7296
  }
6111
- buildQueryFromTemplate(obj) {
6112
- let result;
6113
- // We need to avoid strict mode for the following intropsective code
6114
- (function (obj) {
6115
- // Collect all string properties of the object in a list
6116
- let properties = [];
6117
- // Collect all collections of the object in a list
6118
- let collections = [];
6119
- // Collect all string properties of the object in a list
6120
- if (Object.getPrototypeOf(obj).__properties) {
6121
- Object.keys(Object.getPrototypeOf(obj).__properties).forEach(p => properties.push(p));
6122
- }
6123
- else {
6124
- properties.push(...Object.keys(obj).filter(key => !Array.isArray(obj[key])));
7297
+ /**
7298
+ * Find a subject class by matching an object's properties/collections against SHACL shapes.
7299
+ * Queries SHACL links client-side to find a class whose properties contain all required ones.
7300
+ * @returns The matching class name, or null if no match found.
7301
+ */
7302
+ async findClassByProperties(obj) {
7303
+ // Extract properties and collections from the object
7304
+ let properties = [];
7305
+ let collections = [];
7306
+ const proto = Object.getPrototypeOf(obj);
7307
+ if (proto?.__properties) {
7308
+ properties = Object.keys(proto.__properties);
7309
+ }
7310
+ else {
7311
+ properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));
7312
+ }
7313
+ if (proto?.__collections) {
7314
+ collections = Object.keys(proto.__collections).filter(key => key !== 'isSubjectInstance');
7315
+ }
7316
+ else {
7317
+ collections = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');
7318
+ }
7319
+ if (properties.length === 0 && collections.length === 0) {
7320
+ return null;
7321
+ }
7322
+ // Single SurrealDB query to find all classes and their properties/collections
7323
+ const query = `SELECT
7324
+ in.uri AS shape_source,
7325
+ predicate,
7326
+ out.uri AS target
7327
+ FROM link
7328
+ WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
7329
+ const results = await this.querySurrealDB(query);
7330
+ if (!results || results.length === 0)
7331
+ return null;
7332
+ // Build a map of className -> { properties, collections }
7333
+ const classShapes = new Map();
7334
+ // First pass: find all subject classes
7335
+ for (const r of results) {
7336
+ if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
7337
+ const source = r.shape_source;
7338
+ const sepIdx = source.indexOf('://');
7339
+ if (sepIdx < 0)
7340
+ continue;
7341
+ const className = source.substring(sepIdx + 3).split('/').pop();
7342
+ if (!className)
7343
+ continue;
7344
+ classShapes.set(className, { shapeUri: source, properties: [], collections: [] });
6125
7345
  }
6126
- // Collect all collections of the object in a list
6127
- if (Object.getPrototypeOf(obj).__collections) {
6128
- Object.keys(Object.getPrototypeOf(obj).__collections).filter(key => key !== 'isSubjectInstance').forEach(c => {
6129
- if (!collections.includes(c)) {
6130
- collections.push(c);
7346
+ }
7347
+ // Second pass: collect properties and collections for each class
7348
+ for (const r of results) {
7349
+ if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
7350
+ // Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
7351
+ for (const [className, shape] of classShapes) {
7352
+ if (r.shape_source.endsWith(`${className}Shape`)) {
7353
+ const dotIdx = r.target.lastIndexOf('.');
7354
+ if (dotIdx < 0)
7355
+ continue;
7356
+ const name = r.target.substring(dotIdx + 1);
7357
+ if (r.predicate === 'sh://property') {
7358
+ shape.properties.push(name);
7359
+ }
7360
+ else {
7361
+ shape.collections.push(name);
7362
+ }
6131
7363
  }
6132
- });
6133
- }
6134
- else {
6135
- collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'));
6136
- }
6137
- // Collect all set functions of the object in a list
6138
- let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"));
6139
- // Add all set functions of the object's prototype to that list
6140
- setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
6141
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
6142
- return descriptor && typeof descriptor.value === "function" && key.startsWith("set") && !key.startsWith("setCollection");
6143
- }));
6144
- // Collect all add functions of the object in a list
6145
- let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("add"));
6146
- // Add all add functions of the object's prototype to that list
6147
- addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
6148
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
6149
- return descriptor && typeof descriptor.value === "function" && key.startsWith("add");
6150
- }));
6151
- // Collect all remove functions of the object in a list
6152
- let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("remove"));
6153
- // Add all remove functions of the object's prototype to that list
6154
- removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
6155
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
6156
- return descriptor && typeof descriptor.value === "function" && key.startsWith("remove");
6157
- }));
6158
- // Collect all add functions of the object in a list
6159
- let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("setCollection"));
6160
- // Add all add functions of the object's prototype to that list
6161
- setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
6162
- const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
6163
- return descriptor && typeof descriptor.value === "function" && key.startsWith("setCollection");
6164
- }));
6165
- // Construct query to find all subject classes that have the given properties and collections
6166
- let query = `subject_class(Class, C)`;
6167
- for (let property of properties) {
6168
- query += `, property(C, "${property}")`;
6169
- }
6170
- for (let collection of collections) {
6171
- query += `, collection(C, "${collection}")`;
6172
- }
6173
- for (let setFunction of setFunctions) {
6174
- // e.g. "setState" -> "state"
6175
- let property = setFunction.substring(3);
6176
- property = property.charAt(0).toLowerCase() + property.slice(1);
6177
- query += `, property_setter(C, "${property}", _)`;
6178
- }
6179
- for (let addFunction of addFunctions) {
6180
- query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`;
6181
- }
6182
- for (let removeFunction of removeFunctions) {
6183
- query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`;
7364
+ }
6184
7365
  }
6185
- for (let setCollectionFunction of setCollectionFunctions) {
6186
- query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`;
7366
+ }
7367
+ // Find a class that has all required properties and collections
7368
+ for (const [className, shape] of classShapes) {
7369
+ const hasAllProps = properties.every(p => shape.properties.includes(p));
7370
+ const hasAllCols = collections.every(c => shape.collections.includes(c));
7371
+ if (hasAllProps && hasAllCols) {
7372
+ return className;
6187
7373
  }
6188
- query += ".";
6189
- result = query;
6190
- }(obj));
6191
- return result;
7374
+ }
7375
+ return null;
6192
7376
  }
6193
7377
  /** Returns all subject classes that match the given template object.
6194
7378
  * This function looks at the properties of the template object and
@@ -6202,14 +7386,31 @@ class PerspectiveProxy {
6202
7386
  * @param obj The template object
6203
7387
  */
6204
7388
  async subjectClassesByTemplate(obj) {
6205
- const query = this.buildQueryFromTemplate(obj);
6206
- let result = await this.infer(query);
6207
- if (!result) {
6208
- return [];
7389
+ // SHACL-based lookup: try property matching first (more precise), fall back to className
7390
+ try {
7391
+ const match = await this.findClassByProperties(obj);
7392
+ if (match) {
7393
+ return [match];
7394
+ }
6209
7395
  }
6210
- else {
6211
- return result.map(x => x.Class);
7396
+ catch (e) {
7397
+ console.warn('subjectClassesByTemplate: property matching failed:', e);
7398
+ }
7399
+ // Fall back to className lookup
7400
+ try {
7401
+ // @ts-ignore - className is added dynamically by decorators
7402
+ const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
7403
+ if (className) {
7404
+ const existingClasses = await this.subjectClasses();
7405
+ if (existingClasses.includes(className)) {
7406
+ return [className];
7407
+ }
7408
+ }
7409
+ }
7410
+ catch (e) {
7411
+ console.warn('subjectClassesByTemplate: className lookup failed:', e);
6212
7412
  }
7413
+ return [];
6213
7414
  }
6214
7415
  /** Takes a JS class (its constructor) and assumes that it was decorated by
6215
7416
  * the @subjectClass etc. decorators. It then tests if there is a subject class
@@ -6218,12 +7419,20 @@ class PerspectiveProxy {
6218
7419
  * static generateSDNA() function and adds it to the perspective's SDNA.
6219
7420
  */
6220
7421
  async ensureSDNASubjectClass(jsClass) {
6221
- const subjectClass = await this.subjectClassesByTemplate(new jsClass);
6222
- if (subjectClass.length > 0) {
6223
- return;
6224
- }
6225
- const { name, sdna } = jsClass.generateSDNA();
6226
- await this.addSdna(name, sdna, 'subject_class');
7422
+ // Get the class name from the JS class
7423
+ const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
7424
+ // Note: Duplicate checking is handled on the Rust side in add_sdna
7425
+ // Generate SHACL SDNA (Prolog-free)
7426
+ if (!jsClass.generateSHACL) {
7427
+ throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @ModelOptions decorator.`);
7428
+ }
7429
+ // Get SHACL shape (W3C standard + AD4M action definitions)
7430
+ const { shape } = jsClass.generateSHACL();
7431
+ // Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()
7432
+ const shaclJson = JSON.stringify(shape.toJSON());
7433
+ // Pass SHACL JSON to backend (Prolog-free)
7434
+ // Backend stores SHACL links directly
7435
+ await this.addSdna(className, '', 'subject_class', shaclJson);
6227
7436
  }
6228
7437
  getNeighbourhoodProxy() {
6229
7438
  return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, "f").uuid);
@@ -6713,11 +7922,22 @@ class PerspectiveClient {
6713
7922
  }));
6714
7923
  return perspectiveRemoveLink;
6715
7924
  }
6716
- async addSdna(uuid, name, sdnaCode, sdnaType) {
7925
+ /**
7926
+ * Adds Social DNA code to a perspective.
7927
+ *
7928
+ * Preferred usage: pass shaclJson (from SHACLShape.toJSON()) as the primary schema definition.
7929
+ * The sdnaCode parameter is kept for backward compatibility but SHACL is the source of truth
7930
+ * for all SDNA operations. Prolog engines remain available for complex queries.
7931
+ *
7932
+ * @param sdnaCode - Legacy Prolog code (pass empty string when using shaclJson)
7933
+ * @param shaclJson - SHACL JSON string from SHACLShape.toJSON() (recommended)
7934
+ */
7935
+ async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {
6717
7936
  return unwrapApolloResult(await __classPrivateFieldGet$9(this, _PerspectiveClient_apolloClient, "f").mutate({
6718
- mutation: gql `mutation perspectiveAddSdna($uuid: String!, $name: String!, $sdnaCode: String!, $sdnaType: String!) {
6719
- perspectiveAddSdna(uuid: $uuid, name: $name, sdnaCode: $sdnaCode, sdnaType: $sdnaType)
6720
- }`, variables: { uuid, name, sdnaCode, sdnaType }
7937
+ mutation: gql `mutation perspectiveAddSdna($uuid: String!, $name: String!, $sdnaCode: String, $sdnaType: String!, $shaclJson: String) {
7938
+ perspectiveAddSdna(uuid: $uuid, name: $name, sdnaCode: $sdnaCode, sdnaType: $sdnaType, shaclJson: $shaclJson)
7939
+ }`,
7940
+ variables: { uuid, name, sdnaCode: sdnaCode || "", sdnaType, shaclJson }
6721
7941
  })).perspectiveAddSdna;
6722
7942
  }
6723
7943
  async executeCommands(uuid, commands, expression, parameters, batchId) {
@@ -15845,17 +17065,16 @@ class AIClient {
15845
17065
  const decompressed = JSON.parse(pako.inflate(compressed, { to: 'string' }));
15846
17066
  return decompressed;
15847
17067
  }
15848
- async openTranscriptionStream(modelId, streamCallback, params, language) {
17068
+ async openTranscriptionStream(modelId, streamCallback, params) {
15849
17069
  const { aiOpenTranscriptionStream } = unwrapApolloResult(await __classPrivateFieldGet$3(this, _AIClient_apolloClient, "f").mutate({
15850
17070
  mutation: gql `
15851
- mutation AiOpenTranscriptionStream($modelId: String!, $params: VoiceActivityParamsInput, $language: String) {
15852
- aiOpenTranscriptionStream(modelId: $modelId, params: $params, language: $language)
17071
+ mutation AiOpenTranscriptionStream($modelId: String!, $params: VoiceActivityParamsInput) {
17072
+ aiOpenTranscriptionStream(modelId: $modelId, params: $params)
15853
17073
  }
15854
17074
  `,
15855
17075
  variables: {
15856
17076
  modelId,
15857
- params,
15858
- language
17077
+ params
15859
17078
  }
15860
17079
  }));
15861
17080
  const subscription = __classPrivateFieldGet$3(this, _AIClient_apolloClient, "f").subscribe({
@@ -16535,8 +17754,8 @@ function InstanceQuery(options) {
16535
17754
  // Prolog failed, fall through to SurrealDB
16536
17755
  }
16537
17756
  // Fallback to SurrealDB (SdnaOnly mode)
16538
- // Get all instances first
16539
- let allInstances = await perspective.getAllSubjectInstances(subjectClassName);
17757
+ // Get all instances first - pass the class constructor, not just the name
17758
+ let allInstances = await perspective.getAllSubjectInstances(target);
16540
17759
  // Filter by where clause if provided
16541
17760
  if (options && options.where) {
16542
17761
  let filtered = [];
@@ -17017,9 +18236,9 @@ function ModelOptions(opts) {
17017
18236
  target: "value",
17018
18237
  ...(local && { local: true })
17019
18238
  }];
17020
- collectionCode += `collection_adder(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`;
17021
- collectionCode += `collection_remover(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`;
17022
- collectionCode += `collection_setter(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`;
18239
+ collectionCode += `collection_adder(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`;
18240
+ collectionCode += `collection_remover(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`;
18241
+ collectionCode += `collection_setter(${uuid}, "${collection}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`;
17023
18242
  }
17024
18243
  collectionsCode.push(collectionCode);
17025
18244
  }
@@ -17040,6 +18259,195 @@ function ModelOptions(opts) {
17040
18259
  name: subjectName
17041
18260
  };
17042
18261
  };
18262
+ // Generate SHACL shape (W3C standard + AD4M action definitions)
18263
+ target.generateSHACL = function () {
18264
+ const subjectName = opts.name;
18265
+ const obj = target.prototype;
18266
+ // Determine namespace from first property or collection, or use default
18267
+ let namespace = "ad4m://";
18268
+ const properties = obj.__properties || {};
18269
+ const collections = obj.__collections || {};
18270
+ // Try properties first
18271
+ if (Object.keys(properties).length > 0) {
18272
+ const firstProp = properties[Object.keys(properties)[0]];
18273
+ if (firstProp.through) {
18274
+ // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
18275
+ const match = firstProp.through.match(/^([^:]+:\/\/)/);
18276
+ if (match) {
18277
+ namespace = match[1];
18278
+ }
18279
+ }
18280
+ }
18281
+ // Fall back to collections if no properties
18282
+ else if (Object.keys(collections).length > 0) {
18283
+ const firstColl = collections[Object.keys(collections)[0]];
18284
+ if (firstColl.through) {
18285
+ const match = firstColl.through.match(/^([^:]+:\/\/)/);
18286
+ if (match) {
18287
+ namespace = match[1];
18288
+ }
18289
+ }
18290
+ }
18291
+ // Create SHACL shape
18292
+ const shapeUri = `${namespace}${subjectName}Shape`;
18293
+ const targetClass = `${namespace}${subjectName}`;
18294
+ const shape = new SHACLShape(shapeUri, targetClass);
18295
+ // === Extract Constructor Actions (same logic as generateSDNA) ===
18296
+ let constructorActions = [];
18297
+ if (obj.subjectConstructor && obj.subjectConstructor.length) {
18298
+ constructorActions = constructorActions.concat(obj.subjectConstructor);
18299
+ }
18300
+ // === Extract Destructor Actions ===
18301
+ let destructorActions = [];
18302
+ // Convert properties to SHACL property shapes
18303
+ for (const propName in properties) {
18304
+ const propMeta = properties[propName];
18305
+ if (!propMeta.through)
18306
+ continue; // Skip properties without predicates
18307
+ const propShape = {
18308
+ name: propName,
18309
+ path: propMeta.through,
18310
+ };
18311
+ // Determine datatype from initial value or resolveLanguage
18312
+ if (propMeta.resolveLanguage === "literal") {
18313
+ // If it resolves via literal language, it's likely a string
18314
+ propShape.datatype = "xsd://string";
18315
+ }
18316
+ else if (propMeta.initial) {
18317
+ // Try to infer from initial value type
18318
+ const initialType = typeof obj[propName];
18319
+ if (initialType === "number") {
18320
+ propShape.datatype = "xsd://integer";
18321
+ }
18322
+ else if (initialType === "boolean") {
18323
+ propShape.datatype = "xsd://boolean";
18324
+ }
18325
+ else if (initialType === "string") {
18326
+ propShape.datatype = "xsd://string";
18327
+ }
18328
+ }
18329
+ // Cardinality constraints
18330
+ if (propMeta.required) {
18331
+ propShape.minCount = 1;
18332
+ }
18333
+ // Single-valued properties get maxCount 1
18334
+ // (collections are handled separately below)
18335
+ if (!propMeta.collection) {
18336
+ propShape.maxCount = 1;
18337
+ }
18338
+ // Flag properties have fixed value
18339
+ if (propMeta.flag && propMeta.initial) {
18340
+ propShape.hasValue = propMeta.initial;
18341
+ }
18342
+ // AD4M-specific metadata
18343
+ if (propMeta.local !== undefined) {
18344
+ propShape.local = propMeta.local;
18345
+ }
18346
+ if (propMeta.writable !== undefined) {
18347
+ propShape.writable = propMeta.writable;
18348
+ }
18349
+ if (propMeta.resolveLanguage) {
18350
+ propShape.resolveLanguage = propMeta.resolveLanguage;
18351
+ }
18352
+ // === Extract Setter Actions (same logic as generateSDNA) ===
18353
+ if (propMeta.setter) {
18354
+ // Custom setter defined - not yet supported in SHACL
18355
+ console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
18356
+ `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
18357
+ // TODO: Parse custom Prolog setter to extract actions
18358
+ }
18359
+ else if (propMeta.writable && propMeta.through) {
18360
+ let setter = obj[propertyNameToSetterName(propName)];
18361
+ if (typeof setter === "function") {
18362
+ propShape.setter = [{
18363
+ action: "setSingleTarget",
18364
+ source: "this",
18365
+ predicate: propMeta.through,
18366
+ target: "value",
18367
+ ...(propMeta.local && { local: true })
18368
+ }];
18369
+ }
18370
+ }
18371
+ // Add to constructor actions if property has initial value
18372
+ if (propMeta.initial) {
18373
+ constructorActions.push({
18374
+ action: "addLink",
18375
+ source: "this",
18376
+ predicate: propMeta.through,
18377
+ target: propMeta.initial,
18378
+ });
18379
+ // Add to destructor actions
18380
+ destructorActions.push({
18381
+ action: "removeLink",
18382
+ source: "this",
18383
+ predicate: propMeta.through,
18384
+ target: "*",
18385
+ });
18386
+ }
18387
+ shape.addProperty(propShape);
18388
+ }
18389
+ // Convert collections to SHACL property shapes
18390
+ // (collections variable already declared above for namespace inference)
18391
+ for (const collName in collections) {
18392
+ const collMeta = collections[collName];
18393
+ if (!collMeta.through)
18394
+ continue;
18395
+ const collShape = {
18396
+ name: collName,
18397
+ path: collMeta.through,
18398
+ // Collections have no maxCount (unlimited)
18399
+ // minCount defaults to 0 (optional)
18400
+ };
18401
+ // Determine if it's a reference (IRI) or literal
18402
+ // Collections typically contain references (IRIs) to other entities
18403
+ // They're literals only if explicitly marked or contain primitive values
18404
+ if (collMeta.where?.isInstance) {
18405
+ // Collection of typed entities - definitely IRIs
18406
+ collShape.nodeKind = 'IRI';
18407
+ }
18408
+ else {
18409
+ // Default to IRI for collections (most common case)
18410
+ // Literal collections are rare and would need explicit marking
18411
+ collShape.nodeKind = 'IRI';
18412
+ }
18413
+ // AD4M-specific metadata
18414
+ if (collMeta.local !== undefined) {
18415
+ collShape.local = collMeta.local;
18416
+ }
18417
+ if (collMeta.writable !== undefined) {
18418
+ collShape.writable = collMeta.writable;
18419
+ }
18420
+ // === Extract Collection Actions (adder/remover) ===
18421
+ // Adder action - adds a link to the collection
18422
+ collShape.adder = [{
18423
+ action: "addLink",
18424
+ source: "this",
18425
+ predicate: collMeta.through,
18426
+ target: "value",
18427
+ ...(collMeta.local && { local: true })
18428
+ }];
18429
+ // Remover action - removes a link from the collection
18430
+ collShape.remover = [{
18431
+ action: "removeLink",
18432
+ source: "this",
18433
+ predicate: collMeta.through,
18434
+ target: "value",
18435
+ ...(collMeta.local && { local: true })
18436
+ }];
18437
+ shape.addProperty(collShape);
18438
+ }
18439
+ // Set constructor and destructor actions on the shape
18440
+ if (constructorActions.length > 0) {
18441
+ shape.setConstructorActions(constructorActions);
18442
+ }
18443
+ if (destructorActions.length > 0) {
18444
+ shape.setDestructorActions(destructorActions);
18445
+ }
18446
+ return {
18447
+ shape,
18448
+ name: subjectName
18449
+ };
18450
+ };
17043
18451
  Object.defineProperty(target, 'type', { configurable: true });
17044
18452
  };
17045
18453
  }
@@ -17479,7 +18887,7 @@ type Mutation {
17479
18887
  aiCloseTranscriptionStream(streamId: String!): String!
17480
18888
  aiEmbed(modelId: String!, text: String!): String!
17481
18889
  aiFeedTranscriptionStream(audio: [Float!]!, streamIds: [String!]!): String!
17482
- aiOpenTranscriptionStream(language: String, modelId: String!, params: VoiceActivityParamsInput): String!
18890
+ aiOpenTranscriptionStream(modelId: String!, params: VoiceActivityParamsInput): String!
17483
18891
  aiPrompt(prompt: String!, taskId: String!): String!
17484
18892
  aiRemoveModel(modelId: String!): Boolean!
17485
18893
  aiRemoveTask(taskId: String!): AITask!
@@ -17505,7 +18913,7 @@ type Mutation {
17505
18913
  perspectiveAddLink(batchId: String, link: LinkInput!, status: String = "shared", uuid: String!): LinkExpression!
17506
18914
  perspectiveAddLinkExpression(batchId: String, link: LinkExpressionInput!, status: String = "shared", uuid: String!): LinkExpression!
17507
18915
  perspectiveAddLinks(batchId: String, links: [LinkInput!]!, status: String = "shared", uuid: String!): [LinkExpression!]!
17508
- perspectiveAddSdna(name: String!, sdnaCode: String!, sdnaType: String!, uuid: String!): Boolean!
18916
+ perspectiveAddSdna(name: String!, sdnaCode: String, sdnaType: String!, shaclJson: String, uuid: String!): Boolean!
17509
18917
  perspectiveCommitBatch(batchId: String!, uuid: String!): LinkExpressionMutations!
17510
18918
  perspectiveCreateBatch(uuid: String!): String!
17511
18919
  perspectiveCreateSubject(batchId: String, expressionAddress: String!, initialValues: String, subjectClass: String!, uuid: String!): Boolean!
@@ -19264,8 +20672,10 @@ class Ad4mModel {
19264
20672
  console.warn(`Failed to resolve expression for ${propName}:`, e);
19265
20673
  }
19266
20674
  }
19267
- else if (typeof value === 'string' && value.startsWith('literal://')) {
19268
- // Parse literal URL
20675
+ else if (propMeta.resolveLanguage === 'literal' && typeof value === 'string' && value.startsWith('literal://')) {
20676
+ // Only parse literal URIs when resolveLanguage is explicitly 'literal'.
20677
+ // Without this guard, properties pointing to baseExpressions of other models
20678
+ // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
19269
20679
  try {
19270
20680
  const parsed = Literal.fromUrl(value).get();
19271
20681
  value = parsed.data !== undefined ? parsed.data : parsed;
@@ -20016,8 +21426,12 @@ WHERE ${whereConditions.join(' AND ')}
20016
21426
  let convertedValue = target;
20017
21427
  // Only process if target has a value
20018
21428
  if (target !== undefined && target !== null && target !== '') {
20019
- // Check if we need to resolve a non-literal language expression
20020
- if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string') {
21429
+ // Check if we need to resolve a non-literal language expression.
21430
+ // resolveLanguage must be defined and not 'literal' to trigger expression resolution.
21431
+ // Also skip if the target itself is a literal:// URI — those are handled by the
21432
+ // literal-parsing branch below (avoids calling getExpression on empty literals like
21433
+ // "literal://string:" which would cause a deserialization error).
21434
+ if (propMeta.resolveLanguage != undefined && propMeta.resolveLanguage !== 'literal' && typeof target === 'string' && !target.startsWith('literal://')) {
20021
21435
  // For non-literal languages, resolve the expression via perspective.getExpression()
20022
21436
  // Note: Literals are already parsed by SurrealDB's fn::parse_literal()
20023
21437
  try {
@@ -20039,8 +21453,10 @@ WHERE ${whereConditions.join(' AND ')}
20039
21453
  convertedValue = target; // Fall back to raw value
20040
21454
  }
20041
21455
  }
20042
- else if (typeof target === 'string' && target.startsWith('literal://')) {
20043
- // Fallback: If we somehow got a literal URL that wasn't parsed by SurrealDB, parse it now
21456
+ else if (propMeta.resolveLanguage === 'literal' && typeof target === 'string' && target.startsWith('literal://')) {
21457
+ // Only parse literal URIs when resolveLanguage is explicitly set to 'literal'.
21458
+ // Without this check, properties pointing to baseExpressions of other models
21459
+ // (which may be literal:// strings) would get unwrapped, breaking link URI validation.
20044
21460
  try {
20045
21461
  const parsed = Literal.fromUrl(target).get();
20046
21462
  if (parsed.data !== undefined) {
@@ -20541,6 +21957,10 @@ WHERE ${whereConditions.join(' AND ')}
20541
21957
  const actions = this.generatePropertySetterAction(key, metadata);
20542
21958
  // Get resolve language from metadata (replaces Prolog query)
20543
21959
  let resolveLanguage = metadata.resolveLanguage;
21960
+ // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal://string:)
21961
+ if (value === undefined || value === null || value === "") {
21962
+ return;
21963
+ }
20544
21964
  if (resolveLanguage) {
20545
21965
  value = await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").createExpression(value, resolveLanguage);
20546
21966
  }
@@ -20635,8 +22055,10 @@ WHERE ${whereConditions.join(' AND ')}
20635
22055
  initialValues[key] = value;
20636
22056
  }
20637
22057
  }
22058
+ // Get the class name instead of passing the instance to avoid Prolog query generation
22059
+ const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);
20638
22060
  // Create the subject with the initial values
20639
- await this.perspective.createSubject(this, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
22061
+ await this.perspective.createSubject(className, __classPrivateFieldGet(this, _Ad4mModel_baseExpression, "f"), initialValues, batchId);
20640
22062
  // Link the subject to the source
20641
22063
  await __classPrivateFieldGet(this, _Ad4mModel_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _Ad4mModel_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }), 'shared', batchId);
20642
22064
  // Set collections
@@ -21554,4 +22976,4 @@ class ModelQueryBuilder {
21554
22976
  }
21555
22977
  }
21556
22978
 
21557
- export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, Capability, CapabilityInput, Collection, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, Icon, ImportResult, ImportStats, InstanceQuery, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, ModelOptions, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, capSentence, escapeSurrealString, exprRef2String, formatList, hasLink, isExpression, isLink, linkEqual, makeRandomPrologAtom, parseExprUrl, typeDefsString };
22979
+ export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, Capability, CapabilityInput, Collection, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, Icon, ImportResult, ImportStats, InstanceQuery, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, ModelOptions, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, capSentence, escapeSurrealString, exprRef2String, formatList, hasLink, isExpression, isLink, linkEqual, makeRandomPrologAtom, parseExprUrl, typeDefsString };