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