@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -1,20 +1,21 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ 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");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
1
6
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
7
  if (kind === "m") throw new TypeError("Private method is not writable");
3
8
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
9
  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
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
11
  };
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_reconnectUnsub, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_generation, _QuerySubscriptionProxy_deliverResult, _QuerySubscriptionProxy_startKeepalive, _QuerySubscriptionProxy_notifyCallbacks, _QuerySubscriptionProxy_releaseHold, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_releases, _PerspectiveProxy_ensuredSubjectClasses, _PerspectiveProxy_overlaysInFlight;
12
+ var _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_live, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_deliver, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_releases, _PerspectiveProxy_ensuredSubjectClasses, _PerspectiveProxy_overlaysInFlight;
13
13
  import { Link } from "../links/Links";
14
14
  import { LinkQuery } from "./LinkQuery";
15
15
  import { Literal } from "../Literal";
16
16
  import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
17
17
  import { getCachedResult, setCachedResult, invalidatePerspectiveCache } from "../model/query-cache";
18
+ import { LiveQuery } from "./LiveQuery";
18
19
  import { SHACLShape } from "../shacl/SHACLShape";
19
20
  import { SHACLFlow } from "../shacl/SHACLFlow";
20
21
  /** Extract namespace prefix from a URI (everything up to and including the last / or #) */
@@ -30,424 +31,73 @@ function extractNamespaceFromUri(uri) {
30
31
  return uri.substring(0, colonIdx + 1);
31
32
  return uri;
32
33
  }
33
- /** Proxy object for a subscribed Prolog query that provides real-time updates
34
- *
35
- * This class handles:
36
- * - Keeping the subscription alive by sending periodic keepalive signals
37
- * - Managing callbacks for result updates
38
- * - Subscribing to query updates via WebSocket subscriptions
39
- * - Maintaining the latest query result
40
- * - Ensuring subscription is fully initialized before allowing access
41
- * - Cleaning up resources when disposed
42
- *
43
- * The subscription will remain active as long as keepalive signals are sent.
44
- * Make sure to call dispose() when you're done with the subscription to clean up
45
- * resources, stop keepalive signals, and notify the backend to remove the subscription.
34
+ /** A live SPARQL query with its latest result.
46
35
  *
47
- * The subscription goes through an initialization process where it waits for the first
48
- * result to come through the subscription channel. You can await the `initialized`
49
- * promise to ensure the subscription is ready. The initialization will timeout after
50
- * 30 seconds if no result is received.
36
+ * `subscribe()` opens the query and resolves once the first result is in;
37
+ * `onResult()` callbacks then get every later result. The executor sends
38
+ * only changes; `LiveQuery` applies them, recovers from a missed update and
39
+ * re-opens the query after a reconnect. Call `dispose()` when done.
51
40
  *
52
- * Example usage:
53
41
  * ```typescript
54
- * const subscription = await perspective.subscribeInfer("my_query(X)");
55
- * // At this point the subscription is already initialized since subscribeInfer waits
56
- *
57
- * // Set up callback for future updates
58
- * const removeCallback = subscription.onResult(result => {
59
- * console.log("New result:", result);
60
- * });
61
- *
62
- * // Later: clean up subscription and notify backend
42
+ * const subscription = await perspective.subscribeQuery("SELECT ?s WHERE { ?s ?p ?o }");
43
+ * const remove = subscription.onResult(result => console.log(result));
63
44
  * subscription.dispose();
64
45
  * ```
65
46
  */
