@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
|
@@ -10,11 +10,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
12
|
var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks;
|
|
13
|
+
import { Link } from "../links/Links";
|
|
13
14
|
import { LinkQuery } from "./LinkQuery";
|
|
14
15
|
import { Literal } from "../Literal";
|
|
15
16
|
import { Subject } from "../model/Subject";
|
|
16
|
-
import { collectionAdderToName, collectionRemoverToName, collectionSetterToName } from "../model/util";
|
|
17
17
|
import { escapeSurrealString } from "../utils";
|
|
18
|
+
import { SHACLShape } from "../shacl/SHACLShape";
|
|
19
|
+
import { SHACLFlow } from "../shacl/SHACLFlow";
|
|
18
20
|
/** Proxy object for a subscribed Prolog query that provides real-time updates
|
|
19
21
|
*
|
|
20
22
|
* This class handles:
|
|
@@ -777,42 +779,129 @@ export class PerspectiveProxy {
|
|
|
777
779
|
}
|
|
778
780
|
/** Returns all the Social DNA flows defined in this perspective */
|
|
779
781
|
async sdnaFlows() {
|
|
780
|
-
|
|
781
|
-
|
|
782
|
+
// Query for all flow registration links
|
|
783
|
+
const flowLinks = await this.get(new LinkQuery({
|
|
784
|
+
source: "ad4m://self",
|
|
785
|
+
predicate: "ad4m://has_flow"
|
|
786
|
+
}));
|
|
787
|
+
return flowLinks.map(l => {
|
|
788
|
+
try {
|
|
789
|
+
return Literal.fromUrl(l.data.target).get();
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
return l.data.target;
|
|
793
|
+
}
|
|
794
|
+
});
|
|
782
795
|
}
|
|
783
796
|
/** Returns all Social DNA flows that can be started from the given expression */
|
|
784
797
|
async availableFlows(exprAddr) {
|
|
785
|
-
const
|
|
786
|
-
|
|
798
|
+
const allFlowNames = await this.sdnaFlows();
|
|
799
|
+
const available = [];
|
|
800
|
+
for (const name of allFlowNames) {
|
|
801
|
+
const flow = await this.getFlow(name);
|
|
802
|
+
if (!flow)
|
|
803
|
+
continue;
|
|
804
|
+
if (flow.flowable === "any") {
|
|
805
|
+
available.push(name);
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
// Check if the expression matches the flowable link pattern
|
|
809
|
+
const pattern = flow.flowable;
|
|
810
|
+
const source = pattern.source || exprAddr;
|
|
811
|
+
const links = await this.get(new LinkQuery({
|
|
812
|
+
source,
|
|
813
|
+
predicate: pattern.predicate,
|
|
814
|
+
target: pattern.target
|
|
815
|
+
}));
|
|
816
|
+
if (links.length > 0) {
|
|
817
|
+
available.push(name);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return available;
|
|
787
822
|
}
|
|
788
823
|
/** Starts the Social DNA flow @param flowName on the expression @param exprAddr */
|
|
789
824
|
async startFlow(flowName, exprAddr) {
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
825
|
+
const flow = await this.getFlow(flowName);
|
|
826
|
+
if (!flow)
|
|
827
|
+
throw `Flow "${flowName}" not found`;
|
|
828
|
+
if (flow.startAction.length === 0)
|
|
829
|
+
throw `Flow "${flowName}" has no start action`;
|
|
830
|
+
await this.executeAction(flow.startAction, exprAddr, undefined);
|
|
794
831
|
}
|
|
795
832
|
/** Returns all expressions in the given state of given Social DNA flow */
|
|
796
833
|
async expressionsInFlowState(flowName, flowState) {
|
|
797
|
-
|
|
798
|
-
|
|
834
|
+
const flow = await this.getFlow(flowName);
|
|
835
|
+
if (!flow)
|
|
836
|
+
return [];
|
|
837
|
+
// Find the state with the matching value
|
|
838
|
+
const state = flow.states.find(s => s.value === flowState);
|
|
839
|
+
if (!state)
|
|
840
|
+
return [];
|
|
841
|
+
// Query for expressions matching this state's check pattern
|
|
842
|
+
const pattern = state.stateCheck;
|
|
843
|
+
const links = await this.get(new LinkQuery({
|
|
844
|
+
predicate: pattern.predicate,
|
|
845
|
+
target: pattern.target
|
|
846
|
+
}));
|
|
847
|
+
// Return the sources (expression addresses) - use source if pattern has no explicit source
|
|
848
|
+
return links.map(l => pattern.source ? l.data.target : l.data.source);
|
|
799
849
|
}
|
|
800
850
|
/** Returns the given expression's flow state with regard to given Social DNA flow */
|
|
801
851
|
async flowState(flowName, exprAddr) {
|
|
802
|
-
|
|
803
|
-
|
|
852
|
+
const flow = await this.getFlow(flowName);
|
|
853
|
+
if (!flow)
|
|
854
|
+
throw `Flow "${flowName}" not found`;
|
|
855
|
+
// Check each state to find which one the expression is in
|
|
856
|
+
for (const state of flow.states) {
|
|
857
|
+
const pattern = state.stateCheck;
|
|
858
|
+
const source = pattern.source || exprAddr;
|
|
859
|
+
const links = await this.get(new LinkQuery({
|
|
860
|
+
source,
|
|
861
|
+
predicate: pattern.predicate,
|
|
862
|
+
target: pattern.target
|
|
863
|
+
}));
|
|
864
|
+
if (links.length > 0)
|
|
865
|
+
return state.value;
|
|
866
|
+
}
|
|
867
|
+
throw `Expression "${exprAddr}" is not in any state of flow "${flowName}"`;
|
|
804
868
|
}
|
|
805
869
|
/** Returns available action names, with regard to Social DNA flow and expression's flow state */
|
|
806
870
|
async flowActions(flowName, exprAddr) {
|
|
807
|
-
|
|
808
|
-
|
|
871
|
+
const flow = await this.getFlow(flowName);
|
|
872
|
+
if (!flow)
|
|
873
|
+
return [];
|
|
874
|
+
// Determine current state
|
|
875
|
+
let currentStateName = null;
|
|
876
|
+
for (const state of flow.states) {
|
|
877
|
+
const pattern = state.stateCheck;
|
|
878
|
+
const source = pattern.source || exprAddr;
|
|
879
|
+
const links = await this.get(new LinkQuery({
|
|
880
|
+
source,
|
|
881
|
+
predicate: pattern.predicate,
|
|
882
|
+
target: pattern.target
|
|
883
|
+
}));
|
|
884
|
+
if (links.length > 0) {
|
|
885
|
+
currentStateName = state.name;
|
|
886
|
+
break;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (!currentStateName)
|
|
890
|
+
return [];
|
|
891
|
+
// Return transitions available from current state
|
|
892
|
+
return flow.transitions
|
|
893
|
+
.filter(t => t.fromState === currentStateName)
|
|
894
|
+
.map(t => t.actionName);
|
|
809
895
|
}
|
|
810
896
|
/** Runs given Social DNA flow action */
|
|
811
897
|
async runFlowAction(flowName, exprAddr, actionName) {
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
898
|
+
const flow = await this.getFlow(flowName);
|
|
899
|
+
if (!flow)
|
|
900
|
+
throw `Flow "${flowName}" not found`;
|
|
901
|
+
const transition = flow.transitions.find(t => t.actionName === actionName);
|
|
902
|
+
if (!transition)
|
|
903
|
+
throw `Action "${actionName}" not found in flow "${flowName}"`;
|
|
904
|
+
await this.executeAction(transition.actions, exprAddr, undefined);
|
|
816
905
|
}
|
|
817
906
|
/** Returns the perspective's Social DNA code
|
|
818
907
|
* This will return all SDNA code elements in an array.
|
|
@@ -876,16 +965,253 @@ export class PerspectiveProxy {
|
|
|
876
965
|
const code = Literal.fromUrl(sdnaLinks[0].data.target).get();
|
|
877
966
|
return typeof code === 'string' ? code : null;
|
|
878
967
|
}
|
|
879
|
-
/**
|
|
880
|
-
|
|
881
|
-
|
|
968
|
+
/**
|
|
969
|
+
* Adds Social DNA code to the perspective.
|
|
970
|
+
*
|
|
971
|
+
* **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.
|
|
972
|
+
* This method is primarily for the GraphQL layer and legacy Prolog code.
|
|
973
|
+
*
|
|
974
|
+
* @param name - Unique name for this SDNA definition
|
|
975
|
+
* @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)
|
|
976
|
+
* @param sdnaType - Type of SDNA: "subject_class", "flow", or "custom"
|
|
977
|
+
* @param shaclJson - SHACL JSON string (use addShacl() for type-safe alternative)
|
|
978
|
+
*
|
|
979
|
+
* @example
|
|
980
|
+
* // Recommended: Use addShacl() with SHACLShape type
|
|
981
|
+
* const shape = new SHACLShape('recipe://Recipe');
|
|
982
|
+
* shape.addProperty({ name: 'title', path: 'recipe://title', datatype: 'xsd:string' });
|
|
983
|
+
* await perspective.addShacl('Recipe', shape);
|
|
984
|
+
*
|
|
985
|
+
* // Legacy: Prolog code is auto-converted to SHACL
|
|
986
|
+
* await perspective.addSdna('Recipe', prologCode, 'subject_class');
|
|
987
|
+
*/
|
|
988
|
+
async addSdna(name, sdnaCode, sdnaType, shaclJson) {
|
|
989
|
+
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* **Recommended way to add SDNA schemas.**
|
|
993
|
+
*
|
|
994
|
+
* Store a SHACL shape in this Perspective using the type-safe `SHACLShape` class.
|
|
995
|
+
* The shape is serialized as RDF triples (links) for native AD4M storage and querying.
|
|
996
|
+
*
|
|
997
|
+
* @param name - Unique name for this schema (e.g., 'Recipe', 'Task')
|
|
998
|
+
* @param shape - SHACLShape instance defining the schema
|
|
999
|
+
*
|
|
1000
|
+
* @example
|
|
1001
|
+
* import { SHACLShape } from '@coasys/ad4m';
|
|
1002
|
+
*
|
|
1003
|
+
* const shape = new SHACLShape('recipe://Recipe');
|
|
1004
|
+
* shape.addProperty({
|
|
1005
|
+
* name: 'title',
|
|
1006
|
+
* path: 'recipe://title',
|
|
1007
|
+
* datatype: 'xsd:string',
|
|
1008
|
+
* minCount: 1
|
|
1009
|
+
* });
|
|
1010
|
+
* shape.addProperty({
|
|
1011
|
+
* name: 'ingredients',
|
|
1012
|
+
* path: 'recipe://has_ingredient',
|
|
1013
|
+
* // No maxCount = collection
|
|
1014
|
+
* });
|
|
1015
|
+
*
|
|
1016
|
+
* await perspective.addShacl('Recipe', shape);
|
|
1017
|
+
*/
|
|
1018
|
+
async addShacl(name, shape) {
|
|
1019
|
+
// Serialize shape to links
|
|
1020
|
+
const shapeLinks = shape.toLinks();
|
|
1021
|
+
// Create name -> shape mapping links
|
|
1022
|
+
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1023
|
+
const allLinks = [
|
|
1024
|
+
...shapeLinks.map(l => new Link({
|
|
1025
|
+
source: l.source,
|
|
1026
|
+
predicate: l.predicate,
|
|
1027
|
+
target: l.target
|
|
1028
|
+
})),
|
|
1029
|
+
new Link({
|
|
1030
|
+
source: "ad4m://self",
|
|
1031
|
+
predicate: "ad4m://has_shacl",
|
|
1032
|
+
target: nameMapping.toUrl()
|
|
1033
|
+
}),
|
|
1034
|
+
new Link({
|
|
1035
|
+
source: nameMapping.toUrl(),
|
|
1036
|
+
predicate: "ad4m://shacl_shape_uri",
|
|
1037
|
+
target: shape.nodeShapeUri
|
|
1038
|
+
})
|
|
1039
|
+
];
|
|
1040
|
+
// Batch add all links at once
|
|
1041
|
+
await this.addLinks(allLinks);
|
|
882
1042
|
}
|
|
883
|
-
/**
|
|
1043
|
+
/**
|
|
1044
|
+
* Retrieve a SHACL shape by name from this Perspective
|
|
1045
|
+
*/
|
|
1046
|
+
async getShacl(name) {
|
|
1047
|
+
// Find the shape URI from the name mapping
|
|
1048
|
+
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1049
|
+
const shapeUriLinks = await this.get(new LinkQuery({
|
|
1050
|
+
source: nameMapping.toUrl(),
|
|
1051
|
+
predicate: "ad4m://shacl_shape_uri"
|
|
1052
|
+
}));
|
|
1053
|
+
if (shapeUriLinks.length === 0) {
|
|
1054
|
+
return null;
|
|
1055
|
+
}
|
|
1056
|
+
const shapeUri = shapeUriLinks[0].data.target;
|
|
1057
|
+
const escapedShapeUri = escapeSurrealString(shapeUri);
|
|
1058
|
+
// First get property shape URIs so we can query everything in one go
|
|
1059
|
+
const propertyLinks = await this.get(new LinkQuery({
|
|
1060
|
+
source: shapeUri,
|
|
1061
|
+
predicate: "sh://property"
|
|
1062
|
+
}));
|
|
1063
|
+
// Build a single surreal query that fetches all relevant links
|
|
1064
|
+
const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
|
|
1065
|
+
const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
|
|
1066
|
+
const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
|
|
1067
|
+
const result = await this.querySurrealDB(query);
|
|
1068
|
+
const shapeLinks = (result || []).map((r) => ({
|
|
1069
|
+
source: r.source,
|
|
1070
|
+
predicate: r.predicate,
|
|
1071
|
+
target: r.target
|
|
1072
|
+
}));
|
|
1073
|
+
return SHACLShape.fromLinks(shapeLinks, shapeUri);
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Get all SHACL shapes stored in this Perspective
|
|
1077
|
+
*/
|
|
1078
|
+
async getAllShacl() {
|
|
1079
|
+
const nameLinks = await this.get(new LinkQuery({
|
|
1080
|
+
source: "ad4m://self",
|
|
1081
|
+
predicate: "ad4m://has_shacl"
|
|
1082
|
+
}));
|
|
1083
|
+
const shapes = [];
|
|
1084
|
+
for (const nameLink of nameLinks) {
|
|
1085
|
+
const nameUrl = nameLink.data.target;
|
|
1086
|
+
const name = Literal.fromUrl(nameUrl).get();
|
|
1087
|
+
const shapeName = name.replace('shacl://', '');
|
|
1088
|
+
const shape = await this.getShacl(shapeName);
|
|
1089
|
+
if (shape) {
|
|
1090
|
+
shapes.push({ name: shapeName, shape });
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
return shapes;
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* **Recommended way to add Flow definitions.**
|
|
1097
|
+
*
|
|
1098
|
+
* Store a SHACL Flow (state machine) in this Perspective using the type-safe `SHACLFlow` class.
|
|
1099
|
+
* The flow is serialized as RDF triples (links) for native AD4M storage and querying.
|
|
1100
|
+
*
|
|
1101
|
+
* @param name - Flow name (e.g., 'TODO', 'Approval')
|
|
1102
|
+
* @param flow - SHACLFlow instance defining the state machine
|
|
1103
|
+
*
|
|
1104
|
+
* @example
|
|
1105
|
+
* ```typescript
|
|
1106
|
+
* import { SHACLFlow } from '@coasys/ad4m';
|
|
1107
|
+
*
|
|
1108
|
+
* const todoFlow = new SHACLFlow('TODO', 'todo://');
|
|
1109
|
+
* todoFlow.flowable = 'any';
|
|
1110
|
+
*
|
|
1111
|
+
* // Define states
|
|
1112
|
+
* todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});
|
|
1113
|
+
* todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});
|
|
1114
|
+
*
|
|
1115
|
+
* // Define start action
|
|
1116
|
+
* todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];
|
|
1117
|
+
*
|
|
1118
|
+
* // Define transitions
|
|
1119
|
+
* todoFlow.addTransition({
|
|
1120
|
+
* actionName: 'Complete',
|
|
1121
|
+
* fromState: 'ready',
|
|
1122
|
+
* toState: 'done',
|
|
1123
|
+
* actions: [
|
|
1124
|
+
* { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },
|
|
1125
|
+
* { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }
|
|
1126
|
+
* ]
|
|
1127
|
+
* });
|
|
1128
|
+
*
|
|
1129
|
+
* await perspective.addFlow('TODO', todoFlow);
|
|
1130
|
+
* ```
|
|
1131
|
+
*/
|
|
1132
|
+
async addFlow(name, flow) {
|
|
1133
|
+
// Serialize flow to links
|
|
1134
|
+
const flowLinks = flow.toLinks();
|
|
1135
|
+
// Create registration and mapping links
|
|
1136
|
+
const flowNameLiteral = Literal.from(name).toUrl();
|
|
1137
|
+
const allLinks = [
|
|
1138
|
+
...flowLinks.map(l => new Link({
|
|
1139
|
+
source: l.source,
|
|
1140
|
+
predicate: l.predicate,
|
|
1141
|
+
target: l.target
|
|
1142
|
+
})),
|
|
1143
|
+
new Link({
|
|
1144
|
+
source: "ad4m://self",
|
|
1145
|
+
predicate: "ad4m://has_flow",
|
|
1146
|
+
target: flowNameLiteral
|
|
1147
|
+
}),
|
|
1148
|
+
new Link({
|
|
1149
|
+
source: flowNameLiteral,
|
|
1150
|
+
predicate: "ad4m://flow_uri",
|
|
1151
|
+
target: flow.flowUri
|
|
1152
|
+
})
|
|
1153
|
+
];
|
|
1154
|
+
// Batch add all links at once
|
|
1155
|
+
await this.addLinks(allLinks);
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Retrieve a Flow definition by name from this Perspective
|
|
1159
|
+
*
|
|
1160
|
+
* @param name - Flow name to retrieve
|
|
1161
|
+
* @returns The SHACLFlow or null if not found
|
|
1162
|
+
*/
|
|
1163
|
+
async getFlow(name) {
|
|
1164
|
+
const flowNameLiteral = Literal.from(name).toUrl();
|
|
1165
|
+
// Find flow URI from name mapping
|
|
1166
|
+
const flowUriLinks = await this.get(new LinkQuery({
|
|
1167
|
+
source: flowNameLiteral,
|
|
1168
|
+
predicate: "ad4m://flow_uri"
|
|
1169
|
+
}));
|
|
1170
|
+
if (flowUriLinks.length === 0) {
|
|
1171
|
+
return null;
|
|
1172
|
+
}
|
|
1173
|
+
const flowUri = flowUriLinks[0].data.target;
|
|
1174
|
+
const escapedFlowUri = escapeSurrealString(flowUri);
|
|
1175
|
+
// Compute alternate prefix for state/transition URIs
|
|
1176
|
+
const alternatePrefix = flowUri.endsWith('Flow')
|
|
1177
|
+
? flowUri.slice(0, -4) + '.'
|
|
1178
|
+
: flowUri + '.';
|
|
1179
|
+
const escapedAltPrefix = escapeSurrealString(alternatePrefix);
|
|
1180
|
+
// Single surreal query to get all flow-related links
|
|
1181
|
+
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}')`;
|
|
1182
|
+
const result = await this.querySurrealDB(query);
|
|
1183
|
+
const flowLinks = (result || []).map((r) => ({
|
|
1184
|
+
source: r.source,
|
|
1185
|
+
predicate: r.predicate,
|
|
1186
|
+
target: r.target
|
|
1187
|
+
}));
|
|
1188
|
+
return SHACLFlow.fromLinks(flowLinks, flowUri);
|
|
1189
|
+
}
|
|
1190
|
+
/** Returns all the Subject classes defined in this perspectives SDNA
|
|
1191
|
+
*
|
|
1192
|
+
* Uses SHACL-based lookup (Prolog-free implementation).
|
|
1193
|
+
*/
|
|
884
1194
|
async subjectClasses() {
|
|
885
1195
|
try {
|
|
886
|
-
|
|
1196
|
+
// Query SHACL class links directly — no need for a separate GraphQL endpoint
|
|
1197
|
+
const classLinks = await this.get(new LinkQuery({
|
|
1198
|
+
predicate: "rdf://type",
|
|
1199
|
+
target: "ad4m://SubjectClass"
|
|
1200
|
+
}));
|
|
1201
|
+
const classNames = classLinks
|
|
1202
|
+
.map(l => {
|
|
1203
|
+
const source = l.data.source;
|
|
1204
|
+
// Extract class name from URI like "recipe://Recipe" or "flux://Channel"
|
|
1205
|
+
const parts = source.split("://");
|
|
1206
|
+
const lastPart = parts[parts.length - 1];
|
|
1207
|
+
return lastPart.split('/').pop() || '';
|
|
1208
|
+
})
|
|
1209
|
+
.filter(name => name.length > 0);
|
|
1210
|
+
// Deduplicate
|
|
1211
|
+
return [...new Set(classNames)];
|
|
887
1212
|
}
|
|
888
1213
|
catch (e) {
|
|
1214
|
+
console.warn('subjectClasses: SHACL lookup failed:', e);
|
|
889
1215
|
return [];
|
|
890
1216
|
}
|
|
891
1217
|
}
|
|
@@ -925,9 +1251,14 @@ export class PerspectiveProxy {
|
|
|
925
1251
|
}), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
|
|
926
1252
|
}
|
|
927
1253
|
else {
|
|
928
|
-
|
|
1254
|
+
const obj = subjectClass;
|
|
1255
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1256
|
+
|| await this.findClassByProperties(obj);
|
|
1257
|
+
if (!resolvedClassName) {
|
|
1258
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1259
|
+
}
|
|
929
1260
|
await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
|
|
930
|
-
|
|
1261
|
+
className: resolvedClassName,
|
|
931
1262
|
initialValues
|
|
932
1263
|
}), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
|
|
933
1264
|
}
|
|
@@ -941,8 +1272,47 @@ export class PerspectiveProxy {
|
|
|
941
1272
|
if (typeof subjectClass === "string") {
|
|
942
1273
|
return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
|
|
943
1274
|
}
|
|
944
|
-
|
|
945
|
-
|
|
1275
|
+
const obj = subjectClass;
|
|
1276
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1277
|
+
|| await this.findClassByProperties(obj);
|
|
1278
|
+
if (!resolvedClassName) {
|
|
1279
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1280
|
+
}
|
|
1281
|
+
return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
|
|
1285
|
+
* Returns the parsed action array if found, or null if not found.
|
|
1286
|
+
*/
|
|
1287
|
+
async getActionsFromSHACL(className, predicate) {
|
|
1288
|
+
// Use regex to match exact class name followed by "Shape" at end of URI
|
|
1289
|
+
// This prevents "RecipeShape" from matching "MyRecipeShape"
|
|
1290
|
+
const escaped = this.escapeRegExp(className);
|
|
1291
|
+
const shapePattern = new RegExp(`[/:#]${escaped}Shape$`);
|
|
1292
|
+
const links = await this.get(new LinkQuery({ predicate }));
|
|
1293
|
+
for (const link of links) {
|
|
1294
|
+
if (shapePattern.test(link.data.source)) {
|
|
1295
|
+
// Parse actions from literal://string:{json}
|
|
1296
|
+
const prefix = "literal://string:";
|
|
1297
|
+
if (link.data.target.startsWith(prefix)) {
|
|
1298
|
+
const jsonStr = link.data.target.slice(prefix.length);
|
|
1299
|
+
// Decode URL-encoded JSON if needed, with fallback for raw % characters
|
|
1300
|
+
let decoded = jsonStr;
|
|
1301
|
+
try {
|
|
1302
|
+
decoded = decodeURIComponent(jsonStr);
|
|
1303
|
+
}
|
|
1304
|
+
catch { }
|
|
1305
|
+
try {
|
|
1306
|
+
return JSON.parse(decoded);
|
|
1307
|
+
}
|
|
1308
|
+
catch (e) {
|
|
1309
|
+
console.warn(`Failed to parse SHACL actions JSON for ${className}:`, e);
|
|
1310
|
+
return null;
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
return null;
|
|
946
1316
|
}
|
|
947
1317
|
/** Removes a subject instance by running its (SDNA defined) destructor,
|
|
948
1318
|
* which means removing links around the given expression address
|
|
@@ -956,12 +1326,12 @@ export class PerspectiveProxy {
|
|
|
956
1326
|
*/
|
|
957
1327
|
async removeSubject(subjectClass, exprAddr, batchId) {
|
|
958
1328
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
1329
|
+
// Get destructor actions from SHACL links (Prolog-free)
|
|
1330
|
+
let actions = await this.getActionsFromSHACL(className, "ad4m://destructor");
|
|
1331
|
+
if (!actions) {
|
|
1332
|
+
throw `No destructor found for subject class: ${className}. Make sure the class was registered with SHACL.`;
|
|
962
1333
|
}
|
|
963
|
-
|
|
964
|
-
await this.executeAction(actions[0], exprAddr, undefined, batchId);
|
|
1334
|
+
await this.executeAction(actions, exprAddr, undefined, batchId);
|
|
965
1335
|
}
|
|
966
1336
|
/** Checks if the given expression is a subject instance of the given subject class
|
|
967
1337
|
* @param expression The expression to be checked
|
|
@@ -971,21 +1341,11 @@ export class PerspectiveProxy {
|
|
|
971
1341
|
*/
|
|
972
1342
|
async isSubjectInstance(expression, subjectClass) {
|
|
973
1343
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
|
|
974
|
-
// Get metadata from
|
|
1344
|
+
// Get metadata from SHACL links
|
|
975
1345
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
976
1346
|
if (!metadata) {
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
try {
|
|
980
|
-
const escapedClassName = className.replace(/"/g, '\\"');
|
|
981
|
-
const escapedExpression = expression.replace(/"/g, '\\"');
|
|
982
|
-
const result = await this.infer(`subject_class("${escapedClassName}", C), instance(C, "${escapedExpression}")`);
|
|
983
|
-
return result && result.length > 0;
|
|
984
|
-
}
|
|
985
|
-
catch (e) {
|
|
986
|
-
console.warn(`Failed to check instance via Prolog for class ${className}:`, e);
|
|
987
|
-
return false;
|
|
988
|
-
}
|
|
1347
|
+
console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);
|
|
1348
|
+
return false;
|
|
989
1349
|
}
|
|
990
1350
|
// If no required triples, any expression with links is an instance
|
|
991
1351
|
if (metadata.requiredTriples.length === 0) {
|
|
@@ -1042,160 +1402,59 @@ export class PerspectiveProxy {
|
|
|
1042
1402
|
return subject;
|
|
1043
1403
|
}
|
|
1044
1404
|
/**
|
|
1045
|
-
*
|
|
1046
|
-
*
|
|
1047
|
-
* Returns required predicates that define what makes something an instance,
|
|
1048
|
-
* plus a map of property/collection names to their predicates.
|
|
1405
|
+
* Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
|
|
1406
|
+
* Retrieves the SHACL shape and extracts metadata for instance queries.
|
|
1049
1407
|
*/
|
|
1050
1408
|
async getSubjectClassMetadataFromSDNA(className) {
|
|
1051
1409
|
try {
|
|
1052
|
-
//
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
predicate: "ad4m://sdna"
|
|
1057
|
-
}));
|
|
1058
|
-
//console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
|
|
1059
|
-
if (!sdnaLinks || sdnaLinks.length === 0) {
|
|
1060
|
-
console.warn(`No SDNA found for class ${className}`);
|
|
1061
|
-
return null;
|
|
1062
|
-
}
|
|
1063
|
-
if (!sdnaLinks[0].data.target) {
|
|
1064
|
-
console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
|
|
1410
|
+
// Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
|
|
1411
|
+
const shape = await this.getShacl(className);
|
|
1412
|
+
if (!shape) {
|
|
1413
|
+
console.warn(`No SHACL metadata found for ${className}`);
|
|
1065
1414
|
return null;
|
|
1066
1415
|
}
|
|
1067
|
-
|
|
1068
|
-
const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
|
|
1069
|
-
//console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
|
|
1070
|
-
// Store required triples as {predicate, target?}
|
|
1071
|
-
// target is only set for flags (exact matches), otherwise undefined
|
|
1416
|
+
const requiredPredicates = [];
|
|
1072
1417
|
const requiredTriples = [];
|
|
1073
|
-
// Parse the instance rule from the SDNA code
|
|
1074
|
-
// Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
|
|
1075
|
-
// Use a more robust pattern that handles complex rule bodies
|
|
1076
|
-
// Match from "instance(" to the closing "." using non-greedy matching
|
|
1077
|
-
const instanceRulePattern = /instance\([^)]+\)\s*:-\s*([^.]+)\./g;
|
|
1078
|
-
let instanceRuleMatch;
|
|
1079
|
-
let foundInstanceRule = false;
|
|
1080
|
-
while ((instanceRuleMatch = instanceRulePattern.exec(sdnaCode)) !== null) {
|
|
1081
|
-
foundInstanceRule = true;
|
|
1082
|
-
const ruleBody = instanceRuleMatch[1];
|
|
1083
|
-
// Extract all triple(Base, "predicate", Target) patterns
|
|
1084
|
-
// Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
|
|
1085
|
-
const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
|
|
1086
|
-
let match;
|
|
1087
|
-
while ((match = tripleRegex.exec(ruleBody)) !== null) {
|
|
1088
|
-
const predicate = match[1];
|
|
1089
|
-
const target = match[2]; // undefined if matched "_"
|
|
1090
|
-
requiredTriples.push({ predicate, target });
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
if (!foundInstanceRule) {
|
|
1094
|
-
console.warn(`No instance rule found in SDNA for ${className}`);
|
|
1095
|
-
}
|
|
1096
|
-
// For backward compatibility, also maintain requiredPredicates array
|
|
1097
|
-
const requiredPredicates = requiredTriples.map(t => t.predicate);
|
|
1098
|
-
// Extract property metadata
|
|
1099
1418
|
const properties = new Map();
|
|
1100
|
-
const
|
|
1101
|
-
//
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
// Escape propName to prevent regex injection and ReDoS attacks
|
|
1119
|
-
const escapedPropName = this.escapeRegExp(propName);
|
|
1120
|
-
const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedPropName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
|
|
1121
|
-
if (getterMatch) {
|
|
1122
|
-
predicate = getterMatch[1];
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
if (predicate) {
|
|
1126
|
-
// Check if property has resolveLanguage
|
|
1127
|
-
const resolveResults = await this.infer(`subject_class("${className}", C), property_resolve_language(C, "${propName}", Lang)`);
|
|
1128
|
-
const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
|
|
1129
|
-
properties.set(propName, { predicate, resolveLanguage });
|
|
1130
|
-
}
|
|
1419
|
+
const collections = new Map();
|
|
1420
|
+
// Build property/collection maps and track writable predicates from shape properties
|
|
1421
|
+
const writablePredicates = new Set();
|
|
1422
|
+
for (const prop of shape.properties) {
|
|
1423
|
+
if (!prop.path || !prop.name)
|
|
1424
|
+
continue;
|
|
1425
|
+
if (prop.writable) {
|
|
1426
|
+
writablePredicates.add(prop.path);
|
|
1427
|
+
}
|
|
1428
|
+
const isCollection = prop.adder && prop.adder.length > 0;
|
|
1429
|
+
if (isCollection) {
|
|
1430
|
+
collections.set(prop.name, { predicate: prop.path });
|
|
1431
|
+
}
|
|
1432
|
+
else {
|
|
1433
|
+
properties.set(prop.name, {
|
|
1434
|
+
predicate: prop.path,
|
|
1435
|
+
resolveLanguage: prop.resolveLanguage
|
|
1436
|
+
});
|
|
1131
1437
|
}
|
|
1132
1438
|
}
|
|
1133
|
-
//
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
let predicate = null;
|
|
1142
|
-
let instanceFilter = undefined;
|
|
1143
|
-
let condition = undefined;
|
|
1144
|
-
// Try to extract predicate from collection_adder first
|
|
1145
|
-
const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
|
|
1146
|
-
if (adderResults && adderResults.length > 0) {
|
|
1147
|
-
const adderString = adderResults[0].Adder;
|
|
1148
|
-
const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
|
|
1149
|
-
if (predicateMatch) {
|
|
1150
|
-
predicate = predicateMatch[1] || predicateMatch[2];
|
|
1439
|
+
// Extract required predicates/triples from constructor actions
|
|
1440
|
+
if (shape.constructor_actions) {
|
|
1441
|
+
for (const action of shape.constructor_actions) {
|
|
1442
|
+
if (action.predicate) {
|
|
1443
|
+
requiredPredicates.push(action.predicate);
|
|
1444
|
+
const isWritableProperty = writablePredicates.has(action.predicate);
|
|
1445
|
+
if (action.target && action.target !== 'value' && !isWritableProperty) {
|
|
1446
|
+
requiredTriples.push({ predicate: action.predicate, target: action.target });
|
|
1151
1447
|
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
// It will be populated by augmentMetadataWithCollectionOptions() when needed
|
|
1155
|
-
// Parse collection_getter from SDNA to extract predicate and instanceFilter
|
|
1156
|
-
// Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
|
|
1157
|
-
// Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
|
|
1158
|
-
// Use a line-based match to avoid capturing multiple collections
|
|
1159
|
-
// Escape collName to prevent regex injection and ReDoS attacks
|
|
1160
|
-
const escapedCollName = this.escapeRegExp(collName);
|
|
1161
|
-
const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${escapedCollName}"[^)]*\\)\\s*:-[^.]+\\.`);
|
|
1162
|
-
const getterLineMatch = sdnaCode.match(getterLinePattern);
|
|
1163
|
-
if (getterLineMatch) {
|
|
1164
|
-
const getterLine = getterLineMatch[0];
|
|
1165
|
-
// Extract the body between setof/findall and the final ).
|
|
1166
|
-
// Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
|
|
1167
|
-
const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
|
|
1168
|
-
const bodyMatch = getterLine.match(bodyPattern);
|
|
1169
|
-
if (bodyMatch) {
|
|
1170
|
-
let getterBody = bodyMatch[1];
|
|
1171
|
-
// Remove outer parentheses if present (setof case)
|
|
1172
|
-
if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
|
|
1173
|
-
getterBody = getterBody.substring(1, getterBody.length - 1);
|
|
1174
|
-
}
|
|
1175
|
-
// Extract predicate from triple(Base, "predicate", Target)
|
|
1176
|
-
if (!predicate) {
|
|
1177
|
-
const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
|
|
1178
|
-
if (tripleMatch) {
|
|
1179
|
-
predicate = tripleMatch[1];
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
// Check for instance filter: subject_class("ClassName", OtherClass)
|
|
1183
|
-
const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
|
|
1184
|
-
if (instanceMatch) {
|
|
1185
|
-
instanceFilter = instanceMatch[1];
|
|
1186
|
-
}
|
|
1448
|
+
else {
|
|
1449
|
+
requiredTriples.push({ predicate: action.predicate });
|
|
1187
1450
|
}
|
|
1188
1451
|
}
|
|
1189
|
-
if (predicate) {
|
|
1190
|
-
collections.set(collName, { predicate, instanceFilter, condition });
|
|
1191
|
-
}
|
|
1192
1452
|
}
|
|
1193
1453
|
}
|
|
1194
|
-
//console.log("collections", collections);
|
|
1195
1454
|
return { requiredPredicates, requiredTriples, properties, collections };
|
|
1196
1455
|
}
|
|
1197
1456
|
catch (e) {
|
|
1198
|
-
console.error(`Error getting metadata for ${className}:`, e);
|
|
1457
|
+
console.error(`Error getting SHACL metadata for ${className}:`, e);
|
|
1199
1458
|
return null;
|
|
1200
1459
|
}
|
|
1201
1460
|
}
|
|
@@ -1395,9 +1654,15 @@ export class PerspectiveProxy {
|
|
|
1395
1654
|
*/
|
|
1396
1655
|
async getAllSubjectInstances(subjectClass) {
|
|
1397
1656
|
let classes = [];
|
|
1657
|
+
let isClassConstructor = typeof subjectClass === "function";
|
|
1398
1658
|
if (typeof subjectClass === "string") {
|
|
1399
1659
|
classes = [subjectClass];
|
|
1400
1660
|
}
|
|
1661
|
+
else if (isClassConstructor) {
|
|
1662
|
+
// It's an Ad4mModel class constructor
|
|
1663
|
+
//@ts-ignore
|
|
1664
|
+
classes = [subjectClass.name];
|
|
1665
|
+
}
|
|
1401
1666
|
else {
|
|
1402
1667
|
classes = await this.subjectClassesByTemplate(subjectClass);
|
|
1403
1668
|
}
|
|
@@ -1414,9 +1679,20 @@ export class PerspectiveProxy {
|
|
|
1414
1679
|
for (const result of results || []) {
|
|
1415
1680
|
//console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
|
|
1416
1681
|
try {
|
|
1417
|
-
let
|
|
1418
|
-
|
|
1419
|
-
|
|
1682
|
+
let instance;
|
|
1683
|
+
if (isClassConstructor) {
|
|
1684
|
+
// Create an instance of the actual Ad4mModel class
|
|
1685
|
+
//@ts-ignore
|
|
1686
|
+
instance = new subjectClass(this, result.base);
|
|
1687
|
+
// Load the instance data from links
|
|
1688
|
+
await instance.get();
|
|
1689
|
+
}
|
|
1690
|
+
else {
|
|
1691
|
+
// Legacy: Create a Subject proxy
|
|
1692
|
+
instance = new Subject(this, result.base, className);
|
|
1693
|
+
await instance.init();
|
|
1694
|
+
}
|
|
1695
|
+
instances.push(instance);
|
|
1420
1696
|
//console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
|
|
1421
1697
|
}
|
|
1422
1698
|
catch (e) {
|
|
@@ -1465,87 +1741,85 @@ export class PerspectiveProxy {
|
|
|
1465
1741
|
}
|
|
1466
1742
|
return instances;
|
|
1467
1743
|
}
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1744
|
+
/**
|
|
1745
|
+
* Find a subject class by matching an object's properties/collections against SHACL shapes.
|
|
1746
|
+
* Queries SHACL links client-side to find a class whose properties contain all required ones.
|
|
1747
|
+
* @returns The matching class name, or null if no match found.
|
|
1748
|
+
*/
|
|
1749
|
+
async findClassByProperties(obj) {
|
|
1750
|
+
// Extract properties and collections from the object
|
|
1751
|
+
let properties = [];
|
|
1752
|
+
let collections = [];
|
|
1753
|
+
const proto = Object.getPrototypeOf(obj);
|
|
1754
|
+
if (proto?.__properties) {
|
|
1755
|
+
properties = Object.keys(proto.__properties);
|
|
1756
|
+
}
|
|
1757
|
+
else {
|
|
1758
|
+
properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));
|
|
1759
|
+
}
|
|
1760
|
+
if (proto?.__collections) {
|
|
1761
|
+
collections = Object.keys(proto.__collections).filter(key => key !== 'isSubjectInstance');
|
|
1762
|
+
}
|
|
1763
|
+
else {
|
|
1764
|
+
collections = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');
|
|
1765
|
+
}
|
|
1766
|
+
if (properties.length === 0 && collections.length === 0) {
|
|
1767
|
+
return null;
|
|
1768
|
+
}
|
|
1769
|
+
// Single SurrealDB query to find all classes and their properties/collections
|
|
1770
|
+
const query = `SELECT
|
|
1771
|
+
in.uri AS shape_source,
|
|
1772
|
+
predicate,
|
|
1773
|
+
out.uri AS target
|
|
1774
|
+
FROM link
|
|
1775
|
+
WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
|
|
1776
|
+
const results = await this.querySurrealDB(query);
|
|
1777
|
+
if (!results || results.length === 0)
|
|
1778
|
+
return null;
|
|
1779
|
+
// Build a map of className -> { properties, collections }
|
|
1780
|
+
const classShapes = new Map();
|
|
1781
|
+
// First pass: find all subject classes
|
|
1782
|
+
for (const r of results) {
|
|
1783
|
+
if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
|
|
1784
|
+
const source = r.shape_source;
|
|
1785
|
+
const sepIdx = source.indexOf('://');
|
|
1786
|
+
if (sepIdx < 0)
|
|
1787
|
+
continue;
|
|
1788
|
+
const className = source.substring(sepIdx + 3).split('/').pop();
|
|
1789
|
+
if (!className)
|
|
1790
|
+
continue;
|
|
1791
|
+
classShapes.set(className, { shapeUri: source, properties: [], collections: [] });
|
|
1482
1792
|
}
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1793
|
+
}
|
|
1794
|
+
// Second pass: collect properties and collections for each class
|
|
1795
|
+
for (const r of results) {
|
|
1796
|
+
if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
|
|
1797
|
+
// Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
|
|
1798
|
+
for (const [className, shape] of classShapes) {
|
|
1799
|
+
if (r.shape_source.endsWith(`${className}Shape`)) {
|
|
1800
|
+
const dotIdx = r.target.lastIndexOf('.');
|
|
1801
|
+
if (dotIdx < 0)
|
|
1802
|
+
continue;
|
|
1803
|
+
const name = r.target.substring(dotIdx + 1);
|
|
1804
|
+
if (r.predicate === 'sh://property') {
|
|
1805
|
+
shape.properties.push(name);
|
|
1806
|
+
}
|
|
1807
|
+
else {
|
|
1808
|
+
shape.collections.push(name);
|
|
1809
|
+
}
|
|
1488
1810
|
}
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
else {
|
|
1492
|
-
collections.push(...Object.keys(obj).filter(key => Array.isArray(obj[key])).filter(key => key !== 'isSubjectInstance'));
|
|
1493
|
-
}
|
|
1494
|
-
// Collect all set functions of the object in a list
|
|
1495
|
-
let setFunctions = Object.getOwnPropertyNames(obj).filter(key => (typeof obj[key] === "function") && key.startsWith("set") && !key.startsWith("setCollection"));
|
|
1496
|
-
// Add all set functions of the object's prototype to that list
|
|
1497
|
-
setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1498
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1499
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("set") && !key.startsWith("setCollection");
|
|
1500
|
-
}));
|
|
1501
|
-
// Collect all add functions of the object in a list
|
|
1502
|
-
let addFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("add"));
|
|
1503
|
-
// Add all add functions of the object's prototype to that list
|
|
1504
|
-
addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1505
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1506
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("add");
|
|
1507
|
-
}));
|
|
1508
|
-
// Collect all remove functions of the object in a list
|
|
1509
|
-
let removeFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("remove"));
|
|
1510
|
-
// Add all remove functions of the object's prototype to that list
|
|
1511
|
-
removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1512
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1513
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("remove");
|
|
1514
|
-
}));
|
|
1515
|
-
// Collect all add functions of the object in a list
|
|
1516
|
-
let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter(key => (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === "function") && key.startsWith("setCollection"));
|
|
1517
|
-
// Add all add functions of the object's prototype to that list
|
|
1518
|
-
setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter(key => {
|
|
1519
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
1520
|
-
return descriptor && typeof descriptor.value === "function" && key.startsWith("setCollection");
|
|
1521
|
-
}));
|
|
1522
|
-
// Construct query to find all subject classes that have the given properties and collections
|
|
1523
|
-
let query = `subject_class(Class, C)`;
|
|
1524
|
-
for (let property of properties) {
|
|
1525
|
-
query += `, property(C, "${property}")`;
|
|
1526
|
-
}
|
|
1527
|
-
for (let collection of collections) {
|
|
1528
|
-
query += `, collection(C, "${collection}")`;
|
|
1529
|
-
}
|
|
1530
|
-
for (let setFunction of setFunctions) {
|
|
1531
|
-
// e.g. "setState" -> "state"
|
|
1532
|
-
let property = setFunction.substring(3);
|
|
1533
|
-
property = property.charAt(0).toLowerCase() + property.slice(1);
|
|
1534
|
-
query += `, property_setter(C, "${property}", _)`;
|
|
1535
|
-
}
|
|
1536
|
-
for (let addFunction of addFunctions) {
|
|
1537
|
-
query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`;
|
|
1538
|
-
}
|
|
1539
|
-
for (let removeFunction of removeFunctions) {
|
|
1540
|
-
query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`;
|
|
1811
|
+
}
|
|
1541
1812
|
}
|
|
1542
|
-
|
|
1543
|
-
|
|
1813
|
+
}
|
|
1814
|
+
// Find a class that has all required properties and collections
|
|
1815
|
+
for (const [className, shape] of classShapes) {
|
|
1816
|
+
const hasAllProps = properties.every(p => shape.properties.includes(p));
|
|
1817
|
+
const hasAllCols = collections.every(c => shape.collections.includes(c));
|
|
1818
|
+
if (hasAllProps && hasAllCols) {
|
|
1819
|
+
return className;
|
|
1544
1820
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
}(obj));
|
|
1548
|
-
return result;
|
|
1821
|
+
}
|
|
1822
|
+
return null;
|
|
1549
1823
|
}
|
|
1550
1824
|
/** Returns all subject classes that match the given template object.
|
|
1551
1825
|
* This function looks at the properties of the template object and
|
|
@@ -1559,14 +1833,31 @@ export class PerspectiveProxy {
|
|
|
1559
1833
|
* @param obj The template object
|
|
1560
1834
|
*/
|
|
1561
1835
|
async subjectClassesByTemplate(obj) {
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1836
|
+
// SHACL-based lookup: try property matching first (more precise), fall back to className
|
|
1837
|
+
try {
|
|
1838
|
+
const match = await this.findClassByProperties(obj);
|
|
1839
|
+
if (match) {
|
|
1840
|
+
return [match];
|
|
1841
|
+
}
|
|
1566
1842
|
}
|
|
1567
|
-
|
|
1568
|
-
|
|
1843
|
+
catch (e) {
|
|
1844
|
+
console.warn('subjectClassesByTemplate: property matching failed:', e);
|
|
1845
|
+
}
|
|
1846
|
+
// Fall back to className lookup
|
|
1847
|
+
try {
|
|
1848
|
+
// @ts-ignore - className is added dynamically by decorators
|
|
1849
|
+
const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
|
|
1850
|
+
if (className) {
|
|
1851
|
+
const existingClasses = await this.subjectClasses();
|
|
1852
|
+
if (existingClasses.includes(className)) {
|
|
1853
|
+
return [className];
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
catch (e) {
|
|
1858
|
+
console.warn('subjectClassesByTemplate: className lookup failed:', e);
|
|
1569
1859
|
}
|
|
1860
|
+
return [];
|
|
1570
1861
|
}
|
|
1571
1862
|
/** Takes a JS class (its constructor) and assumes that it was decorated by
|
|
1572
1863
|
* the @subjectClass etc. decorators. It then tests if there is a subject class
|
|
@@ -1575,12 +1866,20 @@ export class PerspectiveProxy {
|
|
|
1575
1866
|
* static generateSDNA() function and adds it to the perspective's SDNA.
|
|
1576
1867
|
*/
|
|
1577
1868
|
async ensureSDNASubjectClass(jsClass) {
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1869
|
+
// Get the class name from the JS class
|
|
1870
|
+
const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
|
|
1871
|
+
// Note: Duplicate checking is handled on the Rust side in add_sdna
|
|
1872
|
+
// Generate SHACL SDNA (Prolog-free)
|
|
1873
|
+
if (!jsClass.generateSHACL) {
|
|
1874
|
+
throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @ModelOptions decorator.`);
|
|
1581
1875
|
}
|
|
1582
|
-
|
|
1583
|
-
|
|
1876
|
+
// Get SHACL shape (W3C standard + AD4M action definitions)
|
|
1877
|
+
const { shape } = jsClass.generateSHACL();
|
|
1878
|
+
// Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()
|
|
1879
|
+
const shaclJson = JSON.stringify(shape.toJSON());
|
|
1880
|
+
// Pass SHACL JSON to backend (Prolog-free)
|
|
1881
|
+
// Backend stores SHACL links directly
|
|
1882
|
+
await this.addSdna(className, '', 'subject_class', shaclJson);
|
|
1584
1883
|
}
|
|
1585
1884
|
getNeighbourhoodProxy() {
|
|
1586
1885
|
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
|