@coasys/ad4m 0.12.0-rc1-dev.2 → 0.12.0-rc1-dev.4
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/jest.config.js +10 -3
- package/lib/index.cjs +6893 -5884
- package/lib/index.js +6889 -5872
- package/lib/src/Ad4mClient.d.ts +9 -16
- package/lib/src/Ad4mClient.js +46 -25
- package/lib/src/Literal.d.ts +1 -2
- package/lib/src/Literal.js +38 -35
- package/lib/src/SmartLiteral.d.ts +1 -2
- package/lib/src/SmartLiteral.js +30 -15
- package/lib/src/agent/AgentClient.d.ts +1 -4
- package/lib/src/agent/AgentClient.js +79 -99
- package/lib/src/ai/AIClient.d.ts +1 -2
- package/lib/src/ai/AIClient.js +224 -220
- package/lib/src/expression/ExpressionClient.d.ts +1 -1
- package/lib/src/expression/ExpressionClient.js +73 -86
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/language/LanguageClient.d.ts +1 -1
- package/lib/src/language/LanguageClient.js +52 -52
- package/lib/src/model/Ad4mModel.d.ts +1351 -144
- package/lib/src/model/Ad4mModel.js +3760 -228
- package/lib/src/model/Ad4mModel.test.js +522 -979
- package/lib/src/model/Subject.d.ts +3 -3
- package/lib/src/model/Subject.js +25 -25
- package/lib/src/model/decorators.d.ts +444 -100
- package/lib/src/model/decorators.js +686 -321
- package/lib/src/model/util.d.ts +6 -6
- package/lib/src/model/util.js +24 -24
- package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
- package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
- package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
- package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
- package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
- package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
- package/lib/src/perspectives/PerspectiveClient.js +240 -316
- package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
- package/lib/src/perspectives/PerspectiveProxy.js +485 -832
- package/lib/src/runtime/RuntimeClient.d.ts +1 -5
- package/lib/src/runtime/RuntimeClient.js +238 -412
- package/lib/src/shacl/SHACLFlow.test.js +105 -164
- package/lib/src/shacl/SHACLShape.d.ts +12 -17
- package/lib/src/shacl/SHACLShape.js +115 -128
- package/lib/src/shacl/SHACLShape.test.js +176 -244
- package/lib/src/shims/reflect-metadata.d.ts +0 -0
- package/lib/src/shims/type-graphql.d.ts +32 -0
- package/lib/src/src/Ad4mClient.d.ts +28 -0
- package/lib/src/src/Address.d.ts +1 -0
- package/lib/src/src/DID.d.ts +1 -0
- package/lib/src/src/Exception.d.ts +7 -0
- package/lib/src/src/Literal.d.ts +7 -0
- package/lib/src/src/PubSub.d.ts +17 -0
- package/lib/src/src/SmartLiteral.d.ts +12 -0
- package/lib/src/src/agent/Agent.d.ts +110 -0
- package/lib/src/src/agent/AgentClient.d.ts +62 -0
- package/lib/src/src/agent/AgentResolver.d.ts +30 -0
- package/lib/src/src/agent/AgentStatus.d.ts +8 -0
- package/lib/src/src/ai/AIClient.d.ts +32 -0
- package/lib/src/src/ai/AIResolver.d.ts +75 -0
- package/lib/src/src/ai/Tasks.d.ts +37 -0
- package/lib/src/src/buildSchema.d.ts +1 -0
- package/lib/src/src/expression/Expression.d.ts +28 -0
- package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
- package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
- package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
- package/lib/src/src/index.d.ts +35 -0
- package/lib/src/src/jestSetup.d.ts +1 -0
- package/lib/src/src/language/Icon.d.ts +4 -0
- package/lib/src/src/language/Language.d.ts +206 -0
- package/lib/src/src/language/LanguageClient.d.ts +17 -0
- package/lib/src/src/language/LanguageContext.d.ts +37 -0
- package/lib/src/src/language/LanguageHandle.d.ts +9 -0
- package/lib/src/src/language/LanguageMeta.d.ts +35 -0
- package/lib/src/src/language/LanguageRef.d.ts +6 -0
- package/lib/src/src/language/LanguageResolver.d.ts +19 -0
- package/lib/src/src/links/Links.d.ts +39 -0
- package/lib/src/src/links/Links.test.d.ts +1 -0
- package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
- package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
- package/lib/src/src/model/Subject.d.ts +25 -0
- package/lib/src/src/model/decorators.d.ts +545 -0
- package/lib/src/src/model/util.d.ts +12 -0
- package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
- package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
- package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
- package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
- package/lib/src/src/perspectives/Perspective.d.ts +38 -0
- package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
- package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
- package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
- package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
- package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
- package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
- package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
- package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
- package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
- package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
- package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
- package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
- package/lib/src/src/typeDefs.d.ts +1 -0
- package/lib/src/src/unwrapApolloResult.d.ts +2 -0
- package/lib/src/src/utils.d.ts +25 -0
- package/lib/src/utils.d.ts +0 -8
- package/lib/src/utils.js +7 -21
- package/package.json +15 -14
- package/src/Ad4mClient.test.ts +1315 -1564
- package/src/Ad4mClient.ts +54 -55
- package/src/Literal.test.ts +26 -45
- package/src/Literal.ts +66 -82
- package/src/SmartLiteral.ts +58 -74
- package/src/agent/AgentClient.ts +99 -144
- package/src/ai/AIClient.ts +359 -409
- package/src/expression/ExpressionClient.ts +96 -142
- package/src/index.ts +1 -1
- package/src/language/LanguageClient.ts +113 -137
- package/src/model/Ad4mModel.test.ts +616 -1114
- package/src/model/Ad4mModel.ts +4386 -451
- package/src/model/Subject.ts +159 -0
- package/src/model/decorators.ts +1168 -667
- package/src/model/util.ts +54 -53
- package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
- package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
- package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
- package/src/perspectives/PerspectiveClient.ts +540 -779
- package/src/perspectives/PerspectiveProxy.ts +2067 -2860
- package/src/runtime/RuntimeClient.ts +476 -775
- package/src/shacl/SHACLFlow.test.ts +129 -196
- package/src/shacl/SHACLShape.test.ts +190 -284
- package/src/shacl/SHACLShape.ts +200 -224
- package/src/utils.ts +17 -31
- package/tsconfig.json +10 -9
- package/src/model/IMPROVEMENTS.md +0 -482
- package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
- package/src/model/README.md +0 -317
- package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
- package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
- package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
- package/src/model/mutation.ts +0 -461
- package/src/model/parentUtils.ts +0 -91
- package/src/model/prolog/generatePrologFacts.ts +0 -176
- package/src/model/prolog/index.ts +0 -1
- package/src/model/query/ModelQueryBuilder.ts +0 -173
- package/src/model/query/fetchInstance.ts +0 -181
- package/src/model/query/hydration.ts +0 -273
- package/src/model/query/operations.ts +0 -510
- package/src/model/query/snapshot.ts +0 -126
- package/src/model/query/surrealCompiler.ts +0 -376
- package/src/model/schema/fromJSONSchema.ts +0 -411
- package/src/model/schema/metadata.ts +0 -148
- package/src/model/subscription.ts +0 -307
- package/src/model/transaction.ts +0 -60
- package/src/model/types.ts +0 -207
|
@@ -1,8 +1,23 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
9
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
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";
|
|
1
14
|
import { LinkQuery } from "./LinkQuery";
|
|
2
15
|
import { Literal } from "../Literal";
|
|
3
|
-
import {
|
|
4
|
-
import { getPropertiesMetadata, getRelationsMetadata
|
|
16
|
+
import { Subject } from "../model/Subject";
|
|
17
|
+
import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
|
|
5
18
|
import { escapeSurrealString } from "../utils";
|
|
19
|
+
import { SHACLShape } from "../shacl/SHACLShape";
|
|
20
|
+
import { SHACLFlow } from "../shacl/SHACLFlow";
|
|
6
21
|
/** Proxy object for a subscribed Prolog query that provides real-time updates
|
|
7
22
|
*
|
|
8
23
|
* This class handles:
|
|
@@ -43,116 +58,137 @@ export class QuerySubscriptionProxy {
|
|
|
43
58
|
* @param client - The PerspectiveClient instance to use for communication
|
|
44
59
|
*/
|
|
45
60
|
constructor(uuid, query, client) {
|
|
46
|
-
this
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
this
|
|
51
|
-
this
|
|
52
|
-
this
|
|
53
|
-
this
|
|
54
|
-
this
|
|
61
|
+
_QuerySubscriptionProxy_instances.add(this);
|
|
62
|
+
_QuerySubscriptionProxy_uuid.set(this, void 0);
|
|
63
|
+
_QuerySubscriptionProxy_subscriptionId.set(this, void 0);
|
|
64
|
+
_QuerySubscriptionProxy_client.set(this, void 0);
|
|
65
|
+
_QuerySubscriptionProxy_callbacks.set(this, void 0);
|
|
66
|
+
_QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
|
|
67
|
+
_QuerySubscriptionProxy_unsubscribe.set(this, void 0);
|
|
68
|
+
_QuerySubscriptionProxy_latestResult.set(this, void 0);
|
|
69
|
+
_QuerySubscriptionProxy_disposed.set(this, false);
|
|
70
|
+
_QuerySubscriptionProxy_initialized.set(this, void 0);
|
|
71
|
+
_QuerySubscriptionProxy_initResolve.set(this, void 0);
|
|
72
|
+
_QuerySubscriptionProxy_initReject.set(this, void 0);
|
|
73
|
+
_QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
|
|
74
|
+
_QuerySubscriptionProxy_query.set(this, void 0);
|
|
75
|
+
this.isSurrealDB = false;
|
|
76
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_uuid, uuid, "f");
|
|
77
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_query, query, "f");
|
|
78
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_client, client, "f");
|
|
79
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
|
|
80
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, null, "f");
|
|
55
81
|
// Create the promise once and store its resolve/reject
|
|
56
|
-
this
|
|
57
|
-
this
|
|
58
|
-
this
|
|
59
|
-
});
|
|
82
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
|
|
83
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
|
|
84
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, reject, "f");
|
|
85
|
+
}), "f");
|
|
60
86
|
}
|
|
61
87
|
async subscribe() {
|
|
62
88
|
// Clean up previous subscription attempt if retrying
|
|
63
|
-
if (this
|
|
64
|
-
this.
|
|
65
|
-
this
|
|
89
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
|
|
90
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
|
|
91
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
|
|
66
92
|
}
|
|
67
93
|
// Clear any existing timeout
|
|
68
|
-
if (this
|
|
69
|
-
clearTimeout(this
|
|
70
|
-
this
|
|
94
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
|
|
95
|
+
clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
|
|
96
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
|
|
71
97
|
}
|
|
72
98
|
// Clear any existing keepalive timer to prevent accumulation
|
|
73
|
-
if (this
|
|
74
|
-
clearTimeout(this
|
|
75
|
-
this
|
|
99
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
|
|
100
|
+
clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
|
|
101
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
|
|
76
102
|
}
|
|
77
103
|
try {
|
|
78
104
|
// Initialize the query subscription
|
|
79
105
|
let initialResult;
|
|
80
|
-
|
|
81
|
-
|
|
106
|
+
if (this.isSurrealDB) {
|
|
107
|
+
initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveSubscribeSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
|
|
111
|
+
}
|
|
112
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
|
|
82
113
|
// Process the initial result immediately for fast UX
|
|
83
114
|
if (initialResult.result) {
|
|
84
|
-
this
|
|
85
|
-
this.
|
|
115
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, initialResult.result, "f");
|
|
116
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);
|
|
86
117
|
}
|
|
87
118
|
else {
|
|
88
|
-
console.warn(
|
|
119
|
+
console.warn('⚠️ No initial result returned from subscribeQuery!');
|
|
89
120
|
}
|
|
90
121
|
// Set up timeout for retry
|
|
91
|
-
this
|
|
92
|
-
console.error(
|
|
122
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
|
|
123
|
+
console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
|
|
93
124
|
// Recursively retry subscription, catching any errors
|
|
94
|
-
this.subscribe().catch(
|
|
95
|
-
console.error(
|
|
125
|
+
this.subscribe().catch(error => {
|
|
126
|
+
console.error('Error during subscription retry after timeout:', error);
|
|
96
127
|
});
|
|
97
|
-
}, 30000);
|
|
128
|
+
}, 30000), "f");
|
|
98
129
|
// Subscribe to query updates
|
|
99
|
-
this
|
|
130
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => {
|
|
100
131
|
// Clear timeout on first message
|
|
101
|
-
if (this
|
|
102
|
-
clearTimeout(this
|
|
103
|
-
this
|
|
132
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
|
|
133
|
+
clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
|
|
134
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
|
|
104
135
|
}
|
|
105
136
|
// Resolve the initialization promise (only resolves once)
|
|
106
|
-
if (this
|
|
107
|
-
this.
|
|
108
|
-
this
|
|
109
|
-
this
|
|
137
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f")) {
|
|
138
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
|
|
139
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
|
|
140
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
|
|
110
141
|
}
|
|
111
142
|
// Skip duplicate init messages
|
|
112
|
-
if (updateResult.isInit && this
|
|
143
|
+
if (updateResult.isInit && __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f"))
|
|
113
144
|
return;
|
|
114
|
-
this
|
|
115
|
-
this.
|
|
116
|
-
});
|
|
145
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, updateResult, "f");
|
|
146
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);
|
|
147
|
+
}), "f");
|
|
117
148
|
}
|
|
118
149
|
catch (error) {
|
|
119
|
-
console.error(
|
|
150
|
+
console.error('Error setting up subscription:', error);
|
|
120
151
|
// Reject the promise if this is the first attempt
|
|
121
|
-
if (this
|
|
122
|
-
this.
|
|
123
|
-
this
|
|
124
|
-
this
|
|
152
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f")) {
|
|
153
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
|
|
154
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
|
|
155
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
|
|
125
156
|
}
|
|
126
157
|
throw error; // Re-throw so caller knows it failed
|
|
127
158
|
}
|
|
128
159
|
// Start keepalive loop using platform-agnostic setTimeout
|
|
129
160
|
const keepaliveLoop = async () => {
|
|
130
|
-
if (this
|
|
161
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
|
|
131
162
|
return;
|
|
132
163
|
try {
|
|
133
|
-
|
|
164
|
+
if (this.isSurrealDB) {
|
|
165
|
+
await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveKeepAliveSurrealQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
|
|
169
|
+
}
|
|
134
170
|
}
|
|
135
171
|
catch (e) {
|
|
136
|
-
console.error(
|
|
172
|
+
console.error('Error in keepalive:', e);
|
|
137
173
|
// try to reinitialize the subscription
|
|
138
|
-
console.log(
|
|
174
|
+
console.log('Reinitializing subscription for query:', __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
|
|
139
175
|
try {
|
|
140
176
|
await this.subscribe();
|
|
141
|
-
console.log(
|
|
177
|
+
console.log('Subscription reinitialized');
|
|
142
178
|
}
|
|
143
179
|
catch (resubscribeError) {
|
|
144
|
-
console.error(
|
|
180
|
+
console.error('Error during resubscription from keepalive:', resubscribeError);
|
|
145
181
|
// Don't schedule another keepalive on resubscribe failure
|
|
146
182
|
return;
|
|
147
183
|
}
|
|
148
184
|
}
|
|
149
185
|
// Schedule next keepalive if not disposed
|
|
150
|
-
if (!this
|
|
151
|
-
this
|
|
186
|
+
if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f")) {
|
|
187
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
|
|
152
188
|
}
|
|
153
189
|
};
|
|
154
190
|
// Start the first keepalive loop
|
|
155
|
-
this
|
|
191
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
|
|
156
192
|
}
|
|
157
193
|
/** Get the subscription ID for this query subscription
|
|
158
194
|
*
|
|
@@ -163,7 +199,7 @@ export class QuerySubscriptionProxy {
|
|
|
163
199
|
* @returns The subscription ID string
|
|
164
200
|
*/
|
|
165
201
|
get id() {
|
|
166
|
-
return this
|
|
202
|
+
return __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f");
|
|
167
203
|
}
|
|
168
204
|
/** Promise that resolves when the subscription has received its first result
|
|
169
205
|
* through the subscription channel. This ensures the subscription is fully
|
|
@@ -177,7 +213,7 @@ export class QuerySubscriptionProxy {
|
|
|
177
213
|
* creation methods (like subscribeInfer) already wait for initialization.
|
|
178
214
|
*/
|
|
179
215
|
get initialized() {
|
|
180
|
-
return this
|
|
216
|
+
return __classPrivateFieldGet(this, _QuerySubscriptionProxy_initialized, "f");
|
|
181
217
|
}
|
|
182
218
|
/** Get the latest query result
|
|
183
219
|
*
|
|
@@ -188,7 +224,7 @@ export class QuerySubscriptionProxy {
|
|
|
188
224
|
* @returns The latest query result as a string (usually a JSON array of bindings)
|
|
189
225
|
*/
|
|
190
226
|
get result() {
|
|
191
|
-
return this
|
|
227
|
+
return __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f");
|
|
192
228
|
}
|
|
193
229
|
/** Add a callback that will be called whenever new results arrive
|
|
194
230
|
*
|
|
@@ -210,19 +246,8 @@ export class QuerySubscriptionProxy {
|
|
|
210
246
|
* ```
|
|
211
247
|
*/
|
|
212
248
|
onResult(callback) {
|
|
213
|
-
this.
|
|
214
|
-
return () => this.
|
|
215
|
-
}
|
|
216
|
-
/** Internal method to notify all callbacks of a new result */
|
|
217
|
-
_notifyCallbacks(result) {
|
|
218
|
-
for (const callback of this._callbacks) {
|
|
219
|
-
try {
|
|
220
|
-
callback(result);
|
|
221
|
-
}
|
|
222
|
-
catch (e) {
|
|
223
|
-
console.error("Error in query subscription callback:", e);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
249
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
|
|
250
|
+
return () => __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
|
|
226
251
|
}
|
|
227
252
|
/** Clean up the subscription and stop keepalive signals
|
|
228
253
|
*
|
|
@@ -236,24 +261,39 @@ export class QuerySubscriptionProxy {
|
|
|
236
261
|
* will not receive any more updates. The instance should be discarded.
|
|
237
262
|
*/
|
|
238
263
|
dispose() {
|
|
239
|
-
this
|
|
240
|
-
clearTimeout(this
|
|
241
|
-
if (this
|
|
242
|
-
this.
|
|
264
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_disposed, true, "f");
|
|
265
|
+
clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
|
|
266
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
|
|
267
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
|
|
243
268
|
}
|
|
244
|
-
this.
|
|
245
|
-
if (this
|
|
246
|
-
clearTimeout(this
|
|
247
|
-
this
|
|
269
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").clear();
|
|
270
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
|
|
271
|
+
clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
|
|
272
|
+
__classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
|
|
248
273
|
}
|
|
249
274
|
// Tell the backend to dispose of the subscription
|
|
250
|
-
if (this
|
|
251
|
-
this.
|
|
252
|
-
.
|
|
253
|
-
|
|
275
|
+
if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f")) {
|
|
276
|
+
if (this.isSurrealDB) {
|
|
277
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").perspectiveDisposeSurrealQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
278
|
+
.catch(e => console.error('Error disposing surreal query subscription:', e));
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
__classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"))
|
|
282
|
+
.catch(e => console.error('Error disposing query subscription:', e));
|
|
283
|
+
}
|
|
254
284
|
}
|
|
255
285
|
}
|
|
256
286
|
}
|
|
287
|
+
_QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
|
|
288
|
+
for (const callback of __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f")) {
|
|
289
|
+
try {
|
|
290
|
+
callback(result);
|
|
291
|
+
}
|
|
292
|
+
catch (e) {
|
|
293
|
+
console.error('Error in query subscription callback:', e);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
};
|
|
257
297
|
/**
|
|
258
298
|
* PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
|
|
259
299
|
* that store and organize links between expressions.
|
|
@@ -293,159 +333,34 @@ export class QuerySubscriptionProxy {
|
|
|
293
333
|
* });
|
|
294
334
|
* ```
|
|
295
335
|
*/
|
|
296
|
-
/** Local (unexported) helper – was previously `core/src/model/Subject.ts` */
|
|
297
|
-
class Subject {
|
|
298
|
-
constructor(perspective, baseExpression, subjectClassName) {
|
|
299
|
-
this._baseExpression = baseExpression;
|
|
300
|
-
this._subjectClassName = subjectClassName;
|
|
301
|
-
this._perspective = perspective;
|
|
302
|
-
}
|
|
303
|
-
get baseExpression() {
|
|
304
|
-
return this._baseExpression;
|
|
305
|
-
}
|
|
306
|
-
async init() {
|
|
307
|
-
let isInstance = await this._perspective.isSubjectInstance(this._baseExpression, this._subjectClassName);
|
|
308
|
-
if (!isInstance) {
|
|
309
|
-
throw `Not a valid subject instance of ${this._subjectClassName} for ${this._baseExpression}`;
|
|
310
|
-
}
|
|
311
|
-
let results = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property(C, Property)`);
|
|
312
|
-
let properties = results.map((result) => result.Property);
|
|
313
|
-
for (let p of properties) {
|
|
314
|
-
await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_resolve(C, "${p}")`);
|
|
315
|
-
Object.defineProperty(this, p, {
|
|
316
|
-
configurable: true,
|
|
317
|
-
get: async () => {
|
|
318
|
-
try {
|
|
319
|
-
return await this._perspective.getPropertyValueViaSurreal(this._baseExpression, this._subjectClassName, p);
|
|
320
|
-
}
|
|
321
|
-
catch (err) {
|
|
322
|
-
console.warn(`Failed to get property ${p} via SurrealDB:`, err);
|
|
323
|
-
return undefined;
|
|
324
|
-
}
|
|
325
|
-
},
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
const setters = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_setter(C, Property, Setter)`);
|
|
329
|
-
for (let setter of setters ? setters : []) {
|
|
330
|
-
if (setter) {
|
|
331
|
-
const property = setter.Property;
|
|
332
|
-
const actions = eval(setter.Setter);
|
|
333
|
-
const resolveLanguageResults = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), property_resolve_language(C, "${property}", Language)`);
|
|
334
|
-
let resolveLanguage;
|
|
335
|
-
if (resolveLanguageResults && resolveLanguageResults.length > 0) {
|
|
336
|
-
resolveLanguage = resolveLanguageResults[0].Language;
|
|
337
|
-
}
|
|
338
|
-
this[propertyNameToSetterName(property)] = async (value) => {
|
|
339
|
-
if (resolveLanguage) {
|
|
340
|
-
value = await this._perspective.createExpression(value, resolveLanguage);
|
|
341
|
-
}
|
|
342
|
-
await this._perspective.executeAction(actions, this._baseExpression, [
|
|
343
|
-
{ name: "value", value },
|
|
344
|
-
]);
|
|
345
|
-
};
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
let results2 = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection(C, Collection)`);
|
|
349
|
-
if (!results2)
|
|
350
|
-
results2 = [];
|
|
351
|
-
let collections = results2.map((result) => result.Collection);
|
|
352
|
-
for (let c of collections) {
|
|
353
|
-
Object.defineProperty(this, c, {
|
|
354
|
-
configurable: true,
|
|
355
|
-
get: async () => {
|
|
356
|
-
try {
|
|
357
|
-
return await this._perspective.getCollectionValuesViaSurreal(this._baseExpression, this._subjectClassName, c);
|
|
358
|
-
}
|
|
359
|
-
catch (err) {
|
|
360
|
-
console.warn(`Failed to get collection ${c} via SurrealDB:`, err);
|
|
361
|
-
return [];
|
|
362
|
-
}
|
|
363
|
-
},
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
let adders = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_adder(C, Collection, Adder)`);
|
|
367
|
-
if (!adders)
|
|
368
|
-
adders = [];
|
|
369
|
-
for (let adder of adders) {
|
|
370
|
-
if (adder) {
|
|
371
|
-
const collection = adder.Collection;
|
|
372
|
-
const actions = eval(adder.Adder);
|
|
373
|
-
this[collectionToAdderName(collection)] = async (value) => {
|
|
374
|
-
if (Array.isArray(value)) {
|
|
375
|
-
await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [
|
|
376
|
-
{ name: "value", value: v },
|
|
377
|
-
])));
|
|
378
|
-
}
|
|
379
|
-
else {
|
|
380
|
-
await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
let removers = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_remover(C, Collection, Remover)`);
|
|
386
|
-
if (!removers)
|
|
387
|
-
removers = [];
|
|
388
|
-
for (let remover of removers) {
|
|
389
|
-
if (remover) {
|
|
390
|
-
const collection = remover.Collection;
|
|
391
|
-
const actions = eval(remover.Remover);
|
|
392
|
-
this[collectionToRemoverName(collection)] = async (value) => {
|
|
393
|
-
if (Array.isArray(value)) {
|
|
394
|
-
await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [
|
|
395
|
-
{ name: "value", value: v },
|
|
396
|
-
])));
|
|
397
|
-
}
|
|
398
|
-
else {
|
|
399
|
-
await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
|
|
400
|
-
}
|
|
401
|
-
};
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
let collectionSetters = await this._perspective.infer(`subject_class("${this._subjectClassName}", C), collection_setter(C, Collection, Setter)`);
|
|
405
|
-
if (!collectionSetters)
|
|
406
|
-
collectionSetters = [];
|
|
407
|
-
for (let collectionSetter of collectionSetters) {
|
|
408
|
-
if (collectionSetter) {
|
|
409
|
-
const collection = collectionSetter.Collection;
|
|
410
|
-
const actions = eval(collectionSetter.Setter);
|
|
411
|
-
this[collectionToSetterName(collection)] = async (value) => {
|
|
412
|
-
if (Array.isArray(value)) {
|
|
413
|
-
await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: "value", value: v })));
|
|
414
|
-
}
|
|
415
|
-
else {
|
|
416
|
-
await this._perspective.executeAction(actions, this._baseExpression, [{ name: "value", value }]);
|
|
417
|
-
}
|
|
418
|
-
};
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
336
|
export class PerspectiveProxy {
|
|
424
337
|
/**
|
|
425
338
|
* Creates a new PerspectiveProxy instance.
|
|
426
339
|
* Note: Don't create this directly, use ad4m.perspective.add() instead.
|
|
427
340
|
*/
|
|
428
341
|
constructor(handle, ad4m) {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
this
|
|
434
|
-
this
|
|
435
|
-
this
|
|
436
|
-
this
|
|
437
|
-
this
|
|
438
|
-
this
|
|
439
|
-
this
|
|
440
|
-
this
|
|
441
|
-
this.
|
|
442
|
-
this.
|
|
443
|
-
this.
|
|
444
|
-
this.
|
|
445
|
-
this.
|
|
446
|
-
this.
|
|
447
|
-
this.
|
|
448
|
-
this.
|
|
342
|
+
_PerspectiveProxy_handle.set(this, void 0);
|
|
343
|
+
_PerspectiveProxy_client.set(this, void 0);
|
|
344
|
+
_PerspectiveProxy_perspectiveLinkAddedCallbacks.set(this, void 0);
|
|
345
|
+
_PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);
|
|
346
|
+
_PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);
|
|
347
|
+
_PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);
|
|
348
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], "f");
|
|
349
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], "f");
|
|
350
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], "f");
|
|
351
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], "f");
|
|
352
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_handle, handle, "f");
|
|
353
|
+
__classPrivateFieldSet(this, _PerspectiveProxy_client, ad4m, "f");
|
|
354
|
+
this.uuid = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid;
|
|
355
|
+
this.name = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").name;
|
|
356
|
+
this.owners = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").owners;
|
|
357
|
+
this.sharedUrl = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").sharedUrl;
|
|
358
|
+
this.neighbourhood = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").neighbourhood;
|
|
359
|
+
this.state = __classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").state;
|
|
360
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkAddedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f"));
|
|
361
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkRemovedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f"));
|
|
362
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f"));
|
|
363
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f"));
|
|
449
364
|
}
|
|
450
365
|
/**
|
|
451
366
|
* Escapes special regex characters in a string to prevent ReDoS attacks
|
|
@@ -457,7 +372,7 @@ export class PerspectiveProxy {
|
|
|
457
372
|
* @private
|
|
458
373
|
*/
|
|
459
374
|
escapeRegExp(str) {
|
|
460
|
-
return str.replace(/[.*+?^${}()|[\]\\]/g,
|
|
375
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
461
376
|
}
|
|
462
377
|
/**
|
|
463
378
|
* Executes a set of actions on an expression with optional parameters.
|
|
@@ -467,7 +382,7 @@ export class PerspectiveProxy {
|
|
|
467
382
|
* Each action is an object with the following format:
|
|
468
383
|
* ```typescript
|
|
469
384
|
* {
|
|
470
|
-
* action: "addLink" | "removeLink" | "setSingleTarget" | "
|
|
385
|
+
* action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
|
|
471
386
|
* source: string, // Usually "this" to reference the current expression
|
|
472
387
|
* predicate: string, // The predicate URI
|
|
473
388
|
* target: string // The target value or "value" for parameters
|
|
@@ -478,7 +393,7 @@ export class PerspectiveProxy {
|
|
|
478
393
|
* - `addLink`: Creates a new link
|
|
479
394
|
* - `removeLink`: Removes an existing link
|
|
480
395
|
* - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one
|
|
481
|
-
* - `
|
|
396
|
+
* - `collectionSetter`: Special command for setting relation properties
|
|
482
397
|
*
|
|
483
398
|
* When used with parameters, the special value "value" in the target field will be
|
|
484
399
|
* replaced with the actual parameter value.
|
|
@@ -520,7 +435,7 @@ export class PerspectiveProxy {
|
|
|
520
435
|
* @param batchId - Optional batch ID to group this operation with others
|
|
521
436
|
*/
|
|
522
437
|
async executeAction(actions, expression, parameters, batchId) {
|
|
523
|
-
return await this.
|
|
438
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").executeCommands(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);
|
|
524
439
|
}
|
|
525
440
|
/**
|
|
526
441
|
* Retrieves links from the perspective that match the given query.
|
|
@@ -544,7 +459,7 @@ export class PerspectiveProxy {
|
|
|
544
459
|
* ```
|
|
545
460
|
*/
|
|
546
461
|
async get(query) {
|
|
547
|
-
return await this.
|
|
462
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
548
463
|
}
|
|
549
464
|
/**
|
|
550
465
|
* Executes a Prolog query against the perspective's knowledge base.
|
|
@@ -570,7 +485,7 @@ export class PerspectiveProxy {
|
|
|
570
485
|
* ```
|
|
571
486
|
*/
|
|
572
487
|
async infer(query) {
|
|
573
|
-
return await this.
|
|
488
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").queryProlog(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
574
489
|
}
|
|
575
490
|
/**
|
|
576
491
|
* Executes a SurrealQL query against the perspective's link cache.
|
|
@@ -600,7 +515,7 @@ export class PerspectiveProxy {
|
|
|
600
515
|
* ```
|
|
601
516
|
*/
|
|
602
517
|
async querySurrealDB(query) {
|
|
603
|
-
return await this.
|
|
518
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").querySurrealDB(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, query);
|
|
604
519
|
}
|
|
605
520
|
/**
|
|
606
521
|
* Adds a new link to the perspective.
|
|
@@ -627,8 +542,8 @@ export class PerspectiveProxy {
|
|
|
627
542
|
* }, "local");
|
|
628
543
|
* ```
|
|
629
544
|
*/
|
|
630
|
-
async add(link, status =
|
|
631
|
-
return await this.
|
|
545
|
+
async add(link, status = 'shared', batchId) {
|
|
546
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
|
|
632
547
|
}
|
|
633
548
|
/**
|
|
634
549
|
* Adds multiple links to the perspective in a single operation.
|
|
@@ -639,8 +554,8 @@ export class PerspectiveProxy {
|
|
|
639
554
|
* @param batchId - Optional batch ID to group this operation with others
|
|
640
555
|
* @returns Array of created LinkExpressions
|
|
641
556
|
*/
|
|
642
|
-
async addLinks(links, status =
|
|
643
|
-
return await this.
|
|
557
|
+
async addLinks(links, status = 'shared', batchId) {
|
|
558
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, status, batchId);
|
|
644
559
|
}
|
|
645
560
|
/**
|
|
646
561
|
* Removes multiple links from the perspective.
|
|
@@ -650,7 +565,7 @@ export class PerspectiveProxy {
|
|
|
650
565
|
* @returns Array of removed LinkExpressions
|
|
651
566
|
*/
|
|
652
567
|
async removeLinks(links, batchId) {
|
|
653
|
-
return await this.
|
|
568
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLinks(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, links, batchId);
|
|
654
569
|
}
|
|
655
570
|
/**
|
|
656
571
|
* Applies a set of link mutations (adds and removes) in a single operation.
|
|
@@ -660,29 +575,29 @@ export class PerspectiveProxy {
|
|
|
660
575
|
* @param status - Whether new links should be shared
|
|
661
576
|
* @returns Object containing results of the mutations
|
|
662
577
|
*/
|
|
663
|
-
async linkMutations(mutations, status =
|
|
664
|
-
return await this.
|
|
578
|
+
async linkMutations(mutations, status = 'shared') {
|
|
579
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").linkMutations(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, mutations, status);
|
|
665
580
|
}
|
|
666
581
|
/**
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
async addLinkExpression(link, status =
|
|
675
|
-
return await this.
|
|
582
|
+
* Adds a pre-signed LinkExpression to the perspective.
|
|
583
|
+
*
|
|
584
|
+
* @param link - The signed LinkExpression to add
|
|
585
|
+
* @param status - Whether the link should be shared
|
|
586
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
587
|
+
* @returns The added LinkExpression
|
|
588
|
+
*/
|
|
589
|
+
async addLinkExpression(link, status = 'shared', batchId) {
|
|
590
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addLinkExpression(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, status, batchId);
|
|
676
591
|
}
|
|
677
592
|
/**
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
593
|
+
* Updates an existing link with new data.
|
|
594
|
+
*
|
|
595
|
+
* @param oldLink - The existing link to update
|
|
596
|
+
* @param newLink - The new link data
|
|
597
|
+
* @param batchId - Optional batch ID to group this operation with others
|
|
598
|
+
*/
|
|
684
599
|
async update(oldLink, newLink, batchId) {
|
|
685
|
-
return await this.
|
|
600
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, oldLink, newLink, batchId);
|
|
686
601
|
}
|
|
687
602
|
/**
|
|
688
603
|
* Removes a link from the perspective.
|
|
@@ -691,15 +606,15 @@ export class PerspectiveProxy {
|
|
|
691
606
|
* @param batchId - Optional batch ID to group this operation with others
|
|
692
607
|
*/
|
|
693
608
|
async remove(link, batchId) {
|
|
694
|
-
return await this.
|
|
609
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeLink(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, link, batchId);
|
|
695
610
|
}
|
|
696
611
|
/** Creates a new batch for grouping operations */
|
|
697
612
|
async createBatch() {
|
|
698
|
-
return await this.
|
|
613
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
|
|
699
614
|
}
|
|
700
615
|
/** Commits a batch of operations */
|
|
701
616
|
async commitBatch(batchId) {
|
|
702
|
-
return await this.
|
|
617
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").commitBatch(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, batchId);
|
|
703
618
|
}
|
|
704
619
|
/**
|
|
705
620
|
* Retrieves and renders an Expression referenced in this perspective.
|
|
@@ -708,7 +623,7 @@ export class PerspectiveProxy {
|
|
|
708
623
|
* @returns The rendered Expression
|
|
709
624
|
*/
|
|
710
625
|
async getExpression(expressionURI) {
|
|
711
|
-
return await this.
|
|
626
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getExpression(expressionURI);
|
|
712
627
|
}
|
|
713
628
|
/**
|
|
714
629
|
* Creates a new Expression in the specified Language.
|
|
@@ -718,7 +633,7 @@ export class PerspectiveProxy {
|
|
|
718
633
|
* @returns URI of the created Expression
|
|
719
634
|
*/
|
|
720
635
|
async createExpression(content, languageAddress) {
|
|
721
|
-
return await this.
|
|
636
|
+
return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createExpression(content, languageAddress);
|
|
722
637
|
}
|
|
723
638
|
/**
|
|
724
639
|
* Subscribes to link changes in the perspective.
|
|
@@ -740,14 +655,14 @@ export class PerspectiveProxy {
|
|
|
740
655
|
* ```
|
|
741
656
|
*/
|
|
742
657
|
async addListener(type, cb) {
|
|
743
|
-
if (type ===
|
|
744
|
-
this.
|
|
658
|
+
if (type === 'link-added') {
|
|
659
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").push(cb);
|
|
745
660
|
}
|
|
746
|
-
else if (type ===
|
|
747
|
-
this.
|
|
661
|
+
else if (type === 'link-removed') {
|
|
662
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").push(cb);
|
|
748
663
|
}
|
|
749
|
-
else if (type ===
|
|
750
|
-
this.
|
|
664
|
+
else if (type === 'link-updated') {
|
|
665
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").push(cb);
|
|
751
666
|
}
|
|
752
667
|
}
|
|
753
668
|
/**
|
|
@@ -763,7 +678,7 @@ export class PerspectiveProxy {
|
|
|
763
678
|
* ```
|
|
764
679
|
*/
|
|
765
680
|
async addSyncStateChangeListener(cb) {
|
|
766
|
-
this.
|
|
681
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, "f").push(cb);
|
|
767
682
|
}
|
|
768
683
|
/**
|
|
769
684
|
* Unsubscribes from link changes.
|
|
@@ -772,17 +687,17 @@ export class PerspectiveProxy {
|
|
|
772
687
|
* @param cb - The callback function to remove
|
|
773
688
|
*/
|
|
774
689
|
async removeListener(type, cb) {
|
|
775
|
-
if (type ===
|
|
776
|
-
const index = this.
|
|
777
|
-
this.
|
|
690
|
+
if (type === 'link-added') {
|
|
691
|
+
const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").indexOf(cb);
|
|
692
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, "f").splice(index, 1);
|
|
778
693
|
}
|
|
779
|
-
else if (type ===
|
|
780
|
-
const index = this.
|
|
781
|
-
this.
|
|
694
|
+
else if (type === 'link-removed') {
|
|
695
|
+
const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").indexOf(cb);
|
|
696
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, "f").splice(index, 1);
|
|
782
697
|
}
|
|
783
|
-
else if (type ===
|
|
784
|
-
const index = this.
|
|
785
|
-
this.
|
|
698
|
+
else if (type === 'link-updated') {
|
|
699
|
+
const index = __classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").indexOf(cb);
|
|
700
|
+
__classPrivateFieldGet(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, "f").splice(index, 1);
|
|
786
701
|
}
|
|
787
702
|
}
|
|
788
703
|
/**
|
|
@@ -792,7 +707,7 @@ export class PerspectiveProxy {
|
|
|
792
707
|
* @returns Perspective object containing all links
|
|
793
708
|
*/
|
|
794
709
|
async snapshot() {
|
|
795
|
-
return this.
|
|
710
|
+
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").snapshotByUUID(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
|
|
796
711
|
}
|
|
797
712
|
/**
|
|
798
713
|
* Loads a perspective snapshot, replacing current content.
|
|
@@ -803,7 +718,7 @@ export class PerspectiveProxy {
|
|
|
803
718
|
//Clean the input data from __typename
|
|
804
719
|
const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));
|
|
805
720
|
delete cleanedSnapshot.__typename;
|
|
806
|
-
cleanedSnapshot.links.forEach(
|
|
721
|
+
cleanedSnapshot.links.forEach(link => {
|
|
807
722
|
delete link.data.__typename;
|
|
808
723
|
});
|
|
809
724
|
for (const link of cleanedSnapshot.links) {
|
|
@@ -850,11 +765,8 @@ export class PerspectiveProxy {
|
|
|
850
765
|
* });
|
|
851
766
|
* ```
|
|
852
767
|
*/
|
|
853
|
-
async setSingleTarget(link, status =
|
|
854
|
-
const query = new LinkQuery({
|
|
855
|
-
source: link.source,
|
|
856
|
-
predicate: link.predicate,
|
|
857
|
-
});
|
|
768
|
+
async setSingleTarget(link, status = 'shared') {
|
|
769
|
+
const query = new LinkQuery({ source: link.source, predicate: link.predicate });
|
|
858
770
|
const foundLinks = await this.get(query);
|
|
859
771
|
const removals = [];
|
|
860
772
|
for (const l of foundLinks) {
|
|
@@ -871,9 +783,9 @@ export class PerspectiveProxy {
|
|
|
871
783
|
// Query for all flow registration links
|
|
872
784
|
const flowLinks = await this.get(new LinkQuery({
|
|
873
785
|
source: "ad4m://self",
|
|
874
|
-
predicate: "ad4m://has_flow"
|
|
786
|
+
predicate: "ad4m://has_flow"
|
|
875
787
|
}));
|
|
876
|
-
return flowLinks.map(
|
|
788
|
+
return flowLinks.map(l => {
|
|
877
789
|
try {
|
|
878
790
|
return Literal.fromUrl(l.data.target).get();
|
|
879
791
|
}
|
|
@@ -900,7 +812,7 @@ export class PerspectiveProxy {
|
|
|
900
812
|
const links = await this.get(new LinkQuery({
|
|
901
813
|
source,
|
|
902
814
|
predicate: pattern.predicate,
|
|
903
|
-
target: pattern.target
|
|
815
|
+
target: pattern.target
|
|
904
816
|
}));
|
|
905
817
|
if (links.length > 0) {
|
|
906
818
|
available.push(name);
|
|
@@ -924,17 +836,17 @@ export class PerspectiveProxy {
|
|
|
924
836
|
if (!flow)
|
|
925
837
|
return [];
|
|
926
838
|
// Find the state with the matching value
|
|
927
|
-
const state = flow.states.find(
|
|
839
|
+
const state = flow.states.find(s => s.value === flowState);
|
|
928
840
|
if (!state)
|
|
929
841
|
return [];
|
|
930
842
|
// Query for expressions matching this state's check pattern
|
|
931
843
|
const pattern = state.stateCheck;
|
|
932
844
|
const links = await this.get(new LinkQuery({
|
|
933
845
|
predicate: pattern.predicate,
|
|
934
|
-
target: pattern.target
|
|
846
|
+
target: pattern.target
|
|
935
847
|
}));
|
|
936
848
|
// Return the sources (expression addresses) - use source if pattern has no explicit source
|
|
937
|
-
return links.map(
|
|
849
|
+
return links.map(l => pattern.source ? l.data.target : l.data.source);
|
|
938
850
|
}
|
|
939
851
|
/** Returns the given expression's flow state with regard to given Social DNA flow */
|
|
940
852
|
async flowState(flowName, exprAddr) {
|
|
@@ -948,7 +860,7 @@ export class PerspectiveProxy {
|
|
|
948
860
|
const links = await this.get(new LinkQuery({
|
|
949
861
|
source,
|
|
950
862
|
predicate: pattern.predicate,
|
|
951
|
-
target: pattern.target
|
|
863
|
+
target: pattern.target
|
|
952
864
|
}));
|
|
953
865
|
if (links.length > 0)
|
|
954
866
|
return state.value;
|
|
@@ -968,7 +880,7 @@ export class PerspectiveProxy {
|
|
|
968
880
|
const links = await this.get(new LinkQuery({
|
|
969
881
|
source,
|
|
970
882
|
predicate: pattern.predicate,
|
|
971
|
-
target: pattern.target
|
|
883
|
+
target: pattern.target
|
|
972
884
|
}));
|
|
973
885
|
if (links.length > 0) {
|
|
974
886
|
currentStateName = state.name;
|
|
@@ -979,15 +891,15 @@ export class PerspectiveProxy {
|
|
|
979
891
|
return [];
|
|
980
892
|
// Return transitions available from current state
|
|
981
893
|
return flow.transitions
|
|
982
|
-
.filter(
|
|
983
|
-
.map(
|
|
894
|
+
.filter(t => t.fromState === currentStateName)
|
|
895
|
+
.map(t => t.actionName);
|
|
984
896
|
}
|
|
985
897
|
/** Runs given Social DNA flow action */
|
|
986
898
|
async runFlowAction(flowName, exprAddr, actionName) {
|
|
987
899
|
const flow = await this.getFlow(flowName);
|
|
988
900
|
if (!flow)
|
|
989
901
|
throw `Flow "${flowName}" not found`;
|
|
990
|
-
const transition = flow.transitions.find(
|
|
902
|
+
const transition = flow.transitions.find(t => t.actionName === actionName);
|
|
991
903
|
if (!transition)
|
|
992
904
|
throw `Action "${actionName}" not found in flow "${flowName}"`;
|
|
993
905
|
await this.executeAction(transition.actions, exprAddr, undefined);
|
|
@@ -1000,14 +912,14 @@ export class PerspectiveProxy {
|
|
|
1000
912
|
const sdnaPredicates = [
|
|
1001
913
|
"ad4m://has_subject_class",
|
|
1002
914
|
"ad4m://has_flow",
|
|
1003
|
-
"ad4m://has_custom_sdna"
|
|
915
|
+
"ad4m://has_custom_sdna"
|
|
1004
916
|
];
|
|
1005
917
|
const allSdnaCode = [];
|
|
1006
918
|
for (const predicate of sdnaPredicates) {
|
|
1007
919
|
// Find name literals linked from ad4m://self with this predicate
|
|
1008
920
|
const nameLinks = await this.get(new LinkQuery({
|
|
1009
921
|
source: "ad4m://self",
|
|
1010
|
-
predicate: predicate
|
|
922
|
+
predicate: predicate
|
|
1011
923
|
}));
|
|
1012
924
|
// For each name literal found, get the actual SDNA code
|
|
1013
925
|
for (const nameLink of nameLinks) {
|
|
@@ -1015,12 +927,12 @@ export class PerspectiveProxy {
|
|
|
1015
927
|
// Now find the SDNA code linked from this name with predicate "ad4m://sdna"
|
|
1016
928
|
const sdnaLinks = await this.get(new LinkQuery({
|
|
1017
929
|
source: nameLiteral,
|
|
1018
|
-
predicate: "ad4m://sdna"
|
|
930
|
+
predicate: "ad4m://sdna"
|
|
1019
931
|
}));
|
|
1020
932
|
// Extract the SDNA code from each link
|
|
1021
933
|
for (const sdnaLink of sdnaLinks) {
|
|
1022
934
|
const code = Literal.fromUrl(sdnaLink.data.target).get();
|
|
1023
|
-
if (typeof code ===
|
|
935
|
+
if (typeof code === 'string') {
|
|
1024
936
|
allSdnaCode.push(code);
|
|
1025
937
|
}
|
|
1026
938
|
}
|
|
@@ -1037,7 +949,7 @@ export class PerspectiveProxy {
|
|
|
1037
949
|
const links = await this.get(new LinkQuery({
|
|
1038
950
|
source: "ad4m://self",
|
|
1039
951
|
target: nameLiteral.toUrl(),
|
|
1040
|
-
predicate: "ad4m://has_subject_class"
|
|
952
|
+
predicate: "ad4m://has_subject_class"
|
|
1041
953
|
}));
|
|
1042
954
|
if (links.length === 0) {
|
|
1043
955
|
return null;
|
|
@@ -1045,14 +957,14 @@ export class PerspectiveProxy {
|
|
|
1045
957
|
// Now find the SDNA code linked from this name with predicate "ad4m://sdna"
|
|
1046
958
|
const sdnaLinks = await this.get(new LinkQuery({
|
|
1047
959
|
source: nameLiteral.toUrl(),
|
|
1048
|
-
predicate: "ad4m://sdna"
|
|
960
|
+
predicate: "ad4m://sdna"
|
|
1049
961
|
}));
|
|
1050
962
|
if (sdnaLinks.length === 0) {
|
|
1051
963
|
return null;
|
|
1052
964
|
}
|
|
1053
965
|
// Extract the SDNA code from the first link
|
|
1054
966
|
const code = Literal.fromUrl(sdnaLinks[0].data.target).get();
|
|
1055
|
-
return typeof code ===
|
|
967
|
+
return typeof code === 'string' ? code : null;
|
|
1056
968
|
}
|
|
1057
969
|
/**
|
|
1058
970
|
* Adds Social DNA code to the perspective.
|
|
@@ -1075,7 +987,7 @@ export class PerspectiveProxy {
|
|
|
1075
987
|
* await perspective.addSdna('Recipe', prologCode, 'subject_class');
|
|
1076
988
|
*/
|
|
1077
989
|
async addSdna(name, sdnaCode, sdnaType, shaclJson) {
|
|
1078
|
-
return this.
|
|
990
|
+
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").addSdna(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, name, sdnaCode, sdnaType, shaclJson);
|
|
1079
991
|
}
|
|
1080
992
|
/**
|
|
1081
993
|
* **Recommended way to add SDNA schemas.**
|
|
@@ -1099,34 +1011,35 @@ export class PerspectiveProxy {
|
|
|
1099
1011
|
* shape.addProperty({
|
|
1100
1012
|
* name: 'ingredients',
|
|
1101
1013
|
* path: 'recipe://has_ingredient',
|
|
1102
|
-
* // No maxCount =
|
|
1014
|
+
* // No maxCount = relation
|
|
1103
1015
|
* });
|
|
1104
1016
|
*
|
|
1105
1017
|
* await perspective.addShacl('Recipe', shape);
|
|
1106
1018
|
*/
|
|
1107
1019
|
async addShacl(name, shape) {
|
|
1108
1020
|
// Serialize shape to links
|
|
1109
|
-
const
|
|
1110
|
-
//
|
|
1111
|
-
for (const link of links) {
|
|
1112
|
-
await this.add({
|
|
1113
|
-
source: link.source,
|
|
1114
|
-
predicate: link.predicate,
|
|
1115
|
-
target: link.target,
|
|
1116
|
-
});
|
|
1117
|
-
}
|
|
1118
|
-
// Create a name -> shape mapping link for easy retrieval
|
|
1021
|
+
const shapeLinks = shape.toLinks();
|
|
1022
|
+
// Create name -> shape mapping links
|
|
1119
1023
|
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1024
|
+
const allLinks = [
|
|
1025
|
+
...shapeLinks.map(l => new Link({
|
|
1026
|
+
source: l.source,
|
|
1027
|
+
predicate: l.predicate,
|
|
1028
|
+
target: l.target
|
|
1029
|
+
})),
|
|
1030
|
+
new Link({
|
|
1031
|
+
source: "ad4m://self",
|
|
1032
|
+
predicate: "ad4m://has_shacl",
|
|
1033
|
+
target: nameMapping.toUrl()
|
|
1034
|
+
}),
|
|
1035
|
+
new Link({
|
|
1036
|
+
source: nameMapping.toUrl(),
|
|
1037
|
+
predicate: "ad4m://shacl_shape_uri",
|
|
1038
|
+
target: shape.nodeShapeUri
|
|
1039
|
+
})
|
|
1040
|
+
];
|
|
1041
|
+
// Batch add all links at once
|
|
1042
|
+
await this.addLinks(allLinks);
|
|
1130
1043
|
}
|
|
1131
1044
|
/**
|
|
1132
1045
|
* Retrieve a SHACL shape by name from this Perspective
|
|
@@ -1136,72 +1049,28 @@ export class PerspectiveProxy {
|
|
|
1136
1049
|
const nameMapping = Literal.fromUrl(`literal://string:shacl://${name}`);
|
|
1137
1050
|
const shapeUriLinks = await this.get(new LinkQuery({
|
|
1138
1051
|
source: nameMapping.toUrl(),
|
|
1139
|
-
predicate: "ad4m://shacl_shape_uri"
|
|
1052
|
+
predicate: "ad4m://shacl_shape_uri"
|
|
1140
1053
|
}));
|
|
1141
1054
|
if (shapeUriLinks.length === 0) {
|
|
1142
1055
|
return null;
|
|
1143
1056
|
}
|
|
1144
1057
|
const shapeUri = shapeUriLinks[0].data.target;
|
|
1145
|
-
|
|
1146
|
-
//
|
|
1147
|
-
const shapeLinks = [];
|
|
1148
|
-
// Get shape type and target class
|
|
1149
|
-
const shapeTypeLinks = await this.get(new LinkQuery({
|
|
1150
|
-
source: shapeUri,
|
|
1151
|
-
predicate: "rdf://type",
|
|
1152
|
-
}));
|
|
1153
|
-
shapeLinks.push(...shapeTypeLinks.map((l) => l.data));
|
|
1154
|
-
const targetClassLinks = await this.get(new LinkQuery({
|
|
1155
|
-
source: shapeUri,
|
|
1156
|
-
predicate: "sh://targetClass",
|
|
1157
|
-
}));
|
|
1158
|
-
shapeLinks.push(...targetClassLinks.map((l) => l.data));
|
|
1159
|
-
// Get constructor actions
|
|
1160
|
-
const constructorLinks = await this.get(new LinkQuery({
|
|
1161
|
-
source: shapeUri,
|
|
1162
|
-
predicate: "ad4m://constructor",
|
|
1163
|
-
}));
|
|
1164
|
-
shapeLinks.push(...constructorLinks.map((l) => l.data));
|
|
1165
|
-
// Get destructor actions
|
|
1166
|
-
const destructorLinks = await this.get(new LinkQuery({
|
|
1167
|
-
source: shapeUri,
|
|
1168
|
-
predicate: "ad4m://destructor",
|
|
1169
|
-
}));
|
|
1170
|
-
shapeLinks.push(...destructorLinks.map((l) => l.data));
|
|
1171
|
-
// Get property shapes
|
|
1058
|
+
const escapedShapeUri = escapeSurrealString(shapeUri);
|
|
1059
|
+
// First get property shape URIs so we can query everything in one go
|
|
1172
1060
|
const propertyLinks = await this.get(new LinkQuery({
|
|
1173
1061
|
source: shapeUri,
|
|
1174
|
-
predicate: "sh://property"
|
|
1062
|
+
predicate: "sh://property"
|
|
1063
|
+
}));
|
|
1064
|
+
// Build a single surreal query that fetches all relevant links
|
|
1065
|
+
const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];
|
|
1066
|
+
const escapedSources = sourceUris.map(u => `'${escapeSurrealString(u)}'`).join(', ');
|
|
1067
|
+
const query = `SELECT in.uri AS source, predicate, out.uri AS target FROM link WHERE in.uri IN [${escapedSources}]`;
|
|
1068
|
+
const result = await this.querySurrealDB(query);
|
|
1069
|
+
const shapeLinks = (result || []).map((r) => ({
|
|
1070
|
+
source: r.source,
|
|
1071
|
+
predicate: r.predicate,
|
|
1072
|
+
target: r.target
|
|
1175
1073
|
}));
|
|
1176
|
-
for (const propLink of propertyLinks) {
|
|
1177
|
-
shapeLinks.push(propLink.data);
|
|
1178
|
-
// Get all links for this property shape (named URI or blank node)
|
|
1179
|
-
const propShapeId = propLink.data.target;
|
|
1180
|
-
// Query targeted predicates for this property shape to avoid loading all links
|
|
1181
|
-
const expectedPredicates = [
|
|
1182
|
-
"sh://path",
|
|
1183
|
-
"sh://datatype",
|
|
1184
|
-
"sh://nodeKind",
|
|
1185
|
-
"sh://minCount",
|
|
1186
|
-
"sh://maxCount",
|
|
1187
|
-
"ad4m://local",
|
|
1188
|
-
"ad4m://readOnly",
|
|
1189
|
-
"ad4m://resolveLanguage",
|
|
1190
|
-
"ad4m://setter",
|
|
1191
|
-
"ad4m://adder",
|
|
1192
|
-
"ad4m://remover",
|
|
1193
|
-
"rdf://type", // For CollectionShape detection
|
|
1194
|
-
];
|
|
1195
|
-
for (const predicate of expectedPredicates) {
|
|
1196
|
-
const links = await this.get(new LinkQuery({
|
|
1197
|
-
source: propShapeId,
|
|
1198
|
-
predicate,
|
|
1199
|
-
}));
|
|
1200
|
-
shapeLinks.push(...links.map((l) => l.data));
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
// Reconstruct shape from links
|
|
1204
|
-
const { SHACLShape } = await import("../shacl/SHACLShape");
|
|
1205
1074
|
return SHACLShape.fromLinks(shapeLinks, shapeUri);
|
|
1206
1075
|
}
|
|
1207
1076
|
/**
|
|
@@ -1210,13 +1079,13 @@ export class PerspectiveProxy {
|
|
|
1210
1079
|
async getAllShacl() {
|
|
1211
1080
|
const nameLinks = await this.get(new LinkQuery({
|
|
1212
1081
|
source: "ad4m://self",
|
|
1213
|
-
predicate: "ad4m://has_shacl"
|
|
1082
|
+
predicate: "ad4m://has_shacl"
|
|
1214
1083
|
}));
|
|
1215
1084
|
const shapes = [];
|
|
1216
1085
|
for (const nameLink of nameLinks) {
|
|
1217
1086
|
const nameUrl = nameLink.data.target;
|
|
1218
1087
|
const name = Literal.fromUrl(nameUrl).get();
|
|
1219
|
-
const shapeName = name.replace(
|
|
1088
|
+
const shapeName = name.replace('shacl://', '');
|
|
1220
1089
|
const shape = await this.getShacl(shapeName);
|
|
1221
1090
|
if (shape) {
|
|
1222
1091
|
shapes.push({ name: shapeName, shape });
|
|
@@ -1263,28 +1132,28 @@ export class PerspectiveProxy {
|
|
|
1263
1132
|
*/
|
|
1264
1133
|
async addFlow(name, flow) {
|
|
1265
1134
|
// Serialize flow to links
|
|
1266
|
-
const
|
|
1267
|
-
//
|
|
1268
|
-
for (const link of links) {
|
|
1269
|
-
await this.add({
|
|
1270
|
-
source: link.source,
|
|
1271
|
-
predicate: link.predicate,
|
|
1272
|
-
target: link.target,
|
|
1273
|
-
});
|
|
1274
|
-
}
|
|
1275
|
-
// Create registration link matching ad4m://has_flow pattern
|
|
1135
|
+
const flowLinks = flow.toLinks();
|
|
1136
|
+
// Create registration and mapping links
|
|
1276
1137
|
const flowNameLiteral = Literal.from(name).toUrl();
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1138
|
+
const allLinks = [
|
|
1139
|
+
...flowLinks.map(l => new Link({
|
|
1140
|
+
source: l.source,
|
|
1141
|
+
predicate: l.predicate,
|
|
1142
|
+
target: l.target
|
|
1143
|
+
})),
|
|
1144
|
+
new Link({
|
|
1145
|
+
source: "ad4m://self",
|
|
1146
|
+
predicate: "ad4m://has_flow",
|
|
1147
|
+
target: flowNameLiteral
|
|
1148
|
+
}),
|
|
1149
|
+
new Link({
|
|
1150
|
+
source: flowNameLiteral,
|
|
1151
|
+
predicate: "ad4m://flow_uri",
|
|
1152
|
+
target: flow.flowUri
|
|
1153
|
+
})
|
|
1154
|
+
];
|
|
1155
|
+
// Batch add all links at once
|
|
1156
|
+
await this.addLinks(allLinks);
|
|
1288
1157
|
}
|
|
1289
1158
|
/**
|
|
1290
1159
|
* Retrieve a Flow definition by name from this Perspective
|
|
@@ -1297,45 +1166,26 @@ export class PerspectiveProxy {
|
|
|
1297
1166
|
// Find flow URI from name mapping
|
|
1298
1167
|
const flowUriLinks = await this.get(new LinkQuery({
|
|
1299
1168
|
source: flowNameLiteral,
|
|
1300
|
-
predicate: "ad4m://flow_uri"
|
|
1169
|
+
predicate: "ad4m://flow_uri"
|
|
1301
1170
|
}));
|
|
1302
1171
|
if (flowUriLinks.length === 0) {
|
|
1303
1172
|
return null;
|
|
1304
1173
|
}
|
|
1305
1174
|
const flowUri = flowUriLinks[0].data.target;
|
|
1306
|
-
|
|
1307
|
-
//
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
const
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
"ad4m://hasTransition",
|
|
1321
|
-
"ad4m://stateName",
|
|
1322
|
-
"ad4m://stateValue",
|
|
1323
|
-
"ad4m://stateCheck",
|
|
1324
|
-
"ad4m://actionName",
|
|
1325
|
-
"ad4m://fromState",
|
|
1326
|
-
"ad4m://toState",
|
|
1327
|
-
"ad4m://transitionActions",
|
|
1328
|
-
];
|
|
1329
|
-
const allLinks = [];
|
|
1330
|
-
for (const predicate of flowPredicates) {
|
|
1331
|
-
const links = await this.get(new LinkQuery({ predicate }));
|
|
1332
|
-
allLinks.push(...links);
|
|
1333
|
-
}
|
|
1334
|
-
const flowLinks = allLinks
|
|
1335
|
-
.map((l) => l.data)
|
|
1336
|
-
.filter((l) => l.source === flowUri || l.source.startsWith(alternatePrefix));
|
|
1337
|
-
// Reconstruct flow from links
|
|
1338
|
-
const { SHACLFlow } = await import("../shacl/SHACLFlow");
|
|
1175
|
+
const escapedFlowUri = escapeSurrealString(flowUri);
|
|
1176
|
+
// Compute alternate prefix for state/transition URIs
|
|
1177
|
+
const alternatePrefix = flowUri.endsWith('Flow')
|
|
1178
|
+
? flowUri.slice(0, -4) + '.'
|
|
1179
|
+
: flowUri + '.';
|
|
1180
|
+
const escapedAltPrefix = escapeSurrealString(alternatePrefix);
|
|
1181
|
+
// Single surreal query to get all flow-related links
|
|
1182
|
+
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}')`;
|
|
1183
|
+
const result = await this.querySurrealDB(query);
|
|
1184
|
+
const flowLinks = (result || []).map((r) => ({
|
|
1185
|
+
source: r.source,
|
|
1186
|
+
predicate: r.predicate,
|
|
1187
|
+
target: r.target
|
|
1188
|
+
}));
|
|
1339
1189
|
return SHACLFlow.fromLinks(flowLinks, flowUri);
|
|
1340
1190
|
}
|
|
1341
1191
|
/** Returns all the Subject classes defined in this perspectives SDNA
|
|
@@ -1347,25 +1197,22 @@ export class PerspectiveProxy {
|
|
|
1347
1197
|
// Query SHACL class links directly — no need for a separate GraphQL endpoint
|
|
1348
1198
|
const classLinks = await this.get(new LinkQuery({
|
|
1349
1199
|
predicate: "rdf://type",
|
|
1350
|
-
target: "ad4m://SubjectClass"
|
|
1200
|
+
target: "ad4m://SubjectClass"
|
|
1351
1201
|
}));
|
|
1352
1202
|
const classNames = classLinks
|
|
1353
|
-
.map(
|
|
1203
|
+
.map(l => {
|
|
1354
1204
|
const source = l.data.source;
|
|
1355
|
-
// Extract class name from URI like "recipe://
|
|
1356
|
-
const
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
const afterScheme = source.substring(sepIdx + 3);
|
|
1360
|
-
const lastPart = afterScheme.split("/").pop() || "";
|
|
1361
|
-
// Strip trailing "Shape" suffix if present
|
|
1362
|
-
return lastPart.endsWith("Shape") ? lastPart.slice(0, -5) : lastPart;
|
|
1205
|
+
// Extract class name from URI like "recipe://Recipe" or "flux://Channel"
|
|
1206
|
+
const parts = source.split("://");
|
|
1207
|
+
const lastPart = parts[parts.length - 1];
|
|
1208
|
+
return lastPart.split('/').pop() || '';
|
|
1363
1209
|
})
|
|
1364
|
-
.filter(
|
|
1210
|
+
.filter(name => name.length > 0);
|
|
1211
|
+
// Deduplicate
|
|
1365
1212
|
return [...new Set(classNames)];
|
|
1366
1213
|
}
|
|
1367
1214
|
catch (e) {
|
|
1368
|
-
console.warn(
|
|
1215
|
+
console.warn('subjectClasses: SHACL lookup failed:', e);
|
|
1369
1216
|
return [];
|
|
1370
1217
|
}
|
|
1371
1218
|
}
|
|
@@ -1399,22 +1246,21 @@ export class PerspectiveProxy {
|
|
|
1399
1246
|
let className;
|
|
1400
1247
|
if (typeof subjectClass === "string") {
|
|
1401
1248
|
className = subjectClass;
|
|
1402
|
-
await this.
|
|
1249
|
+
await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
|
|
1403
1250
|
className,
|
|
1404
|
-
initialValues
|
|
1251
|
+
initialValues
|
|
1405
1252
|
}), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
|
|
1406
1253
|
}
|
|
1407
1254
|
else {
|
|
1408
|
-
const
|
|
1409
|
-
const
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
throw new Error(`createSubject: could not resolve className from subject class object. Ensure the class is decorated with @Model.`);
|
|
1255
|
+
const obj = subjectClass;
|
|
1256
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1257
|
+
|| await this.findClassByProperties(obj);
|
|
1258
|
+
if (!resolvedClassName) {
|
|
1259
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1414
1260
|
}
|
|
1415
|
-
await this.
|
|
1416
|
-
className,
|
|
1417
|
-
initialValues
|
|
1261
|
+
await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").createSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({
|
|
1262
|
+
className: resolvedClassName,
|
|
1263
|
+
initialValues
|
|
1418
1264
|
}), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);
|
|
1419
1265
|
}
|
|
1420
1266
|
// Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed
|
|
@@ -1425,16 +1271,15 @@ export class PerspectiveProxy {
|
|
|
1425
1271
|
}
|
|
1426
1272
|
async getSubjectData(subjectClass, exprAddr) {
|
|
1427
1273
|
if (typeof subjectClass === "string") {
|
|
1428
|
-
return JSON.parse(await this.
|
|
1274
|
+
return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
|
|
1429
1275
|
}
|
|
1430
|
-
const
|
|
1431
|
-
const
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
throw new Error(`getSubjectData: could not resolve className from subject class object. Ensure the class is decorated with @Model.`);
|
|
1276
|
+
const obj = subjectClass;
|
|
1277
|
+
const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className
|
|
1278
|
+
|| await this.findClassByProperties(obj);
|
|
1279
|
+
if (!resolvedClassName) {
|
|
1280
|
+
throw new Error("Could not resolve subject class name from object. Use a decorated class or pass a className string.");
|
|
1436
1281
|
}
|
|
1437
|
-
return JSON.parse(await this.
|
|
1282
|
+
return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));
|
|
1438
1283
|
}
|
|
1439
1284
|
/**
|
|
1440
1285
|
* Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).
|
|
@@ -1494,7 +1339,7 @@ export class PerspectiveProxy {
|
|
|
1494
1339
|
* @param subjectClass Either a string with the name of the subject class, or an object
|
|
1495
1340
|
* with the properties of the subject class. In the latter case, the first subject class
|
|
1496
1341
|
* that matches the given properties will be used.
|
|
1497
|
-
|
|
1342
|
+
*/
|
|
1498
1343
|
async isSubjectInstance(expression, subjectClass) {
|
|
1499
1344
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
|
|
1500
1345
|
// Get metadata from SHACL links
|
|
@@ -1509,9 +1354,7 @@ export class PerspectiveProxy {
|
|
|
1509
1354
|
const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${escapedExpression}'`;
|
|
1510
1355
|
const result = await this.querySurrealDB(checkQuery);
|
|
1511
1356
|
const count = result[0]?.count ?? 0;
|
|
1512
|
-
const countValue = typeof count ===
|
|
1513
|
-
? count.Int
|
|
1514
|
-
: count;
|
|
1357
|
+
const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
|
|
1515
1358
|
return countValue > 0;
|
|
1516
1359
|
}
|
|
1517
1360
|
// Check if the expression has all required triples (predicate + optional exact target)
|
|
@@ -1534,9 +1377,7 @@ export class PerspectiveProxy {
|
|
|
1534
1377
|
}
|
|
1535
1378
|
const count = result[0]?.count ?? 0;
|
|
1536
1379
|
// Handle potential object response like {Int: 0}
|
|
1537
|
-
const countValue = typeof count ===
|
|
1538
|
-
? count.Int
|
|
1539
|
-
: count;
|
|
1380
|
+
const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
|
|
1540
1381
|
if (countValue === 0) {
|
|
1541
1382
|
return false;
|
|
1542
1383
|
}
|
|
@@ -1553,7 +1394,7 @@ export class PerspectiveProxy {
|
|
|
1553
1394
|
* that matches the given properties will be used.
|
|
1554
1395
|
*/
|
|
1555
1396
|
async getSubjectProxy(base, subjectClass) {
|
|
1556
|
-
if (!
|
|
1397
|
+
if (!await this.isSubjectInstance(base, subjectClass)) {
|
|
1557
1398
|
throw `Expression ${base} is not a subject instance of given class: ${JSON.stringify(subjectClass)}`;
|
|
1558
1399
|
}
|
|
1559
1400
|
let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
|
|
@@ -1562,135 +1403,56 @@ export class PerspectiveProxy {
|
|
|
1562
1403
|
return subject;
|
|
1563
1404
|
}
|
|
1564
1405
|
/**
|
|
1565
|
-
*
|
|
1566
|
-
*
|
|
1567
|
-
* Returns required predicates that define what makes something an instance,
|
|
1568
|
-
* plus a map of property/collection names to their predicates.
|
|
1569
|
-
*/
|
|
1570
|
-
/**
|
|
1571
|
-
* Gets subject class metadata from SHACL links (Prolog-free implementation).
|
|
1572
|
-
* Uses the link API directly instead of SurrealDB queries.
|
|
1406
|
+
* Gets subject class metadata from SHACL links using SHACLShape.fromLinks().
|
|
1407
|
+
* Retrieves the SHACL shape and extracts metadata for instance queries.
|
|
1573
1408
|
*/
|
|
1574
1409
|
async getSubjectClassMetadataFromSDNA(className) {
|
|
1575
1410
|
try {
|
|
1576
|
-
//
|
|
1577
|
-
const
|
|
1578
|
-
|
|
1579
|
-
source: nameMapping.toUrl(),
|
|
1580
|
-
predicate: "ad4m://shacl_shape_uri",
|
|
1581
|
-
}));
|
|
1582
|
-
if (shapeUriLinks.length === 0) {
|
|
1411
|
+
// Use getShacl() to retrieve the shape via SHACLShape.fromLinks()
|
|
1412
|
+
const shape = await this.getShacl(className);
|
|
1413
|
+
if (!shape) {
|
|
1583
1414
|
console.warn(`No SHACL metadata found for ${className}`);
|
|
1584
1415
|
return null;
|
|
1585
1416
|
}
|
|
1586
|
-
const shapeUri = shapeUriLinks[0].data.target;
|
|
1587
|
-
// Get the target class URI from the shape
|
|
1588
|
-
const targetClassLinks = await this.get(new LinkQuery({
|
|
1589
|
-
source: shapeUri,
|
|
1590
|
-
predicate: "sh://targetClass",
|
|
1591
|
-
}));
|
|
1592
|
-
if (targetClassLinks.length === 0) {
|
|
1593
|
-
console.warn(`No target class found for SHACL shape ${shapeUri}`);
|
|
1594
|
-
return null;
|
|
1595
|
-
}
|
|
1596
|
-
const classUri = targetClassLinks[0].data.target;
|
|
1597
1417
|
const requiredPredicates = [];
|
|
1598
1418
|
const requiredTriples = [];
|
|
1599
1419
|
const properties = new Map();
|
|
1600
|
-
const
|
|
1601
|
-
//
|
|
1602
|
-
const
|
|
1603
|
-
const
|
|
1604
|
-
|
|
1605
|
-
source: shapeUri,
|
|
1606
|
-
predicate: "sh://property",
|
|
1607
|
-
}));
|
|
1608
|
-
for (const propLink of propertyLinks) {
|
|
1609
|
-
const propUri = propLink.data.target;
|
|
1610
|
-
// Extract property name from URI (e.g., "todo://Todo.title" -> "title")
|
|
1611
|
-
const propNameMatch = propUri.match(/\.([^.]+)$/);
|
|
1612
|
-
if (!propNameMatch)
|
|
1420
|
+
const relations = new Map();
|
|
1421
|
+
// Build property/relation maps and track writable predicates from shape properties
|
|
1422
|
+
const writablePredicates = new Set();
|
|
1423
|
+
for (const prop of shape.properties) {
|
|
1424
|
+
if (!prop.path || !prop.name)
|
|
1613
1425
|
continue;
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
const propDetailLinks = await this.get(new LinkQuery({
|
|
1617
|
-
source: propUri,
|
|
1618
|
-
}));
|
|
1619
|
-
let predicate;
|
|
1620
|
-
let resolveLanguage;
|
|
1621
|
-
let isCollection = false;
|
|
1622
|
-
let isReadOnly = false;
|
|
1623
|
-
for (const detail of propDetailLinks) {
|
|
1624
|
-
if (detail.data.predicate === "sh://path") {
|
|
1625
|
-
predicate = detail.data.target;
|
|
1626
|
-
}
|
|
1627
|
-
else if (detail.data.predicate === "ad4m://resolveLanguage") {
|
|
1628
|
-
resolveLanguage = detail.data.target?.replace("literal://string:", "");
|
|
1629
|
-
}
|
|
1630
|
-
else if (detail.data.predicate === "rdf://type" &&
|
|
1631
|
-
detail.data.target === "ad4m://Collection") {
|
|
1632
|
-
isCollection = true;
|
|
1633
|
-
}
|
|
1634
|
-
else if (detail.data.predicate === "ad4m://readOnly" &&
|
|
1635
|
-
detail.data.target === "literal://true") {
|
|
1636
|
-
isReadOnly = true;
|
|
1637
|
-
}
|
|
1426
|
+
if (prop.writable) {
|
|
1427
|
+
writablePredicates.add(prop.path);
|
|
1638
1428
|
}
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
properties.set(propName, { predicate, resolveLanguage });
|
|
1649
|
-
}
|
|
1429
|
+
const isRelation = prop.adder && prop.adder.length > 0;
|
|
1430
|
+
if (isRelation) {
|
|
1431
|
+
relations.set(prop.name, { predicate: prop.path });
|
|
1432
|
+
}
|
|
1433
|
+
else {
|
|
1434
|
+
properties.set(prop.name, {
|
|
1435
|
+
predicate: prop.path,
|
|
1436
|
+
resolveLanguage: prop.resolveLanguage
|
|
1437
|
+
});
|
|
1650
1438
|
}
|
|
1651
1439
|
}
|
|
1652
|
-
//
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
const actionsJson = constructorTarget.substring("literal://string:".length);
|
|
1664
|
-
const actions = JSON.parse(actionsJson);
|
|
1665
|
-
for (const action of actions) {
|
|
1666
|
-
if (action.predicate) {
|
|
1667
|
-
requiredPredicates.push(action.predicate);
|
|
1668
|
-
// Flags: fixed target value + in propertyPredicates + IS readOnly -> require exact match
|
|
1669
|
-
// Properties with initial: has target + in propertyPredicates + NOT readOnly -> any value OK
|
|
1670
|
-
// Other: not in propertyPredicates -> require exact match if has target
|
|
1671
|
-
const isWritableProperty = !readOnlyPredicates.has(action.predicate);
|
|
1672
|
-
if (action.target &&
|
|
1673
|
-
action.target !== "value" &&
|
|
1674
|
-
!isWritableProperty) {
|
|
1675
|
-
// Either a flag (readOnly) or not a property at all - require exact target
|
|
1676
|
-
requiredTriples.push({
|
|
1677
|
-
predicate: action.predicate,
|
|
1678
|
-
target: action.target,
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
else {
|
|
1682
|
-
// Non-readOnly property with initial value - just require predicate exists
|
|
1683
|
-
requiredTriples.push({ predicate: action.predicate });
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1440
|
+
// Extract required predicates/triples from constructor actions
|
|
1441
|
+
if (shape.constructor_actions) {
|
|
1442
|
+
for (const action of shape.constructor_actions) {
|
|
1443
|
+
if (action.predicate) {
|
|
1444
|
+
requiredPredicates.push(action.predicate);
|
|
1445
|
+
const isWritableProperty = writablePredicates.has(action.predicate);
|
|
1446
|
+
if (action.target && action.target !== 'value' && !isWritableProperty) {
|
|
1447
|
+
requiredTriples.push({ predicate: action.predicate, target: action.target });
|
|
1448
|
+
}
|
|
1449
|
+
else {
|
|
1450
|
+
requiredTriples.push({ predicate: action.predicate });
|
|
1686
1451
|
}
|
|
1687
|
-
}
|
|
1688
|
-
catch (e) {
|
|
1689
|
-
console.warn(`Failed to parse constructor actions for ${className}:`, e);
|
|
1690
1452
|
}
|
|
1691
1453
|
}
|
|
1692
1454
|
}
|
|
1693
|
-
return { requiredPredicates, requiredTriples, properties,
|
|
1455
|
+
return { requiredPredicates, requiredTriples, properties, relations };
|
|
1694
1456
|
}
|
|
1695
1457
|
catch (e) {
|
|
1696
1458
|
console.error(`Error getting SHACL metadata for ${className}:`, e);
|
|
@@ -1706,8 +1468,7 @@ export class PerspectiveProxy {
|
|
|
1706
1468
|
return `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
|
|
1707
1469
|
}
|
|
1708
1470
|
// Generate WHERE conditions for each required triple (predicate + optional exact target)
|
|
1709
|
-
const whereConditions = metadata.requiredTriples
|
|
1710
|
-
.map((triple) => {
|
|
1471
|
+
const whereConditions = metadata.requiredTriples.map(triple => {
|
|
1711
1472
|
const escapedPredicate = escapeSurrealString(triple.predicate);
|
|
1712
1473
|
if (triple.target) {
|
|
1713
1474
|
// Flag: must match both predicate AND exact target value
|
|
@@ -1718,8 +1479,7 @@ export class PerspectiveProxy {
|
|
|
1718
1479
|
// Property: just check predicate exists
|
|
1719
1480
|
return `count(->link[WHERE predicate = '${escapedPredicate}']) > 0`;
|
|
1720
1481
|
}
|
|
1721
|
-
})
|
|
1722
|
-
.join(" AND ");
|
|
1482
|
+
}).join(' AND ');
|
|
1723
1483
|
return `SELECT uri AS base FROM node WHERE ${whereConditions}`;
|
|
1724
1484
|
}
|
|
1725
1485
|
/**
|
|
@@ -1761,45 +1521,42 @@ export class PerspectiveProxy {
|
|
|
1761
1521
|
return value;
|
|
1762
1522
|
}
|
|
1763
1523
|
/**
|
|
1764
|
-
* Gets
|
|
1524
|
+
* Gets relation values using SurrealDB when Prolog fails.
|
|
1765
1525
|
* This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
|
|
1766
1526
|
* Note: This is used by Subject.ts (legacy pattern). Ad4mModel.ts uses getModelMetadata() instead.
|
|
1767
1527
|
*/
|
|
1768
|
-
async
|
|
1528
|
+
async getRelationValuesViaSurreal(baseExpression, className, relationName) {
|
|
1769
1529
|
const metadata = await this.getSubjectClassMetadataFromSDNA(className);
|
|
1770
1530
|
if (!metadata) {
|
|
1771
1531
|
return [];
|
|
1772
1532
|
}
|
|
1773
|
-
const
|
|
1774
|
-
if (!
|
|
1533
|
+
const relMeta = metadata.relations.get(relationName);
|
|
1534
|
+
if (!relMeta) {
|
|
1775
1535
|
return [];
|
|
1776
1536
|
}
|
|
1777
1537
|
const escapedBaseExpression = escapeSurrealString(baseExpression);
|
|
1778
|
-
const escapedPredicate = escapeSurrealString(
|
|
1538
|
+
const escapedPredicate = escapeSurrealString(relMeta.predicate);
|
|
1779
1539
|
const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${escapedBaseExpression}' AND predicate = '${escapedPredicate}' ORDER BY timestamp ASC`;
|
|
1780
1540
|
const result = await this.querySurrealDB(query);
|
|
1781
1541
|
if (!result || result.length === 0) {
|
|
1782
1542
|
return [];
|
|
1783
1543
|
}
|
|
1784
|
-
let values = result.map(
|
|
1544
|
+
let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
|
|
1785
1545
|
// Apply condition filtering if present
|
|
1786
|
-
if (
|
|
1546
|
+
if (relMeta.condition && values.length > 0) {
|
|
1787
1547
|
try {
|
|
1788
1548
|
const filteredValues = [];
|
|
1789
1549
|
for (const value of values) {
|
|
1790
|
-
let condition =
|
|
1550
|
+
let condition = relMeta.condition
|
|
1791
1551
|
.replace(/\$perspective/g, `'${this.uuid}'`)
|
|
1792
1552
|
.replace(/\$base/g, `'${baseExpression}'`)
|
|
1793
1553
|
.replace(/Target/g, `'${value.replace(/'/g, "\\'")}'`);
|
|
1794
1554
|
// If condition starts with WHERE, wrap in array length check
|
|
1795
|
-
if (condition.trim().startsWith(
|
|
1555
|
+
if (condition.trim().startsWith('WHERE')) {
|
|
1796
1556
|
condition = `array::len(SELECT * FROM link ${condition}) > 0`;
|
|
1797
1557
|
}
|
|
1798
1558
|
const filterResult = await this.querySurrealDB(`RETURN ${condition}`);
|
|
1799
|
-
const isTrue = filterResult === true ||
|
|
1800
|
-
(Array.isArray(filterResult) &&
|
|
1801
|
-
filterResult.length > 0 &&
|
|
1802
|
-
filterResult[0] === true);
|
|
1559
|
+
const isTrue = filterResult === true || (Array.isArray(filterResult) && filterResult.length > 0 && filterResult[0] === true);
|
|
1803
1560
|
if (isTrue) {
|
|
1804
1561
|
filteredValues.push(value);
|
|
1805
1562
|
}
|
|
@@ -1807,22 +1564,22 @@ export class PerspectiveProxy {
|
|
|
1807
1564
|
values = filteredValues;
|
|
1808
1565
|
}
|
|
1809
1566
|
catch (error) {
|
|
1810
|
-
console.warn(`Failed to apply condition filter for ${
|
|
1567
|
+
console.warn(`Failed to apply condition filter for ${relationName}:`, error);
|
|
1811
1568
|
}
|
|
1812
1569
|
}
|
|
1813
1570
|
// Apply instance filter if present - batch-check all values at once
|
|
1814
|
-
if (
|
|
1571
|
+
if (relMeta.instanceFilter) {
|
|
1815
1572
|
try {
|
|
1816
|
-
const filterMetadata = await this.getSubjectClassMetadataFromSDNA(
|
|
1573
|
+
const filterMetadata = await this.getSubjectClassMetadataFromSDNA(relMeta.instanceFilter);
|
|
1817
1574
|
if (!filterMetadata) {
|
|
1818
1575
|
// Fallback to sequential checks if metadata isn't available
|
|
1819
|
-
return this.filterInstancesSequential(values,
|
|
1576
|
+
return this.filterInstancesSequential(values, relMeta.instanceFilter);
|
|
1820
1577
|
}
|
|
1821
1578
|
return await this.batchCheckSubjectInstances(values, filterMetadata);
|
|
1822
1579
|
}
|
|
1823
1580
|
catch (err) {
|
|
1824
1581
|
// Fallback to sequential checks on error
|
|
1825
|
-
return this.filterInstancesSequential(values,
|
|
1582
|
+
return this.filterInstancesSequential(values, relMeta.instanceFilter);
|
|
1826
1583
|
}
|
|
1827
1584
|
}
|
|
1828
1585
|
return values;
|
|
@@ -1837,19 +1594,15 @@ export class PerspectiveProxy {
|
|
|
1837
1594
|
}
|
|
1838
1595
|
// If no required triples, check which expressions have any links
|
|
1839
1596
|
if (metadata.requiredTriples.length === 0) {
|
|
1840
|
-
const escapedExpressions = expressions
|
|
1841
|
-
.map((e) => `'${escapeSurrealString(e)}'`)
|
|
1842
|
-
.join(", ");
|
|
1597
|
+
const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
|
|
1843
1598
|
const checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] GROUP BY in.uri HAVING count() > 0`;
|
|
1844
1599
|
const result = await this.querySurrealDB(checkQuery);
|
|
1845
|
-
return result.map(
|
|
1600
|
+
return result.map(r => r.uri);
|
|
1846
1601
|
}
|
|
1847
1602
|
// For each required triple, build a query that finds matching expressions
|
|
1848
1603
|
const validExpressionSets = [];
|
|
1849
1604
|
for (const triple of metadata.requiredTriples) {
|
|
1850
|
-
const escapedExpressions = expressions
|
|
1851
|
-
.map((e) => `'${escapeSurrealString(e)}'`)
|
|
1852
|
-
.join(", ");
|
|
1605
|
+
const escapedExpressions = expressions.map(e => `'${escapeSurrealString(e)}'`).join(', ');
|
|
1853
1606
|
const escapedPredicate = escapeSurrealString(triple.predicate);
|
|
1854
1607
|
let checkQuery;
|
|
1855
1608
|
if (triple.target) {
|
|
@@ -1864,15 +1617,15 @@ export class PerspectiveProxy {
|
|
|
1864
1617
|
checkQuery = `SELECT in.uri AS uri FROM link WHERE in.uri IN [${escapedExpressions}] AND predicate = '${escapedPredicate}'`;
|
|
1865
1618
|
}
|
|
1866
1619
|
const result = await this.querySurrealDB(checkQuery);
|
|
1867
|
-
validExpressionSets.push(new Set(result.map(
|
|
1620
|
+
validExpressionSets.push(new Set(result.map(r => r.uri)));
|
|
1868
1621
|
}
|
|
1869
1622
|
// Find intersection: expressions that passed ALL required triple checks
|
|
1870
1623
|
if (validExpressionSets.length === 0) {
|
|
1871
1624
|
return expressions;
|
|
1872
1625
|
}
|
|
1873
1626
|
const firstSet = validExpressionSets[0];
|
|
1874
|
-
const validExpressions = expressions.filter(
|
|
1875
|
-
return validExpressionSets.every(
|
|
1627
|
+
const validExpressions = expressions.filter(expr => {
|
|
1628
|
+
return validExpressionSets.every(set => set.has(expr));
|
|
1876
1629
|
});
|
|
1877
1630
|
return validExpressions;
|
|
1878
1631
|
}
|
|
@@ -1989,211 +1742,96 @@ export class PerspectiveProxy {
|
|
|
1989
1742
|
}
|
|
1990
1743
|
return instances;
|
|
1991
1744
|
}
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
// Collect all string properties of the object in a list
|
|
1997
|
-
let properties = [];
|
|
1998
|
-
// Collect all collections of the object in a list
|
|
1999
|
-
let collections = [];
|
|
2000
|
-
// Collect all string properties of the object in a list
|
|
2001
|
-
const _protoProps = getPropertiesMetadata(Object.getPrototypeOf(obj)?.constructor);
|
|
2002
|
-
if (Object.keys(_protoProps).length > 0) {
|
|
2003
|
-
Object.keys(_protoProps).forEach((p) => properties.push(p));
|
|
2004
|
-
}
|
|
2005
|
-
else {
|
|
2006
|
-
properties.push(...Object.keys(obj).filter((key) => !Array.isArray(obj[key])));
|
|
2007
|
-
}
|
|
2008
|
-
// Collect all collections of the object in a list
|
|
2009
|
-
const _protoCols = getRelationsMetadata(Object.getPrototypeOf(obj)?.constructor);
|
|
2010
|
-
if (Object.keys(_protoCols).length > 0) {
|
|
2011
|
-
Object.keys(_protoCols)
|
|
2012
|
-
.filter((key) => key !== "isSubjectInstance")
|
|
2013
|
-
.forEach((c) => {
|
|
2014
|
-
if (!collections.includes(c)) {
|
|
2015
|
-
collections.push(c);
|
|
2016
|
-
}
|
|
2017
|
-
});
|
|
2018
|
-
}
|
|
2019
|
-
else {
|
|
2020
|
-
collections.push(...Object.keys(obj)
|
|
2021
|
-
.filter((key) => Array.isArray(obj[key]))
|
|
2022
|
-
.filter((key) => key !== "isSubjectInstance"));
|
|
2023
|
-
}
|
|
2024
|
-
// Helper: distinguish collection setters (setComments, setLocations, …) from
|
|
2025
|
-
// plain property setters (setName, setState, …) using @HasMany/__collections metadata
|
|
2026
|
-
// rather than the old "setCollection" string prefix.
|
|
2027
|
-
const _collectionsMetadata = getRelationsMetadata(Object.getPrototypeOf(obj)?.constructor ?? obj.constructor);
|
|
2028
|
-
const isRelationSetter = (key) => {
|
|
2029
|
-
if (!key.startsWith("set") || key.length <= 3)
|
|
2030
|
-
return false;
|
|
2031
|
-
const suffix = key.substring(3);
|
|
2032
|
-
const relationKey = suffix.charAt(0).toLowerCase() + suffix.slice(1);
|
|
2033
|
-
return relationKey in _collectionsMetadata;
|
|
2034
|
-
};
|
|
2035
|
-
// Collect all set functions of the object in a list
|
|
2036
|
-
let setFunctions = Object.getOwnPropertyNames(obj).filter((key) => typeof obj[key] === "function" &&
|
|
2037
|
-
key.startsWith("set") &&
|
|
2038
|
-
!isRelationSetter(key));
|
|
2039
|
-
// Add all set functions of the object's prototype to that list
|
|
2040
|
-
setFunctions = setFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
|
|
2041
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
2042
|
-
return (descriptor &&
|
|
2043
|
-
typeof descriptor.value === "function" &&
|
|
2044
|
-
key.startsWith("set") &&
|
|
2045
|
-
!isRelationSetter(key));
|
|
2046
|
-
}));
|
|
2047
|
-
// Collect all add functions of the object in a list
|
|
2048
|
-
let addFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
|
|
2049
|
-
typeof obj[key] === "function" &&
|
|
2050
|
-
key.startsWith("add"));
|
|
2051
|
-
// Add all add functions of the object's prototype to that list
|
|
2052
|
-
addFunctions = addFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
|
|
2053
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
2054
|
-
return (descriptor &&
|
|
2055
|
-
typeof descriptor.value === "function" &&
|
|
2056
|
-
key.startsWith("add"));
|
|
2057
|
-
}));
|
|
2058
|
-
// Collect all remove functions of the object in a list
|
|
2059
|
-
let removeFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
|
|
2060
|
-
typeof obj[key] === "function" &&
|
|
2061
|
-
key.startsWith("remove"));
|
|
2062
|
-
// Add all remove functions of the object's prototype to that list
|
|
2063
|
-
removeFunctions = removeFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
|
|
2064
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
2065
|
-
return (descriptor &&
|
|
2066
|
-
typeof descriptor.value === "function" &&
|
|
2067
|
-
key.startsWith("remove"));
|
|
2068
|
-
}));
|
|
2069
|
-
// Collect all collection setter functions of the object in a list
|
|
2070
|
-
let setCollectionFunctions = Object.getOwnPropertyNames(obj).filter((key) => Object.prototype.hasOwnProperty.call(obj, key) &&
|
|
2071
|
-
typeof obj[key] === "function" &&
|
|
2072
|
-
key.startsWith("set") &&
|
|
2073
|
-
isRelationSetter(key));
|
|
2074
|
-
// Add all collection setter functions from the object's prototype to that list
|
|
2075
|
-
setCollectionFunctions = setCollectionFunctions.concat(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)).filter((key) => {
|
|
2076
|
-
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), key);
|
|
2077
|
-
return (descriptor &&
|
|
2078
|
-
typeof descriptor.value === "function" &&
|
|
2079
|
-
key.startsWith("set") &&
|
|
2080
|
-
isRelationSetter(key));
|
|
2081
|
-
}));
|
|
2082
|
-
// Construct query to find all subject classes that have the given properties and collections
|
|
2083
|
-
let query = `subject_class(Class, C)`;
|
|
2084
|
-
for (let property of properties) {
|
|
2085
|
-
query += `, property(C, "${property}")`;
|
|
2086
|
-
}
|
|
2087
|
-
for (let collection of collections) {
|
|
2088
|
-
query += `, collection(C, "${collection}")`;
|
|
2089
|
-
}
|
|
2090
|
-
for (let setFunction of setFunctions) {
|
|
2091
|
-
// e.g. "setState" -> "state"
|
|
2092
|
-
let property = setFunction.substring(3);
|
|
2093
|
-
property = property.charAt(0).toLowerCase() + property.slice(1);
|
|
2094
|
-
query += `, property_setter(C, "${property}", _)`;
|
|
2095
|
-
}
|
|
2096
|
-
for (let addFunction of addFunctions) {
|
|
2097
|
-
query += `, collection_adder(C, "${collectionAdderToName(addFunction)}", _)`;
|
|
2098
|
-
}
|
|
2099
|
-
for (let removeFunction of removeFunctions) {
|
|
2100
|
-
query += `, collection_remover(C, "${collectionRemoverToName(removeFunction)}", _)`;
|
|
2101
|
-
}
|
|
2102
|
-
for (let setCollectionFunction of setCollectionFunctions) {
|
|
2103
|
-
query += `, collection_setter(C, "${collectionSetterToName(setCollectionFunction)}", _)`;
|
|
2104
|
-
}
|
|
2105
|
-
query += ".";
|
|
2106
|
-
result = query;
|
|
2107
|
-
})(obj);
|
|
2108
|
-
return result;
|
|
2109
|
-
}
|
|
2110
|
-
/** Finds a single subject class whose SHACL shape matches all properties
|
|
2111
|
-
* and collections present on `obj`. Returns `null` when no match is found.
|
|
1745
|
+
/**
|
|
1746
|
+
* Find a subject class by matching an object's properties/relations against SHACL shapes.
|
|
1747
|
+
* Queries SHACL links client-side to find a class whose properties contain all required ones.
|
|
1748
|
+
* @returns The matching class name, or null if no match found.
|
|
2112
1749
|
*/
|
|
2113
1750
|
async findClassByProperties(obj) {
|
|
2114
|
-
// Extract
|
|
1751
|
+
// Extract properties and relations from the object
|
|
2115
1752
|
let properties = [];
|
|
2116
|
-
let
|
|
1753
|
+
let relations = [];
|
|
2117
1754
|
const proto = Object.getPrototypeOf(obj);
|
|
2118
|
-
|
|
2119
|
-
|
|
1755
|
+
const ctor = proto?.constructor;
|
|
1756
|
+
const registryProps = ctor ? getPropertiesMetadata(ctor) : {};
|
|
1757
|
+
if (Object.keys(registryProps).length > 0) {
|
|
1758
|
+
properties = Object.keys(registryProps);
|
|
2120
1759
|
}
|
|
2121
1760
|
else {
|
|
2122
|
-
properties = Object.keys(obj).filter(
|
|
1761
|
+
properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));
|
|
2123
1762
|
}
|
|
2124
|
-
|
|
2125
|
-
|
|
1763
|
+
const registryRelations = ctor
|
|
1764
|
+
? Object.fromEntries(Object.entries(getRelationsMetadata(ctor)).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'))
|
|
1765
|
+
: {};
|
|
1766
|
+
if (Object.keys(registryRelations).length > 0) {
|
|
1767
|
+
relations = Object.keys(registryRelations).filter(key => key !== 'isSubjectInstance');
|
|
2126
1768
|
}
|
|
2127
1769
|
else {
|
|
2128
|
-
|
|
1770
|
+
relations = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');
|
|
2129
1771
|
}
|
|
2130
|
-
if (properties.length === 0 &&
|
|
1772
|
+
if (properties.length === 0 && relations.length === 0) {
|
|
2131
1773
|
return null;
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
1774
|
+
}
|
|
1775
|
+
// Single SurrealDB query to find all classes and their properties/relations
|
|
1776
|
+
const query = `SELECT
|
|
1777
|
+
in.uri AS shape_source,
|
|
1778
|
+
predicate,
|
|
1779
|
+
out.uri AS target
|
|
1780
|
+
FROM link
|
|
1781
|
+
WHERE predicate IN ['rdf://type', 'sh://property', 'sh://collection']`;
|
|
2139
1782
|
const results = await this.querySurrealDB(query);
|
|
2140
1783
|
if (!results || results.length === 0)
|
|
2141
1784
|
return null;
|
|
2142
|
-
// Build className -> {
|
|
1785
|
+
// Build a map of className -> { properties, relations }
|
|
2143
1786
|
const classShapes = new Map();
|
|
1787
|
+
// First pass: find all subject classes
|
|
2144
1788
|
for (const r of results) {
|
|
2145
|
-
if (r.predicate ===
|
|
1789
|
+
if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {
|
|
2146
1790
|
const source = r.shape_source;
|
|
2147
|
-
const sepIdx = source.indexOf(
|
|
1791
|
+
const sepIdx = source.indexOf('://');
|
|
2148
1792
|
if (sepIdx < 0)
|
|
2149
1793
|
continue;
|
|
2150
|
-
|
|
2151
|
-
.substring(sepIdx + 3)
|
|
2152
|
-
.split("/")
|
|
2153
|
-
.pop();
|
|
1794
|
+
const className = source.substring(sepIdx + 3).split('/').pop();
|
|
2154
1795
|
if (!className)
|
|
2155
1796
|
continue;
|
|
2156
|
-
|
|
2157
|
-
className = className.slice(0, -5);
|
|
2158
|
-
classShapes.set(className, {
|
|
2159
|
-
shapeUri: source,
|
|
2160
|
-
properties: [],
|
|
2161
|
-
collections: [],
|
|
2162
|
-
});
|
|
1797
|
+
classShapes.set(className, { shapeUri: source, properties: [], relations: [] });
|
|
2163
1798
|
}
|
|
2164
1799
|
}
|
|
1800
|
+
// Second pass: collect properties and relations for each class
|
|
2165
1801
|
for (const r of results) {
|
|
2166
|
-
if (r.predicate ===
|
|
2167
|
-
|
|
1802
|
+
if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {
|
|
1803
|
+
// Match shape source to class (e.g., "recipe://RecipeShape" -> "Recipe")
|
|
2168
1804
|
for (const [className, shape] of classShapes) {
|
|
2169
1805
|
if (r.shape_source.endsWith(`${className}Shape`)) {
|
|
2170
|
-
const dotIdx = r.target.lastIndexOf(
|
|
1806
|
+
const dotIdx = r.target.lastIndexOf('.');
|
|
2171
1807
|
if (dotIdx < 0)
|
|
2172
1808
|
continue;
|
|
2173
1809
|
const name = r.target.substring(dotIdx + 1);
|
|
2174
|
-
if (r.predicate ===
|
|
1810
|
+
if (r.predicate === 'sh://property') {
|
|
2175
1811
|
shape.properties.push(name);
|
|
2176
1812
|
}
|
|
2177
1813
|
else {
|
|
2178
|
-
shape.
|
|
1814
|
+
shape.relations.push(name);
|
|
2179
1815
|
}
|
|
2180
1816
|
}
|
|
2181
1817
|
}
|
|
2182
1818
|
}
|
|
2183
1819
|
}
|
|
1820
|
+
// Find a class that has all required properties and relations
|
|
2184
1821
|
for (const [className, shape] of classShapes) {
|
|
2185
|
-
const hasAllProps = properties.every(
|
|
2186
|
-
const
|
|
2187
|
-
if (hasAllProps &&
|
|
1822
|
+
const hasAllProps = properties.every(p => shape.properties.includes(p));
|
|
1823
|
+
const hasAllRels = relations.every(c => shape.relations.includes(c));
|
|
1824
|
+
if (hasAllProps && hasAllRels) {
|
|
2188
1825
|
return className;
|
|
1826
|
+
}
|
|
2189
1827
|
}
|
|
2190
1828
|
return null;
|
|
2191
1829
|
}
|
|
2192
1830
|
/** Returns all subject classes that match the given template object.
|
|
2193
1831
|
* This function looks at the properties of the template object and
|
|
2194
|
-
* its setters and
|
|
1832
|
+
* its setters and relations to create a Prolog query that finds
|
|
2195
1833
|
* all subject classes that would be converted to a proxy object
|
|
2196
|
-
* with exactly the same properties and
|
|
1834
|
+
* with exactly the same properties and relations.
|
|
2197
1835
|
*
|
|
2198
1836
|
* Since there could be multiple subject classes that match the given
|
|
2199
1837
|
* criteria, this function returns a list of class names.
|
|
@@ -2201,21 +1839,16 @@ export class PerspectiveProxy {
|
|
|
2201
1839
|
* @param obj The template object
|
|
2202
1840
|
*/
|
|
2203
1841
|
async subjectClassesByTemplate(obj) {
|
|
2204
|
-
//
|
|
1842
|
+
// className lookup first: the @Model decorator sets a precise className on the prototype,
|
|
1843
|
+
// so this is always more specific than property-set matching.
|
|
1844
|
+
// Property matching alone has a superset-ambiguity problem: if DerivedModel adds
|
|
1845
|
+
// properties to BaseModel, then DerivedModel's shape is a superset of BaseModel's
|
|
1846
|
+
// property list, so findClassByProperties could wrongly return DerivedModel for a
|
|
1847
|
+
// BaseModel instance (causing the derived SDNA constructor to fire and inject extra
|
|
1848
|
+
// links into what should be a plain base instance).
|
|
2205
1849
|
try {
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
return [match];
|
|
2209
|
-
}
|
|
2210
|
-
catch (e) {
|
|
2211
|
-
console.warn("subjectClassesByTemplate: property matching failed:", e);
|
|
2212
|
-
}
|
|
2213
|
-
// Fall back to className lookup against live SHACL links
|
|
2214
|
-
try {
|
|
2215
|
-
const o = obj;
|
|
2216
|
-
const className = o.className ||
|
|
2217
|
-
o.constructor?.className ||
|
|
2218
|
-
o.constructor?.prototype?.className;
|
|
1850
|
+
// @ts-ignore - className is added dynamically by decorators
|
|
1851
|
+
const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;
|
|
2219
1852
|
if (className) {
|
|
2220
1853
|
const existingClasses = await this.subjectClasses();
|
|
2221
1854
|
if (existingClasses.includes(className)) {
|
|
@@ -2224,7 +1857,17 @@ export class PerspectiveProxy {
|
|
|
2224
1857
|
}
|
|
2225
1858
|
}
|
|
2226
1859
|
catch (e) {
|
|
2227
|
-
console.warn(
|
|
1860
|
+
console.warn('subjectClassesByTemplate: className lookup failed:', e);
|
|
1861
|
+
}
|
|
1862
|
+
// Fall back to SHACL-based property matching for undecorated / dynamic objects
|
|
1863
|
+
try {
|
|
1864
|
+
const match = await this.findClassByProperties(obj);
|
|
1865
|
+
if (match) {
|
|
1866
|
+
return [match];
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
catch (e) {
|
|
1870
|
+
console.warn('subjectClassesByTemplate: property matching failed:', e);
|
|
2228
1871
|
}
|
|
2229
1872
|
return [];
|
|
2230
1873
|
}
|
|
@@ -2240,37 +1883,18 @@ export class PerspectiveProxy {
|
|
|
2240
1883
|
// Note: Duplicate checking is handled on the Rust side in add_sdna
|
|
2241
1884
|
// Generate SHACL SDNA (Prolog-free)
|
|
2242
1885
|
if (!jsClass.generateSHACL) {
|
|
2243
|
-
throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @
|
|
1886
|
+
throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);
|
|
2244
1887
|
}
|
|
2245
1888
|
// Get SHACL shape (W3C standard + AD4M action definitions)
|
|
2246
1889
|
const { shape } = jsClass.generateSHACL();
|
|
2247
|
-
// Serialize SHACL shape to JSON for Rust backend
|
|
2248
|
-
const shaclJson = JSON.stringify(
|
|
2249
|
-
target_class: shape.targetClass,
|
|
2250
|
-
constructor_actions: shape.constructor_actions,
|
|
2251
|
-
destructor_actions: shape.destructor_actions,
|
|
2252
|
-
properties: shape.properties.map((p) => ({
|
|
2253
|
-
path: p.path,
|
|
2254
|
-
name: p.name,
|
|
2255
|
-
datatype: p.datatype,
|
|
2256
|
-
min_count: p.minCount,
|
|
2257
|
-
max_count: p.maxCount,
|
|
2258
|
-
read_only: p.readOnly,
|
|
2259
|
-
local: p.local,
|
|
2260
|
-
resolve_language: p.resolveLanguage,
|
|
2261
|
-
node_kind: p.nodeKind,
|
|
2262
|
-
collection: p.collection,
|
|
2263
|
-
setter: p.setter,
|
|
2264
|
-
adder: p.adder,
|
|
2265
|
-
remover: p.remover,
|
|
2266
|
-
})),
|
|
2267
|
-
});
|
|
1890
|
+
// Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()
|
|
1891
|
+
const shaclJson = JSON.stringify(shape.toJSON());
|
|
2268
1892
|
// Pass SHACL JSON to backend (Prolog-free)
|
|
2269
1893
|
// Backend stores SHACL links directly
|
|
2270
|
-
await this.addSdna(className,
|
|
1894
|
+
await this.addSdna(className, '', 'subject_class', shaclJson);
|
|
2271
1895
|
}
|
|
2272
1896
|
getNeighbourhoodProxy() {
|
|
2273
|
-
return this.
|
|
1897
|
+
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getNeighbourhoodProxy(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
|
|
2274
1898
|
}
|
|
2275
1899
|
/**
|
|
2276
1900
|
* Returns a proxy object for working with AI capabilities.
|
|
@@ -2287,7 +1911,7 @@ export class PerspectiveProxy {
|
|
|
2287
1911
|
* ```
|
|
2288
1912
|
*/
|
|
2289
1913
|
get ai() {
|
|
2290
|
-
return this.
|
|
1914
|
+
return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").aiClient;
|
|
2291
1915
|
}
|
|
2292
1916
|
/**
|
|
2293
1917
|
* Creates a subscription for a Prolog query that updates in real-time.
|
|
@@ -2329,7 +1953,35 @@ export class PerspectiveProxy {
|
|
|
2329
1953
|
* ```
|
|
2330
1954
|
*/
|
|
2331
1955
|
async subscribeInfer(query) {
|
|
2332
|
-
const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, this
|
|
1956
|
+
const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
|
|
1957
|
+
// Start the subscription on the Rust side first to get the real subscription ID
|
|
1958
|
+
await subscriptionProxy.subscribe();
|
|
1959
|
+
// Wait for the initial result
|
|
1960
|
+
await subscriptionProxy.initialized;
|
|
1961
|
+
return subscriptionProxy;
|
|
1962
|
+
}
|
|
1963
|
+
/**
|
|
1964
|
+
* Creates a subscription for a SurrealQL query that updates in real-time.
|
|
1965
|
+
*
|
|
1966
|
+
* This method:
|
|
1967
|
+
* 1. Creates the subscription on the Rust side
|
|
1968
|
+
* 2. Sets up the subscription callback
|
|
1969
|
+
* 3. Waits for the initial result to come through the subscription channel
|
|
1970
|
+
* 4. Returns a fully initialized QuerySubscriptionProxy
|
|
1971
|
+
*
|
|
1972
|
+
* The returned subscription is guaranteed to be ready to receive updates,
|
|
1973
|
+
* as this method waits for the initialization process to complete.
|
|
1974
|
+
*
|
|
1975
|
+
* The subscription will be automatically cleaned up on both frontend and backend
|
|
1976
|
+
* when dispose() is called. Make sure to call dispose() when you're done to
|
|
1977
|
+
* prevent memory leaks and ensure proper cleanup of resources.
|
|
1978
|
+
*
|
|
1979
|
+
* @param query - SurrealQL query string
|
|
1980
|
+
* @returns Initialized QuerySubscriptionProxy instance
|
|
1981
|
+
*/
|
|
1982
|
+
async subscribeSurrealDB(query) {
|
|
1983
|
+
const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
|
|
1984
|
+
subscriptionProxy.isSurrealDB = true;
|
|
2333
1985
|
// Start the subscription on the Rust side first to get the real subscription ID
|
|
2334
1986
|
await subscriptionProxy.subscribe();
|
|
2335
1987
|
// Wait for the initial result
|
|
@@ -2337,3 +1989,4 @@ export class PerspectiveProxy {
|
|
|
2337
1989
|
return subscriptionProxy;
|
|
2338
1990
|
}
|
|
2339
1991
|
}
|
|
1992
|
+
_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap();
|