66
47
  export class QuerySubscriptionProxy {
67
- /** Creates a new query subscription
68
- * @param uuid - The UUID of the perspective
69
- * @param query - The Prolog query to subscribe to
70
- * @param client - The PerspectiveClient instance to use for communication
71
- */
72
48
  constructor(uuid, query, client) {
73
49
  _QuerySubscriptionProxy_instances.add(this);
74
- _QuerySubscriptionProxy_uuid.set(this, void 0);
75
- _QuerySubscriptionProxy_subscriptionId.set(this, void 0);
76
- _QuerySubscriptionProxy_client.set(this, void 0);
77
- _QuerySubscriptionProxy_callbacks.set(this, void 0);
78
- _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);
79
- _QuerySubscriptionProxy_unsubscribe.set(this, void 0);
80
- _QuerySubscriptionProxy_reconnectUnsub.set(this, void 0);
81
- _QuerySubscriptionProxy_latestResult.set(this, void 0);
82
- _QuerySubscriptionProxy_disposed.set(this, false);
50
+ _QuerySubscriptionProxy_live.set(this, void 0);
51
+ _QuerySubscriptionProxy_callbacks.set(this, new Set());
83
52
  _QuerySubscriptionProxy_initialized.set(this, void 0);
84
53
  _QuerySubscriptionProxy_initResolve.set(this, void 0);
85
54
  _QuerySubscriptionProxy_initReject.set(this, void 0);
86
- _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);
87
- _QuerySubscriptionProxy_query.set(this, void 0);
88
- // Monotonic token guarding the three concurrent writers of
89
- // `#unsubscribe`/`#subscriptionId` (full subscribe() from the keepalive
90
- // and init-timeout retry paths, and the reconnect swap handler). Each
91
- // writer bumps it on entry and re-checks after every await; a mismatch
92
- // means a newer writer took over while we were suspended, so the stale
93
- // continuation must back out instead of clobbering the newer state
94
- // (worst case otherwise: an overwritten-but-never-called unsubscribe
95
- // leaks its callback in ApiClient._wsCallbacks for the client lifetime).
96
- _QuerySubscriptionProxy_generation.set(this, 0);
97
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_uuid, uuid, "f");
98
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_query, query, "f");
99
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_client, client, "f");
100
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_callbacks, new Set(), "f");
101
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, null, "f");
102
- // Create the promise once and store its resolve/reject
55
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_live, new LiveQuery(client, uuid, () => client.subscribeQuery(uuid, query), result => __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, result)), "f");
103
56
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {
104
57
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, resolve, "f");
105
58
  __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, reject, "f");
106
59
  }), "f");
60
+ // `subscribe()` throws the same error, so a caller who never reads
61
+ // `initialized` must not get an unhandled rejection from it.
62
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_initialized, "f").catch(() => { });
107
63
  }
64
+ /** Open the query; resolves with the first result delivered. */
108
65
  async subscribe() {
109
- var _a;
110
- // Invalidate any suspended writer (older subscribe() or reconnect
111
- // swap parked on an await) — see #generation.
112
- const generation = __classPrivateFieldSet(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
113
- // Remove any prior reconnect listener FIRST — before we touch
114
- // `#unsubscribe`. Rationale: `#unsubscribe()` calls into
115
- // `ApiClient.subscribe()`'s deleter, which closes the WebSocket
116
- // whenever this query owned the last `_wsCallbacks` entry (and no
117
- // RPCs are pending). The subsequent `subscribeQuery()` below then
118
- // re-opens a fresh socket, and that fresh `onopen` fires the
119
- // reconnect callback set. If the OLD reconnect listener is still
120
- // in that set, it re-enters this method, closes the socket again,
121
- // reopens again … an endless resubscribe loop. Clearing the
122
- // listener up-front breaks the cycle; a fresh listener is
123
- // installed at the end of a successful subscribe(), and a
124
- // full-retry recovery listener in the catch block on failure.
125
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
126
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
127
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
128
- }
129
- // Clean up previous subscription attempt if retrying
130
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
131
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
132
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, undefined, "f");
133
- }
134
- // Clear any existing timeout
135
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
136
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
137
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
138
- }
139
- // Clear any existing keepalive timer to prevent accumulation
140
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f")) {
141
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
142
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, "f");
143
- }
144
- // A retry (init timeout, failed keepalive) replaces the hold this
145
- // proxy already has; release it so the proxy never holds two.
146
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_releaseHold).call(this);
147
66
  try {
148
- // Initialize the query subscription
149
- let initialResult;
150
- initialResult = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
151
- // A newer writer (another subscribe() or a reconnect swap) took
152
- // over while we awaited — back out without touching shared state,
153
- // and release the now-orphaned server-side subscription so it
154
- // doesn't linger until its keepalive TTL expires.
155
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") !== generation) {
156
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), initialResult.subscriptionId)
157
- .catch(e => console.error('Error disposing superseded query subscription:', e));
158
- return;
159
- }
160
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, "f");
161
- // Process the initial result immediately for fast UX.
162
- // The subscribeQuery() RPC call already returns the initial result,
163
- // so treat that as successful initialization instead of waiting for a
164
- // follow-up WebSocket update that may never arrive until the query changes.
165
- if (initialResult.result !== undefined) {
166
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, initialResult.result);
167
- }
168
- else {
169
- console.warn('⚠️ No initial result returned from subscribeQuery!');
170
- // Only keep the initialization timeout when the backend did not
171
- // provide an initial result up front.
172
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {
173
- console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');
174
- // Recursively retry subscription, catching any errors
175
- this.subscribe().catch(error => {
176
- console.error('Error during subscription retry after timeout:', error);
177
- });
178
- }, 30000), "f");
179
- }
180
- // Subscribe to query updates
181
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(__classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"), (updateResult) => __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult)), "f");
67
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliver).call(this, await __classPrivateFieldGet(this, _QuerySubscriptionProxy_live, "f").start());
182
68
  }
183
69
  catch (error) {
184
- console.error('Error setting up subscription:', error);
185
- // Reject the promise if this is the first attempt
186
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f")) {
187
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f").call(this, error);
188
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f");
189
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
190
- }
191
- // Restore reconnect recovery before rethrowing. The listener was
192
- // removed at the top of this method; without re-installing one
193
- // here, a single failed resubscribe (e.g. subscribeQuery timing
194
- // out during a network flap) would leave the proxy permanently
195
- // dead: the keepalive loop stops itself on resubscribe failure,
196
- // and nothing else retries. The recovery listener runs the FULL
197
- // subscribe() (not the swap-in-place handler) because after a
198
- // failed attempt there is no keepalive loop left to feed the new
199
- // server subscription — subscribe() restarts it. This is
200
- // loop-safe: in this failed state the proxy owns no
201
- // `_wsCallbacks` entry (the old one was unsubscribed at the top
202
- // of this method and no new one got registered), so the
203
- // subscribe() it triggers has nothing to unsubscribe → the
204
- // socket never closes/reopens under it → no re-entrant onopen.
205
- if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") === generation && __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
206
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").onReconnect(() => {
207
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
208
- return;
209
- console.log('WebSocket reconnected — retrying failed subscription for query:', __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
210
- this.subscribe().catch(e => {
211
- console.error('Error during subscription retry after reconnect:', e);
212
- });
213
- }), "f");
214
- }
215
- throw error; // Re-throw so caller knows it failed
216
- }
217
- // Start keepalive loop
218
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, generation);
219
- // Register for reconnect notification — on WebSocket reconnect,
220
- // immediately re-establish a fresh server-side subscription instead
221
- // of waiting up to 30s for the keepalive to fail.
222
- //
223
- // We deliberately do NOT call `this.subscribe()` here. Full subscribe
224
- // runs `#unsubscribe` first, which delegates to `ApiClient.subscribe`'s
225
- // deleter — that closes the WebSocket when this query owned the LAST
226
- // `_wsCallbacks` entry. The subsequent `subscribeQuery` reopens the
227
- // socket, whose fresh `onopen` fires every registered reconnect
228
- // callback again → recursion (CodeRabbit's original finding). And
229
- // during that close→reopen gap, RPCs in flight from OTHER proxies
230
- // fail with `503 WebSocket not connected` (observed in
231
- // integration-tests-mcp `should fire onWake when mention uses agent DID`
232
- // after PR #899's initial fix — the WakerSubscriptionManager tests
233
- // share a wakerClient across cases, so any dying reconnect handler
234
- // interferes with sibling subscriptions).
235
- //
236
- // The correct shape is a swap-in-place: get a new server-side
237
- // subscription ID via `subscribeQuery`, register a new client-side
238
- // callback FIRST, and only then unsubscribe the old one. That way
239
- // `_wsCallbacks.size` never dips to 0 during the transition, so the
240
- // socket doesn't close, no reconnect loop, and no cross-proxy 503s.
241
- // Any prior listener was already removed at the top of this method
242
- // (see the note there for why cleanup must run before `#unsubscribe`,
243
- // not here).
244
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").onReconnect) {
245
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_reconnectUnsub, __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").onReconnect(async () => {
246
- var _a;
247
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f"))
248
- return;
249
- // The handler is a writer of `#unsubscribe`/`#subscriptionId`
250
- // too, so it takes its own generation — see #generation.
251
- const swapGeneration = __classPrivateFieldSet(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f"), ++_a), "f");
252
- console.log('WebSocket reconnected — re-establishing server subscription for query:', __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
253
- try {
254
- const newInitial = await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
255
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") !== swapGeneration) {
256
- // A newer writer took over while we awaited — back out
257
- // and release the orphaned server-side subscription.
258
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), newInitial.subscriptionId)
259
- .catch(e => console.error('Error disposing superseded query subscription:', e));
260
- return;
261
- }
262
- const newSubId = newInitial.subscriptionId;
263
- // Register the NEW client-side callback BEFORE removing the
264
- // old one — keeps `_wsCallbacks.size >= 1` across the swap.
265
- const newUnsub = __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").subscribeToQueryUpdates(newSubId, (updateResult) => __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, updateResult));
266
- const oldUnsub = __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f");
267
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_unsubscribe, newUnsub, "f");
268
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_releaseHold).call(this);
269
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, newSubId, "f");
270
- if (oldUnsub)
271
- oldUnsub();
272
- // Our generation bump invalidated the running keepalive
273
- // loop — restart it under our generation so the new
274
- // server subscription keeps receiving keepalives.
275
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
276
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
277
- // Deliver the fresh initial result if the server included one
278
- // (matches the eager-delivery path in the main subscribe() body).
279
- // #deliverResult also clears a still-pending init timeout and
280
- // resolves #initialized, keeping this path symmetric with the
281
- // update callback in subscribe() — without it, a swap landing
282
- // while initialization was pending would leave the 30s init
283
- // timer armed and trigger a spurious full resubscribe.
284
- if (newInitial.result !== undefined) {
285
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_deliverResult).call(this, newInitial.result);
286
- }
287
- }
288
- catch (error) {
289
- console.error('Error re-establishing subscription after reconnect:', error);
290
- // Our generation bump invalidated the running keepalive
291
- // loop; if nothing newer superseded us, restart it so
292
- // liveness is preserved — its keepAliveQuery against the
293
- // dead old subscription will fail and fall back to a
294
- // full subscribe(). The reconnect listener also remains
295
- // installed, so a later reconnect retries this handler.
296
- if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") === swapGeneration) {
297
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
298
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_startKeepalive).call(this, swapGeneration);
299
- }
300
- }
301
- }), "f");
70
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_initReject, "f")?.call(this, error);
71
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f"), "f");
72
+ throw error;
302
73
  }
303
74
  }
304
- /** Get the subscription ID for this query subscription
305
- *
306
- * This is a unique identifier assigned when the subscription was created.
307
- * It can be used to reference this specific subscription, for example when
308
- * sending keepalive signals.
309
- *
310
- * @returns The subscription ID string
311
- */
75
+ /** The executor's id for this subscription. */
312
76
  get id() {
313
- return __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f");
77
+ return __classPrivateFieldGet(this, _QuerySubscriptionProxy_live, "f").id;
314
78
  }
315
- /** Promise that resolves when the subscription has received its first result
316
- * through the subscription channel. This ensures the subscription is fully
317
- * set up before allowing access to results or updates.
318
- *
319
- * If no result is received within 30 seconds, the subscription will automatically
320
- * retry. The promise will remain pending until a subscription message successfully
321
- * arrives, or until a fatal error occurs during subscription setup.
322
- *
323
- * Note: You typically don't need to await this directly since the subscription
324
- * creation methods (like subscribeInfer) already wait for initialization.
325
- */
79
+ /** Resolves once the first result has arrived. */
326
80
  get initialized() {
327
81
  return __classPrivateFieldGet(this, _QuerySubscriptionProxy_initialized, "f");
328
82
  }
329
- /** Get the latest query result
330
- *
331
- * This returns the most recent result from the query, which could be either:
332
- * - The initial result from when the subscription was created
333
- * - The latest update received through the subscription
334
- *
335
- * @returns The latest query result as a string (usually a JSON array of bindings)
336
- */
83
+ /** The latest result. */
337
84
  get result() {
338
- return __classPrivateFieldGet(this, _QuerySubscriptionProxy_latestResult, "f");
85
+ return __classPrivateFieldGet(this, _QuerySubscriptionProxy_live, "f").result;
339
86
  }
340
- /** Add a callback that will be called whenever new results arrive
341
- *
342
- * The callback will be called immediately with the current result,
343
- * and then again each time the query results change.
344
- *
345
- * @param callback - Function that takes a result string and processes it
346
- * @returns A function that can be called to remove this callback
347
- *
348
- * Example:
349
- * ```typescript
350
- * const removeCallback = subscription.onResult(result => {
351
- * const bindings = JSON.parse(result);
352
- * console.log("New bindings:", bindings);
353
- * });
354
- *
355
- * // Later: stop receiving updates
356
- * removeCallback();
357
- * ```
358
- */
87
+ /** Call `callback` with every later result. Returns a remover. */
359
88
  onResult(callback) {
360
89
  __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").add(callback);
361
90
  return () => __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").delete(callback);
362
91
  }
363
- /** Clean up the subscription and stop keepalive signals
364
- *
365
- * This method:
366
- * 1. Stops the keepalive timer
367
- * 2. Unsubscribes from subscription updates
368
- * 3. Clears all registered callbacks
369
- * 4. Cleans up any pending initialization timeout
370
- *
371
- * After calling this method, the subscription is no longer active and
372
- * will not receive any more updates. The instance should be discarded.
373
- * Calling it again is a no-op: subscribers of the same query share one
374
- * executor subscription, and only the first call releases this proxy's
375
- * hold on it.
376
- */
92
+ /** End the subscription on the executor and drop all callbacks. */
377
93
  dispose() {
378
- var _a;
379
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_disposed, true, "f");
380
- // Invalidate any suspended writer so a mid-flight subscribe() or
381
- // reconnect swap backs out instead of resurrecting state.
382
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_generation, (_a = __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f"), _a++, _a), "f");
383
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_keepaliveTimer, "f"));
384
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f")) {
385
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_unsubscribe, "f").call(this);
386
- }
387
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_reconnectUnsub, "f")) {
388
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_reconnectUnsub, "f").call(this);
389
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_reconnectUnsub, undefined, "f");
390
- }
94
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_live, "f").dispose();
391
95
  __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f").clear();
392
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
393
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
394
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
395
- }
396
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_releaseHold).call(this);
397
96
  }
398
97
  }
399
- _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_reconnectUnsub = 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_generation = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_deliverResult = function _QuerySubscriptionProxy_deliverResult(result) {
400
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f")) {
401
- clearTimeout(__classPrivateFieldGet(this, _QuerySubscriptionProxy_initTimeoutId, "f"));
402
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initTimeoutId, undefined, "f");
403
- }
404
- // Resolve the initialization promise (only resolves once)
405
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f")) {
406
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f").call(this, true);
407
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, undefined, "f"); // Prevent double-resolve
408
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f");
409
- }
410
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_latestResult, result, "f");
411
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_instances, "m", _QuerySubscriptionProxy_notifyCallbacks).call(this, result);
412
- }, _QuerySubscriptionProxy_startKeepalive = function _QuerySubscriptionProxy_startKeepalive(generation) {
413
- const keepaliveLoop = async () => {
414
- // Generation check kills orphaned loops: a loop whose
415
- // keepAliveQuery was in flight while a newer writer ran is not
416
- // cancelled by clearTimeout and would otherwise reschedule
417
- // itself alongside the newer loop.
418
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") !== generation)
419
- return;
420
- try {
421
- await __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").keepAliveQuery(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f"));
422
- }
423
- catch (e) {
424
- if (__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") || __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") !== generation)
425
- return;
426
- console.error('Error in keepalive:', e);
427
- // try to reinitialize the subscription
428
- console.log('Reinitializing subscription for query:', __classPrivateFieldGet(this, _QuerySubscriptionProxy_query, "f"));
429
- try {
430
- await this.subscribe();
431
- console.log('Subscription reinitialized');
432
- }
433
- catch (resubscribeError) {
434
- console.error('Error during resubscription from keepalive:', resubscribeError);
435
- // Don't schedule another keepalive on resubscribe failure.
436
- // Recovery is not lost: the failed subscribe() installed a
437
- // reconnect listener that retries the full subscribe.
438
- return;
439
- }
440
- // subscribe() succeeded and started its own keepalive loop
441
- // under a new generation — this loop is done.
442
- return;
443
- }
444
- // Schedule next keepalive if still the active generation
445
- if (!__classPrivateFieldGet(this, _QuerySubscriptionProxy_disposed, "f") && __classPrivateFieldGet(this, _QuerySubscriptionProxy_generation, "f") === generation) {
446
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
447
- }
448
- };
449
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), "f");
450
- }, _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {
98
+ _QuerySubscriptionProxy_live = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_deliver = function _QuerySubscriptionProxy_deliver(result) {
99
+ __classPrivateFieldGet(this, _QuerySubscriptionProxy_initResolve, "f")?.call(this, true);
100
+ __classPrivateFieldSet(this, _QuerySubscriptionProxy_initResolve, __classPrivateFieldSet(this, _QuerySubscriptionProxy_initReject, undefined, "f"), "f");
451
101
  for (const callback of __classPrivateFieldGet(this, _QuerySubscriptionProxy_callbacks, "f")) {
452
102
  try {
453
103
  callback(result);
@@ -456,13 +106,6 @@ _QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscripti
456
106
  console.error('Error in query subscription callback:', e);
457
107
  }
458
108
  }
459
- }, _QuerySubscriptionProxy_releaseHold = function _QuerySubscriptionProxy_releaseHold() {
460
- const subscriptionId = __classPrivateFieldGet(this, _QuerySubscriptionProxy_subscriptionId, "f");
461
- __classPrivateFieldSet(this, _QuerySubscriptionProxy_subscriptionId, undefined, "f");
462
- if (subscriptionId) {
463
- __classPrivateFieldGet(this, _QuerySubscriptionProxy_client, "f").disposeQuerySubscription(__classPrivateFieldGet(this, _QuerySubscriptionProxy_uuid, "f"), subscriptionId)
464
- .catch(e => console.error('Error disposing query subscription:', e));
465
- }
466
109
  };
467
110
  /**
468
111
  * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs
@@ -823,6 +466,46 @@ export class PerspectiveProxy {
823
466
  async flowValidOutputs(flow, state) {
824
467
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowValidOutputs(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, flow, state);
825
468
  }
469
+ /**
470
+ * The state each flow instance is in, as **this agent's** executor last
471
+ * derived it — one entry per instance it has derived, optionally narrowed
472
+ * to `instances`. An instance missing from the answer has not been
473
+ * derived here yet; it stands at its flow's first state.
474
+ *
475
+ * The state is not stored on the graph: the engine derives it from the
476
+ * signed proposals and keeps what it derived per agent, outside the
477
+ * perspective. So no other agent — a co-owner on the same node included —
478
+ * can read or write your entries, and a link query never sees them.
479
+ * `FlowInstance.findAll` / `start` call this for you.
480
+ */
481
+ async flowStates(instances) {
482
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowStates(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instances);
483
+ }
484
+ /**
485
+ * The proposals of `instance` whose votes settled an edge, as this
486
+ * agent's executor recorded them — the flow's history, sorted by URI.
487
+ * Replaces the `resolvedAs` property proposals used to carry.
488
+ */
489
+ async flowFired(instance) {
490
+ return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").flowFired(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instance);
491
+ }
492
+ /**
493
+ * Called whenever a flow instance on this perspective changes state on
494
+ * this agent's executor, or an edge settles: `{ instance, from, to,
495
+ * firedProposals, caughtUp }`. Only this agent's sockets receive it.
496
+ *
497
+ * When the executor first derives an instance that already has history
498
+ * (it synced in, or the executor was upgraded) it is called once with
499
+ * `caughtUp: true`, `from: null` and no `firedProposals`: the settles
500
+ * before that are history, but `to` is the state to show for a run that
501
+ * read as not derived (`FlowInstance.currentStateName === undefined`).
502
+ *
503
+ * Returns a function that removes the handler; {@link dispose} removes
504
+ * it too.
505
+ */
506
+ onFlowStateChanged(handler) {
507
+ return this.on("flow-state-changed", handler);
508
+ }
826
509
  /** Mint and store the receipt for a completed flow run. */
827
510
  async mintFlowReceipt(instanceUri) {
828
511
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").mintFlowReceipt(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, instanceUri);
@@ -890,7 +573,9 @@ export class PerspectiveProxy {
890
573
  * triples (written by `addSdna`). Callers no longer ship shape
891
574
  * metadata with the query; the perspective is the source of truth.
892
575
  *
893
- * @param className - The model class name (e.g. "Recipe")
576
+ * @param className - The model class name (e.g. "Recipe"), or several: one
577
+ * query over their union, whose rows carry `__subjectClass` and
578
+ * `__subjectClasses` (#1238)
894
579
  * @param queryJson - Structured query as JSON string
895
580
  * @returns Object with `instances` array and `totalCount`
896
581
  */
@@ -948,16 +633,14 @@ export class PerspectiveProxy {
948
633
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").evaluateGetters(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, instanceIds, propertyNames);
949
634
  }
950
635
  /**
951
- * Subscribe to model query changes. Builds trigger SPARQL from the model shape
952
- * internally in Rust, registers a subscription, runs the initial query, and
953
- * pushes updated results when relevant links change.
954
- *
955
- * The subscription reuses the same WS-RPC subscription channel as subscribeQuery().
956
- * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.
636
+ * Open a live model query on the executor. Later changes arrive as
637
+ * updates; `LiveQuery` (or `ModelQueryBuilder.subscribe()`) applies them.
638
+ * The subscription ends with `disposeQuerySubscription()` or when the
639
+ * socket closes.
957
640
  *
958
- * @param className - The model class name
641
+ * @param className - The model class name, or several (same as modelQuery)
959
642
  * @param queryJson - JSON-serialized query parameters (same as modelQuery)
960
- * @returns Object with `subscriptionId` and initial `result`
643
+ * @returns `subscriptionId`, initial `result` and `revision` (0)
961
644
  */
962
645
  async modelSubscribe(className, queryJson) {
963
646
  return await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").modelSubscribe(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, queryJson);
@@ -1386,6 +1069,9 @@ export class PerspectiveProxy {
1386
1069
  async ensureSubjectClasses(jsClasses) {
1387
1070
  const entries = [];
1388
1071
  for (const jsClass of jsClasses) {
1072
+ // Built-in classes (`TextContent`) live in the executor, not here.
1073
+ if (Object.prototype.hasOwnProperty.call(jsClass, 'builtinUri'))
1074
+ continue;
1389
1075
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
1390
1076
  if (__classPrivateFieldGet(this, _PerspectiveProxy_ensuredSubjectClasses, "f").has(className))
1391
1077
  continue;
@@ -1713,6 +1399,13 @@ export class PerspectiveProxy {
1713
1399
  // getSubjectData() to interact with the created instance.
1714
1400
  return exprAddr;
1715
1401
  }
1402
+ /** Sets properties of an existing instance in the executor. Through an
1403
+ * abstract class (#1435), each value is written by every class of the
1404
+ * record that the abstract class reads, under its own name. */
1405
+ async updateSubject(className, exprAddr, values, batchId) {
1406
+ await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").updateSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, JSON.stringify(values), batchId);
1407
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1408
+ }
1716
1409
  async getSubjectData(subjectClass, exprAddr) {
1717
1410
  if (typeof subjectClass === "string") {
1718
1411
  return JSON.parse(await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").getSubjectData(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, JSON.stringify({ className: subjectClass }), exprAddr));
@@ -1770,7 +1463,24 @@ export class PerspectiveProxy {
1770
1463
  * and won't be executed until the batch is committed.
1771
1464
  */
1772
1465
  async removeSubject(subjectClass, exprAddr, batchId) {
1466
+ // A built-in abstract class (`TextContent`, #1446) is never stored,
1467
+ // so it has no marker: the executor dispatches it by its URI.
1468
+ const ctor = subjectClass?.constructor;
1469
+ if (typeof subjectClass === "object" && ctor && Object.prototype.hasOwnProperty.call(ctor, 'builtinUri')) {
1470
+ await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, ctor.builtinUri, exprAddr, batchId);
1471
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1472
+ return;
1473
+ }
1773
1474
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
1475
+ // An abstract class (#1435) is never a record's class: the executor
1476
+ // runs the destructors of the record's classes it reads.
1477
+ const shapePattern = new RegExp(`[/:#]${this.escapeRegExp(className)}Shape$`);
1478
+ const markers = await this.get(new LinkQuery({ predicate: "ad4m://abstract" }));
1479
+ if (markers.some((link) => shapePattern.test(link.data.source))) {
1480
+ await __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").removeSubject(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid, className, exprAddr, batchId);
1481
+ invalidatePerspectiveCache(__classPrivateFieldGet(this, _PerspectiveProxy_handle, "f").uuid);
1482
+ return;
1483
+ }
1774
1484
  // Get destructor actions from SHACL links (Prolog-free)
1775
1485
  let actions = await this.getActionsFromSHACL(className, "ad4m://destructor");
1776
1486
  if (!actions) {
@@ -2087,6 +1797,9 @@ export class PerspectiveProxy {
2087
1797
  }
2088
1798
  /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */
2089
1799
  async ensureSubjectClass(jsClass) {
1800
+ // Built-in classes (`TextContent`) live in the executor, not here.
1801
+ if (Object.prototype.hasOwnProperty.call(jsClass, 'builtinUri'))
1802
+ return;
2090
1803
  // Get the class name from the JS class
2091
1804
  const className = jsClass.className || jsClass.prototype?.className || jsClass.name;
2092
1805
  // Skip if already registered for this perspective instance
@@ -2305,80 +2018,13 @@ export class PerspectiveProxy {
2305
2018
  get ai() {
2306
2019
  return __classPrivateFieldGet(this, _PerspectiveProxy_client, "f").aiClient;
2307
2020
  }
2308
- /**
2309
- * Creates a subscription for a Prolog query that updates in real-time.
2310
- *
2311
- * This method:
2312
- * 1. Creates the subscription on the Rust side
2313
- * 2. Sets up the subscription callback
2314
- * 3. Waits for the initial result to come through the subscription channel
2315
- * 4. Returns a fully initialized QuerySubscriptionProxy
2316
- *
2317
- * The returned subscription is guaranteed to be ready to receive updates,
2318
- * as this method waits for the initialization process to complete.
2319
- *
2320
- * The subscription will be automatically cleaned up on both frontend and backend
2321
- * when dispose() is called. Make sure to call dispose() when you're done to
2322
- * prevent memory leaks and ensure proper cleanup of resources.
2323
- *
2324
- * @param query - Prolog query string
2325
- * @returns Initialized QuerySubscriptionProxy instance
2326
- *
2327
- * @example
2328
- * ```typescript
2329
- * // Subscribe to active todos
2330
- * const subscription = await perspective.subscribeInfer(`
2331
- * instance(Todo, "Todo"),
2332
- * property_getter("Todo", Todo, "state", "active")
2333
- * `);
2334
- *
2335
- * // Subscription is already initialized here
2336
- * console.log("Initial result:", subscription.result);
2337
- *
2338
- * // Set up callback for future updates
2339
- * subscription.onResult((todos) => {
2340
- * console.log("Active todos:", todos);
2341
- * });
2342
- *
2343
- * // Clean up subscription when done
2344
- * subscription.dispose();
2345
- * ```
2346
- */
2347
- async subscribeInfer(query) {
2348
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
2349
- // Start the subscription on the Rust side first to get the real subscription ID
2350
- await subscriptionProxy.subscribe();
2351
- // Wait for the initial result
2352
- await subscriptionProxy.initialized;
2353
- return subscriptionProxy;
2354
- }
2355
- /**
2356
- * Creates a subscription for a SPARQL query that updates in real-time.
2357
- *
2358
- * This method:
2359
- * 1. Creates the subscription on the Rust side
2360
- * 2. Sets up the subscription callback
2361
- * 3. Waits for the initial result to come through the subscription channel
2362
- * 4. Returns a fully initialized QuerySubscriptionProxy
2363
- *
2364
- * The returned subscription is guaranteed to be ready to receive updates,
2365
- * as this method waits for the initialization process to complete.
2366
- *
2367
- * The subscription will be automatically cleaned up on both frontend and backend
2368
- * when dispose() is called. Make sure to call dispose() when you're done to
2369
- * prevent memory leaks and ensure proper cleanup of resources.
2370
- *
2371
- /** Subscribe to a query with live updates via the SPARQL subscription endpoint.
2372
- * @param query - Query string
2373
- * @returns Initialized QuerySubscriptionProxy instance
2374
- */
2021
+ /** Live SPARQL query: resolves once the first result is in.
2022
+ * Call `dispose()` on the returned proxy when done. The executor
2023
+ * refuses a Prolog query (400): Prolog live queries are not supported. */
2375
2024
  async subscribeQuery(query) {
2376
- const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
2377
- // Start the subscription on the Rust side first to get the real subscription ID
2378
- await subscriptionProxy.subscribe();
2379
- // Wait for the initial result
2380
- await subscriptionProxy.initialized;
2381
- return subscriptionProxy;
2025
+ const subscription = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet(this, _PerspectiveProxy_client, "f"));
2026
+ await subscription.subscribe();
2027
+ return subscription;
2382
2028
  }
2383
2029
  }
2384
2030
  _PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_releases = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap(), _PerspectiveProxy_overlaysInFlight = new WeakMap();