@hydranium/protocol 1.0.0-next.25 → 1.0.0-next.251

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 (250) hide show
  1. package/README.md +44 -49
  2. package/lib/abstract-logger.d.ts +5 -0
  3. package/lib/abstract-logger.d.ts.map +1 -1
  4. package/lib/abstract-logger.js +7 -0
  5. package/lib/abstract-logger.js.map +1 -1
  6. package/lib/client/data-connection.d.ts +245 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +425 -0
  9. package/lib/client/data-connection.js.map +1 -0
  10. package/lib/client/data-events.d.ts +13 -1
  11. package/lib/client/data-events.d.ts.map +1 -1
  12. package/lib/client/data-events.js +21 -0
  13. package/lib/client/data-events.js.map +1 -1
  14. package/lib/client/data-port.d.ts +44 -27
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +473 -81
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +743 -108
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +14 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +14 -9
  23. package/lib/client/index.js.map +1 -1
  24. package/lib/client/message-relay.d.ts +10 -4
  25. package/lib/client/message-relay.d.ts.map +1 -1
  26. package/lib/client/message-relay.js +12 -6
  27. package/lib/client/message-relay.js.map +1 -1
  28. package/lib/client/post-message-transport.d.ts +64 -3
  29. package/lib/client/post-message-transport.d.ts.map +1 -1
  30. package/lib/client/post-message-transport.js +175 -1
  31. package/lib/client/post-message-transport.js.map +1 -1
  32. package/lib/client/rpc-connection.d.ts +157 -0
  33. package/lib/client/rpc-connection.d.ts.map +1 -0
  34. package/lib/client/rpc-connection.js +214 -0
  35. package/lib/client/rpc-connection.js.map +1 -0
  36. package/lib/client-ids.d.ts +45 -0
  37. package/lib/client-ids.d.ts.map +1 -0
  38. package/lib/client-ids.js +48 -0
  39. package/lib/client-ids.js.map +1 -0
  40. package/lib/clock.d.ts +38 -0
  41. package/lib/clock.d.ts.map +1 -1
  42. package/lib/clock.js +36 -1
  43. package/lib/clock.js.map +1 -1
  44. package/lib/console-logger.d.ts +23 -0
  45. package/lib/console-logger.d.ts.map +1 -0
  46. package/lib/console-logger.js +39 -0
  47. package/lib/console-logger.js.map +1 -0
  48. package/lib/data/data-protocol-methods.d.ts +4 -4
  49. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  50. package/lib/data/data-protocol-methods.js +12 -1
  51. package/lib/data/data-protocol-methods.js.map +1 -1
  52. package/lib/data/data-server-protocol.d.ts +132 -41
  53. package/lib/data/data-server-protocol.d.ts.map +1 -1
  54. package/lib/data/events.d.ts +117 -21
  55. package/lib/data/events.d.ts.map +1 -1
  56. package/lib/data/requests.d.ts +69 -11
  57. package/lib/data/requests.d.ts.map +1 -1
  58. package/lib/debouncer.d.ts.map +1 -1
  59. package/lib/debouncer.js.map +1 -1
  60. package/lib/errors.d.ts +187 -29
  61. package/lib/errors.d.ts.map +1 -1
  62. package/lib/errors.js +270 -29
  63. package/lib/errors.js.map +1 -1
  64. package/lib/glsp-request-model-args.d.ts +16 -0
  65. package/lib/glsp-request-model-args.d.ts.map +1 -0
  66. package/lib/glsp-request-model-args.js +19 -0
  67. package/lib/glsp-request-model-args.js.map +1 -0
  68. package/lib/glsp-save-model-actions.d.ts +50 -0
  69. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  70. package/lib/glsp-save-model-actions.js +28 -0
  71. package/lib/glsp-save-model-actions.js.map +1 -0
  72. package/lib/index.d.ts +7 -0
  73. package/lib/index.d.ts.map +1 -1
  74. package/lib/index.js +10 -0
  75. package/lib/index.js.map +1 -1
  76. package/lib/latency-collector.d.ts +8 -4
  77. package/lib/latency-collector.d.ts.map +1 -1
  78. package/lib/latency-collector.js.map +1 -1
  79. package/lib/logger.d.ts +22 -1
  80. package/lib/logger.d.ts.map +1 -1
  81. package/lib/logger.js +31 -3
  82. package/lib/logger.js.map +1 -1
  83. package/lib/messages/index.d.ts +30 -0
  84. package/lib/messages/index.d.ts.map +1 -0
  85. package/lib/messages/index.js +62 -0
  86. package/lib/messages/index.js.map +1 -0
  87. package/lib/messages/primitives.d.ts +188 -0
  88. package/lib/messages/primitives.d.ts.map +1 -0
  89. package/lib/messages/primitives.js +161 -0
  90. package/lib/messages/primitives.js.map +1 -0
  91. package/lib/model-server.d.ts +60 -13
  92. package/lib/model-server.d.ts.map +1 -1
  93. package/lib/model-server.js +4 -2
  94. package/lib/model-server.js.map +1 -1
  95. package/lib/model-service/base-version.d.ts +64 -0
  96. package/lib/model-service/base-version.d.ts.map +1 -0
  97. package/lib/model-service/base-version.js +43 -0
  98. package/lib/model-service/base-version.js.map +1 -0
  99. package/lib/model-service/index.d.ts +1 -1
  100. package/lib/model-service/index.d.ts.map +1 -1
  101. package/lib/model-service/index.js +4 -5
  102. package/lib/model-service/index.js.map +1 -1
  103. package/lib/model-service/reference-candidate.d.ts +5 -3
  104. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  105. package/lib/{model-service/args.js → node/index.d.ts} +2 -3
  106. package/lib/node/index.d.ts.map +1 -0
  107. package/lib/node/index.js +29 -0
  108. package/lib/node/index.js.map +1 -0
  109. package/lib/node/process-memory.d.ts +66 -0
  110. package/lib/node/process-memory.d.ts.map +1 -0
  111. package/lib/node/process-memory.js +291 -0
  112. package/lib/node/process-memory.js.map +1 -0
  113. package/lib/noop-logger.d.ts.map +1 -1
  114. package/lib/noop-logger.js.map +1 -1
  115. package/lib/observable-value.js.map +1 -1
  116. package/lib/patch-merge.d.ts +35 -32
  117. package/lib/patch-merge.d.ts.map +1 -1
  118. package/lib/patch-merge.js +67 -23
  119. package/lib/patch-merge.js.map +1 -1
  120. package/lib/profile-session.d.ts +8 -4
  121. package/lib/profile-session.d.ts.map +1 -1
  122. package/lib/profile-session.js.map +1 -1
  123. package/lib/random-uuid.d.ts +14 -0
  124. package/lib/random-uuid.d.ts.map +1 -0
  125. package/lib/random-uuid.js +24 -0
  126. package/lib/random-uuid.js.map +1 -0
  127. package/lib/reconcile-write.d.ts +65 -0
  128. package/lib/reconcile-write.d.ts.map +1 -0
  129. package/lib/reconcile-write.js +67 -0
  130. package/lib/reconcile-write.js.map +1 -0
  131. package/lib/rpc/bind-rpc-methods.d.ts +33 -3
  132. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  133. package/lib/rpc/bind-rpc-methods.js +32 -3
  134. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  135. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  136. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  137. package/lib/rpc/create-rpc-proxy.js +12 -2
  138. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  139. package/lib/rpc/index.d.ts +1 -0
  140. package/lib/rpc/index.d.ts.map +1 -1
  141. package/lib/rpc/index.js +1 -0
  142. package/lib/rpc/index.js.map +1 -1
  143. package/lib/rpc/send-by-method-name.d.ts +76 -0
  144. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  145. package/lib/rpc/send-by-method-name.js +120 -0
  146. package/lib/rpc/send-by-method-name.js.map +1 -0
  147. package/lib/rpc/wire-prefix.js.map +1 -1
  148. package/lib/testing/catalogue-audit.d.ts +80 -0
  149. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  150. package/lib/testing/catalogue-audit.js +94 -0
  151. package/lib/testing/catalogue-audit.js.map +1 -0
  152. package/lib/testing/data-doubles.d.ts +46 -15
  153. package/lib/testing/data-doubles.d.ts.map +1 -1
  154. package/lib/testing/data-doubles.js +58 -10
  155. package/lib/testing/data-doubles.js.map +1 -1
  156. package/lib/testing/fake-clock.d.ts +9 -1
  157. package/lib/testing/fake-clock.d.ts.map +1 -1
  158. package/lib/testing/fake-clock.js +54 -45
  159. package/lib/testing/fake-clock.js.map +1 -1
  160. package/lib/testing/index.d.ts +1 -0
  161. package/lib/testing/index.d.ts.map +1 -1
  162. package/lib/testing/index.js +5 -2
  163. package/lib/testing/index.js.map +1 -1
  164. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  165. package/lib/testing/node/duplex-connection.js +3 -2
  166. package/lib/testing/node/duplex-connection.js.map +1 -1
  167. package/lib/testing/node/duplex-stream.js.map +1 -1
  168. package/lib/testing/node/index.d.ts +1 -0
  169. package/lib/testing/node/index.d.ts.map +1 -1
  170. package/lib/testing/node/index.js +2 -2
  171. package/lib/testing/node/index.js.map +1 -1
  172. package/lib/testing/node/message-port-pair.d.ts +25 -0
  173. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  174. package/lib/testing/node/message-port-pair.js +26 -0
  175. package/lib/testing/node/message-port-pair.js.map +1 -0
  176. package/lib/testing/wait-for.d.ts +3 -2
  177. package/lib/testing/wait-for.d.ts.map +1 -1
  178. package/lib/testing/wait-for.js +40 -10
  179. package/lib/testing/wait-for.js.map +1 -1
  180. package/lib/tracer.d.ts.map +1 -1
  181. package/lib/tracer.js.map +1 -1
  182. package/lib/transfer-diagnostic.d.ts +33 -0
  183. package/lib/transfer-diagnostic.d.ts.map +1 -1
  184. package/lib/transfer-diagnostic.js +23 -0
  185. package/lib/transfer-diagnostic.js.map +1 -1
  186. package/lib/transfer-document.d.ts +70 -32
  187. package/lib/transfer-document.d.ts.map +1 -1
  188. package/lib/transfer-document.js +17 -9
  189. package/lib/transfer-document.js.map +1 -1
  190. package/lib/uri.d.ts.map +1 -1
  191. package/lib/uri.js.map +1 -1
  192. package/lib/util.d.ts +8 -0
  193. package/lib/util.d.ts.map +1 -1
  194. package/lib/util.js +32 -0
  195. package/lib/util.js.map +1 -1
  196. package/package.json +29 -37
  197. package/src/abstract-logger.ts +8 -0
  198. package/src/client/data-connection.ts +520 -0
  199. package/src/client/data-events.ts +33 -1
  200. package/src/client/data-port.ts +46 -28
  201. package/src/client/data-session.ts +951 -126
  202. package/src/client/index.ts +14 -9
  203. package/src/client/message-relay.ts +30 -8
  204. package/src/client/post-message-transport.ts +219 -4
  205. package/src/client/rpc-connection.ts +281 -0
  206. package/src/client-ids.ts +49 -0
  207. package/src/clock.ts +56 -0
  208. package/src/console-logger.ts +39 -0
  209. package/src/data/data-protocol-methods.ts +13 -4
  210. package/src/data/data-server-protocol.ts +157 -41
  211. package/src/data/events.ts +123 -21
  212. package/src/data/requests.ts +74 -11
  213. package/src/errors.ts +322 -36
  214. package/src/glsp-request-model-args.ts +16 -0
  215. package/src/glsp-save-model-actions.ts +59 -0
  216. package/src/index.ts +10 -0
  217. package/src/latency-collector.ts +8 -3
  218. package/src/logger.ts +28 -2
  219. package/src/messages/index.ts +37 -0
  220. package/src/messages/primitives.ts +271 -0
  221. package/src/model-server.ts +64 -19
  222. package/src/model-service/base-version.ts +72 -0
  223. package/src/model-service/index.ts +4 -5
  224. package/src/model-service/reference-candidate.ts +5 -3
  225. package/src/node/index.ts +14 -0
  226. package/src/node/process-memory.ts +299 -0
  227. package/src/patch-merge.ts +97 -42
  228. package/src/profile-session.ts +9 -4
  229. package/src/random-uuid.ts +21 -0
  230. package/src/reconcile-write.ts +124 -0
  231. package/src/rpc/README.md +4 -5
  232. package/src/rpc/bind-rpc-methods.ts +59 -4
  233. package/src/rpc/create-rpc-proxy.ts +20 -2
  234. package/src/rpc/index.ts +1 -0
  235. package/src/rpc/send-by-method-name.ts +140 -0
  236. package/src/testing/catalogue-audit.ts +111 -0
  237. package/src/testing/data-doubles.ts +149 -25
  238. package/src/testing/fake-clock.ts +62 -47
  239. package/src/testing/index.ts +5 -2
  240. package/src/testing/node/duplex-connection.ts +3 -2
  241. package/src/testing/node/index.ts +2 -2
  242. package/src/testing/node/message-port-pair.ts +40 -0
  243. package/src/testing/wait-for.ts +38 -11
  244. package/src/transfer-diagnostic.ts +40 -0
  245. package/src/transfer-document.ts +87 -34
  246. package/src/util.ts +33 -0
  247. package/lib/model-service/args.d.ts +0 -64
  248. package/lib/model-service/args.d.ts.map +0 -1
  249. package/lib/model-service/args.js.map +0 -1
  250. package/src/model-service/args.ts +0 -67
@@ -0,0 +1,520 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { Disposable, Emitter, type Event } from 'vscode-jsonrpc';
11
+ import { FRAMEWORK_CLIENT_IDS } from '../client-ids';
12
+ import {
13
+ DATA_CLIENT_PROTOCOL_METHODS,
14
+ DATA_SERVER_WIRE_PREFIX,
15
+ type DataClientProtocol,
16
+ type DataServerProtocol,
17
+ type DiagnosticOf,
18
+ type ProjectOf,
19
+ type TransferDocumentDirtyChangedEvent,
20
+ type TransferDocumentUpdatedEvent
21
+ } from '../data';
22
+ import { DuplicateClientIdError, ReservedClientIdError } from '../errors';
23
+ import type { Logger } from '../logger';
24
+ import { defineMessage, describeError, resolve } from '../messages/primitives';
25
+ import { NoopLogger } from '../noop-logger';
26
+ import { randomUuid } from '../random-uuid';
27
+ import type { TransferElement } from '../transfer-element';
28
+ import { DataEvents } from './data-events';
29
+ import type { DataPort } from './data-port';
30
+ import { DataSession, type DataSessionFactory } from './data-session';
31
+ import { RpcConnection, type RpcConnectionGeneration, type RpcConnectionLifecycle } from './rpc-connection';
32
+
33
+ /**
34
+ * A watch {@link DataConnection.watchDocument} keeps could not be sent again to
35
+ * a connection that became ready after a drop; the next one sends it again.
36
+ */
37
+ export const DATA_CONNECTION_WATCH_RESTORE_FAILED = defineMessage(
38
+ 'hydranium/protocol/data-connection-watch-restore-failed',
39
+ 'Could not watch {uri} again after reconnecting to the data server: {detail}'
40
+ );
41
+
42
+ /**
43
+ * A session's restore threw when its connection came back; the connection
44
+ * went on restoring the others.
45
+ */
46
+ export const DATA_CONNECTION_SESSION_RESTORE_FAILED = defineMessage(
47
+ 'hydranium/protocol/data-connection-session-restore-failed',
48
+ 'Could not restore a session after reconnecting to the data server: {detail}'
49
+ );
50
+
51
+ /** Options for {@link DataConnection}. */
52
+ export interface DataConnectionOptions<
53
+ TTransfer extends TransferElement = TransferElement,
54
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
55
+ > extends RpcConnectionLifecycle {
56
+ /**
57
+ * Wire namespace the server is addressed under. Defaults to the
58
+ * framework's {@link DATA_SERVER_WIRE_PREFIX}, which is what an unmodified
59
+ * `DataServer` binds. Override only alongside the server's own
60
+ * `methodNamespace` option — a mismatch turns every request into
61
+ * "Unhandled method" rather than failing at wire-up.
62
+ */
63
+ readonly methodNamespace?: string;
64
+ /** Builds the sessions `createSession` hands out. Defaults to a plain {@link DataSession}. */
65
+ readonly sessionFactory?: DataSessionFactory<TTransfer, TServer>;
66
+ }
67
+
68
+ /** {@link DataConnectionOptions} for a client that does not speak {@link DataClientProtocol}. */
69
+ export interface DataConnectionOptionsWithMethods<
70
+ TClient extends object,
71
+ TTransfer extends TransferElement = TransferElement,
72
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
73
+ > extends DataConnectionOptions<TTransfer, TServer> {
74
+ /**
75
+ * Method names of the client to bind as inbound handlers. Declare it
76
+ * `as const satisfies ReadonlyArray<keyof YourClient & string>` so the list
77
+ * cannot drift from the interface.
78
+ */
79
+ readonly clientMethods: readonly (keyof TClient & string)[];
80
+ }
81
+
82
+ /**
83
+ * Trailing constructor arguments, required only when the client cannot take
84
+ * the framework's default method list.
85
+ *
86
+ * `bindRpcMethods` throws for a name the target does not implement, so a
87
+ * request/response-only client binding the default list fails at wire-up. The
88
+ * conditional turns that into a compile error.
89
+ */
90
+ export type DataConnectionArgs<
91
+ TTransfer extends TransferElement,
92
+ TClient extends object,
93
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
94
+ > =
95
+ TClient extends DataClientProtocol<TTransfer>
96
+ ? [options?: DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>]
97
+ : [options: DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>];
98
+
99
+ /**
100
+ * A {@link RpcConnection} to the data head, carrying as many participants as
101
+ * the host has interested parties.
102
+ *
103
+ * Document operations live on the participants rather than here: they carry a
104
+ * `clientId`, which identifies a participant rather than a wire, and the server
105
+ * keys its opens and watches per `(uri, clientId)`. Two parties sharing one
106
+ * identity cannot tell each other's writes from their own echoes.
107
+ * {@link DataConnection.watchDocument} is the exception: it acts as no
108
+ * participant, under an id no session holds, and opens or writes nothing.
109
+ *
110
+ * Generic over the transfer root so this file names no grammar. An adopter
111
+ * binds the concrete root (or the union of them, for a multi-grammar head) at
112
+ * its own edge.
113
+ */
114
+ export class DataConnection<
115
+ TTransfer extends TransferElement,
116
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>,
117
+ TClient extends object = DataClientProtocol<TTransfer>
118
+ > extends RpcConnection<TServer, TClient> {
119
+ protected readonly sessions = new Set<DataSession<TTransfer, TServer>>();
120
+ protected readonly sessionFactory: DataSessionFactory<TTransfer, TServer>;
121
+ protected readonly createSessionEmitter = new Emitter<DataSession<TTransfer, TServer>>();
122
+ /**
123
+ * Fires with each session {@link createSession} starts, before it returns,
124
+ * so a listener sees every session a caller can. A session started before
125
+ * the listener subscribed is in {@link liveSessions}.
126
+ */
127
+ readonly onDidCreateSession: Event<DataSession<TTransfer, TServer>> = this.createSessionEmitter.event;
128
+ /**
129
+ * Per URI, the `dirty` the client was last told, whether a session of this
130
+ * connection has it open or a watch follows it. A session's open or close
131
+ * of the URI forgets it; disposing a watch does not, since a watch knows
132
+ * only the caller's spelling of the URI, not the server's key. A
133
+ * session's restore and a watch sent again after a reconnect tell the
134
+ * client their answer where it differs, a forgotten URI included; see
135
+ * {@link restoreDirty}.
136
+ */
137
+ protected readonly dirtyStates = new Map<string, boolean>();
138
+ /** Backs each session's {@link DataSessionHost.onDidChangeDirty}. */
139
+ protected readonly dirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
140
+ /** Backs each session's {@link DataSessionHost.onDidUpdateDocument}. */
141
+ protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>>();
142
+ /**
143
+ * Per id {@link watchDocument} watches under, the URI it watches, which
144
+ * {@link generationReady} sends again to every later generation until the
145
+ * watch's handle is disposed.
146
+ */
147
+ protected readonly watches = new Map<string, string>();
148
+ /**
149
+ * Per id, the URI of a watch whose handle was disposed with no ready
150
+ * generation to unwatch on. {@link generationReady} sends the unwatch to the
151
+ * next ready one: a generation that failed its readiness check after its
152
+ * watches were sent leaves them on a connection the port may hand back.
153
+ */
154
+ protected readonly pendingUnwatches = new Map<string, string>();
155
+ /** The port's logger, or one that logs nothing. */
156
+ protected readonly logger: Logger;
157
+ /** Backs {@link onDidReconnect}. */
158
+ protected readonly reconnectEmitter = new Emitter<void>();
159
+ /**
160
+ * Fires on every reconnect: once a connection becomes ready after an
161
+ * earlier one was, and its watches have been sent. The server sends no
162
+ * event for a change made while the connection was down, so a watcher reads
163
+ * its document again on this; a read it sends now reaches the server after
164
+ * its watch.
165
+ */
166
+ readonly onDidReconnect: Event<void> = this.reconnectEmitter.event;
167
+ /** Whether a generation was ready before, which makes the next one a reconnect. */
168
+ protected readyBefore = false;
169
+
170
+ constructor(port: DataPort, client: TClient, ...rest: DataConnectionArgs<TTransfer, TClient, TServer>) {
171
+ const [options = {}] = rest as [
172
+ (DataConnectionOptions<TTransfer, TServer> & Partial<DataConnectionOptionsWithMethods<TClient, TTransfer, TServer>>)?
173
+ ];
174
+ super(port, client, {
175
+ methodNamespace: options.methodNamespace ?? DATA_SERVER_WIRE_PREFIX,
176
+ // The default is reachable only where `TClient` satisfies
177
+ // `DataClientProtocol`, which the constructor's conditional enforces;
178
+ // the compiler cannot carry that through to the generic parameter.
179
+ clientMethods: options.clientMethods ?? (DATA_CLIENT_PROTOCOL_METHODS as unknown as readonly (keyof TClient & string)[]),
180
+ lifecycle: options
181
+ });
182
+ this.sessionFactory =
183
+ options.sessionFactory ?? ((clientId, host, label) => new DataSession<TTransfer, TServer>(clientId, host, label));
184
+ this.logger = (port.logger ?? new NoopLogger()).for('DataConnection');
185
+ }
186
+
187
+ /**
188
+ * The sessions of this connection that have not ended, in the order they
189
+ * started. A session is listed until its `onDidDispose` fires, or until
190
+ * {@link dispose} clears the list.
191
+ */
192
+ get liveSessions(): readonly DataSession<TTransfer, TServer>[] {
193
+ return [...this.sessions];
194
+ }
195
+
196
+ /**
197
+ * Start a participant on this connection, registered with the server under a
198
+ * fresh id, `label` plus `#` plus a random UUID, or under `clientId` when
199
+ * given. Pass a `label` naming the participant; without one it is
200
+ * `session`. Synchronous: the registration is sent at once, and the
201
+ * session's calls wait for it. The server refuses an id live anywhere in
202
+ * its process, and every call of that session then rejects with an error
203
+ * `isDuplicateClientIdError` recognises; an id the server reserves beyond
204
+ * {@link FRAMEWORK_CLIENT_IDS}, such as the integrity author, with one
205
+ * `isReservedClientIdError` recognises. Only the code crosses the wire, so
206
+ * test with those guards rather than `instanceof`.
207
+ *
208
+ * Throws a {@link ReservedClientIdError} for an id in
209
+ * {@link FRAMEWORK_CLIENT_IDS} — those are authors the SERVER emits rather
210
+ * than participants, so a session holding one would read the framework's
211
+ * own broadcasts as its own echoes and drop them — and a
212
+ * {@link DuplicateClientIdError} for an id a live session on this
213
+ * connection already holds.
214
+ */
215
+ createSession(label = 'session', clientId?: string): DataSession<TTransfer, TServer> {
216
+ this.assertLive();
217
+ const id = clientId ?? `${label}#${randomUuid()}`;
218
+ if (FRAMEWORK_CLIENT_IDS.includes(id)) {
219
+ throw new ReservedClientIdError(id);
220
+ }
221
+ if ([...this.sessions].some(session => session.clientId === id)) {
222
+ throw new DuplicateClientIdError(id);
223
+ }
224
+ const session = this.sessionFactory(
225
+ id,
226
+ {
227
+ connected: () => this.connected(),
228
+ reportError: (error, reported) => this.reportError(error, reported),
229
+ restoreDirty: event => this.restoreDirty(event),
230
+ forgetDirty: uri => this.dirtyStates.delete(uri),
231
+ onDidChangeDirty: this.dirtyChangedEmitter.event,
232
+ onDidUpdateDocument: this.documentUpdatedEmitter.event
233
+ },
234
+ label
235
+ );
236
+ this.sessions.add(session);
237
+ // Subscribed before the session is handed out, so the id is free again
238
+ // on this connection by the time any caller's listener runs.
239
+ session.onDidDispose(() => this.sessions.delete(session));
240
+ // A failure reaches the session's own calls, which wait for the same
241
+ // registration; caught here only so it is not also reported unhandled.
242
+ session.connected().catch(() => undefined);
243
+ this.createSessionEmitter.fire(session);
244
+ return session;
245
+ }
246
+
247
+ /**
248
+ * Follow `uri` without opening it: its update events reach this
249
+ * connection's client once this resolves. An open would hold the document
250
+ * for as long as the caller follows it. The watch runs under an id of its
251
+ * own, `label` plus `#` plus a random UUID, and needs no session: a session
252
+ * closing the document would also end its own watch of it. Every later
253
+ * connection that becomes ready gets the watch again. Disposing the handle
254
+ * unwatches.
255
+ */
256
+ async watchDocument(uri: string, label = 'watch'): Promise<Disposable> {
257
+ const clientId = `${label}#${randomUuid()}`;
258
+ const server = await this.connected();
259
+ // Kept only from here: kept during the wait, a generation that became
260
+ // ready meanwhile would send the watch a second time.
261
+ this.watches.set(clientId, uri);
262
+ try {
263
+ await server.watchModelDocument({ uri, clientId });
264
+ } catch (error: unknown) {
265
+ this.watches.delete(clientId);
266
+ throw error;
267
+ }
268
+ this.logger.debug(`Watch ${uri} as ${clientId}`);
269
+ return Disposable.create(() => {
270
+ if (!this.watches.delete(clientId)) {
271
+ return;
272
+ }
273
+ // Without a ready generation the unwatch waits for the next one,
274
+ // rather than opening a connection only for it.
275
+ const unwatchLater = (): void => {
276
+ this.pendingUnwatches.set(clientId, uri);
277
+ };
278
+ const generation = this.generation;
279
+ if (!generation) {
280
+ unwatchLater();
281
+ return;
282
+ }
283
+ (generation.ready ??= this.awaitReady(generation)).then(() => {
284
+ if (this.generation === generation) {
285
+ this.unwatch(generation, clientId, uri);
286
+ } else {
287
+ unwatchLater();
288
+ }
289
+ }, unwatchLater);
290
+ });
291
+ }
292
+
293
+ /**
294
+ * The client, with its `onDocumentDirtyChanged` passing through
295
+ * {@link deliverDirty} first, so {@link dirtyStates} holds what the server
296
+ * told it, and every session hears it through {@link dirtyChangedEmitter};
297
+ * and with its `onDocumentUpdated` heard by every session through
298
+ * {@link documentUpdatedEmitter} first. Every other bound method forwards
299
+ * to the client unchanged, and one the client lacks stays absent, so the
300
+ * binding still refuses it.
301
+ */
302
+ protected override localTarget(): TClient {
303
+ const client = this.client as unknown as Record<string, unknown>;
304
+ const hearsDirty = typeof client.onDocumentDirtyChanged === 'function';
305
+ const hearsUpdates = typeof client.onDocumentUpdated === 'function';
306
+ if (!hearsDirty && !hearsUpdates) {
307
+ return this.client;
308
+ }
309
+ const target: Record<string, unknown> = {};
310
+ for (const name of this.clientMethods) {
311
+ const method: unknown = client[name];
312
+ if (typeof method === 'function') {
313
+ target[name] = (params: unknown): unknown => (method as (params: unknown) => unknown).call(client, params);
314
+ }
315
+ }
316
+ if (hearsDirty) {
317
+ target.onDocumentDirtyChanged = (event: TransferDocumentDirtyChangedEvent): void => {
318
+ this.dirtyChangedEmitter.fire(event);
319
+ this.deliverDirty(event);
320
+ };
321
+ }
322
+ if (hearsUpdates) {
323
+ const forward = target.onDocumentUpdated as (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>) => void;
324
+ target.onDocumentUpdated = (event: TransferDocumentUpdatedEvent<TTransfer, DiagnosticOf<TServer>>): void => {
325
+ this.documentUpdatedEmitter.fire(event);
326
+ forward(event);
327
+ };
328
+ }
329
+ return target as unknown as TClient;
330
+ }
331
+
332
+ /**
333
+ * Hand a dirty state a restore read to the client, unless it is what
334
+ * {@link dirtyStates} says the client was last told; a URI it holds
335
+ * nothing for counts as different.
336
+ */
337
+ protected restoreDirty(event: TransferDocumentDirtyChangedEvent): void {
338
+ if (this.dirtyStates.get(event.uri) !== (event.text?.dirty ?? false)) {
339
+ this.deliverDirty(event);
340
+ }
341
+ }
342
+
343
+ /** Record `event` in {@link dirtyStates} and hand it to the client. */
344
+ protected deliverDirty(event: TransferDocumentDirtyChangedEvent): void {
345
+ this.dirtyStates.set(event.uri, event.text?.dirty ?? false);
346
+ const client = this.client as unknown as Partial<Pick<DataClientProtocol<TTransfer>, 'onDocumentDirtyChanged'>>;
347
+ client.onDocumentDirtyChanged?.(event);
348
+ }
349
+
350
+ /**
351
+ * After the transport dropped, reconnect on the next macrotask for the
352
+ * sessions with documents open, so they re-watch and follow their documents
353
+ * again without waiting for a call of their own, and connect for what
354
+ * {@link watchDocument} watches, which {@link generationReady} places
355
+ * again; a session with nothing open restores on its next call. Nothing is
356
+ * scheduled once this connection is disposed, which drops its generation
357
+ * too.
358
+ */
359
+ protected override dropGeneration(): void {
360
+ const dropped = this.generation !== undefined;
361
+ super.dropGeneration();
362
+ if (dropped && !this.disposed) {
363
+ setTimeout(() => {
364
+ if (!this.disposed) {
365
+ this.reconnectSessions();
366
+ if (this.watches.size > 0) {
367
+ // One generation, not `connected`, which follows a drop to
368
+ // the next: that drop's own timer asks again whether
369
+ // anything is still kept. A failure is reported by the gate.
370
+ const generation = this.currentGeneration();
371
+ (generation.ready ??= this.awaitReady(generation)).catch(() => undefined);
372
+ }
373
+ }
374
+ }, 0);
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Call `reconnect()` on every session, reporting a throw instead of letting
380
+ * one session's restore stop the others and the watches after them, and,
381
+ * inside the readiness gate, fail the whole generation.
382
+ */
383
+ protected reconnectSessions(): void {
384
+ for (const session of this.sessions) {
385
+ try {
386
+ session.reconnect();
387
+ } catch (error: unknown) {
388
+ // Reported, so it reaches the user on a port without a logger;
389
+ // logged too, since only the log names the session.
390
+ this.reportError(error, resolve(DATA_CONNECTION_SESSION_RESTORE_FAILED, { detail: describeError(error) }));
391
+ this.logger.error(`Could not restore session ${session.clientId}: ${describeError(error)}`);
392
+ }
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Restore what the server lost with an earlier generation, whichever
398
+ * request brought this one up: the documents of sessions that have some
399
+ * open, and every watch {@link watchDocument} keeps.
400
+ */
401
+ protected override generationReady(generation: RpcConnectionGeneration<TServer>): void {
402
+ super.generationReady(generation);
403
+ this.reconnectSessions();
404
+ this.watches.forEach((uri, clientId) => this.watchAgain(generation, clientId, uri));
405
+ this.pendingUnwatches.forEach((uri, clientId) => this.unwatch(generation, clientId, uri));
406
+ this.pendingUnwatches.clear();
407
+ if (this.readyBefore) {
408
+ this.reconnectEmitter.fire(undefined);
409
+ }
410
+ this.readyBefore = true;
411
+ }
412
+
413
+ /** Take back the watch of `uri` under `clientId` on `generation`; the server ignores one it does not hold. */
414
+ protected unwatch(generation: RpcConnectionGeneration<TServer>, clientId: string, uri: string): void {
415
+ this.logger.debug(`Unwatch ${uri} as ${clientId}`);
416
+ generation.server.unwatchModelDocument({ uri, clientId }).catch(() => undefined);
417
+ }
418
+
419
+ /**
420
+ * Send the watch of `uri` under `clientId` to `generation`, which has just
421
+ * passed its readiness gate. Sent at once rather than after a wait, so no
422
+ * drop can come between choosing the generation and sending. A failure is
423
+ * reported, since no caller waits on it, only while the watch is kept and
424
+ * `generation` is still current: otherwise the next generation sends it
425
+ * again.
426
+ *
427
+ * Once the watch is in place, the document's dirty state is read and goes
428
+ * through {@link restoreDirty}, as a session's restore does: a flip while
429
+ * the connection was down reached no one.
430
+ */
431
+ protected watchAgain(generation: RpcConnectionGeneration<TServer>, clientId: string, uri: string): void {
432
+ generation.server.watchModelDocument({ uri, clientId }).then(
433
+ () => {
434
+ if (!this.watches.has(clientId)) {
435
+ return;
436
+ }
437
+ this.logger.debug(`Watch ${uri} again as ${clientId}`);
438
+ generation.server.getModelDocument({ uri }).then(
439
+ current => {
440
+ if (current.text && this.watches.has(clientId)) {
441
+ try {
442
+ this.restoreDirty({ uri: current.uri, text: current.text });
443
+ } catch {
444
+ // The client's listener failed, not the watch, which stays kept.
445
+ }
446
+ }
447
+ },
448
+ () => undefined
449
+ );
450
+ },
451
+ (error: unknown) => {
452
+ if (!this.watches.has(clientId)) {
453
+ return;
454
+ }
455
+ if (this.generation !== generation) {
456
+ this.logger.debug(`Watch of ${uri} as ${clientId} cut short by a lost connection; the next one sends it again`);
457
+ return;
458
+ }
459
+ this.reportError(error, resolve(DATA_CONNECTION_WATCH_RESTORE_FAILED, { uri, detail: describeError(error) }));
460
+ }
461
+ );
462
+ }
463
+
464
+ /**
465
+ * Sessions are detached rather than disposed: the server ends every session
466
+ * on a connection it sees close, so ending each one first sends requests
467
+ * over a connection this call is about to dispose.
468
+ */
469
+ override dispose(): void {
470
+ for (const session of [...this.sessions]) {
471
+ session.detach();
472
+ }
473
+ // For a factory's session whose `detach` does not fire.
474
+ this.sessions.clear();
475
+ this.watches.clear();
476
+ this.pendingUnwatches.clear();
477
+ this.createSessionEmitter.dispose();
478
+ this.reconnectEmitter.dispose();
479
+ this.dirtyChangedEmitter.dispose();
480
+ this.documentUpdatedEmitter.dispose();
481
+ super.dispose();
482
+ }
483
+ }
484
+
485
+ /**
486
+ * A {@link DataConnection} that brings its own {@link DataEvents}, so a host
487
+ * with several interested parties does not have to supply one.
488
+ *
489
+ * **The client slot holds exactly one object, and that is why this exists.**
490
+ * `createRpcProxy` binds a single `localTarget`, and underneath a method name
491
+ * maps to one handler — a second registration replaces the first silently. So a
492
+ * properties panel and a tree cannot both be the client; one fan-out sits in the
493
+ * slot and both subscribe to it.
494
+ *
495
+ * Use {@link DataConnection} directly instead when the client is yours: an
496
+ * adopter service that implements the protocol plus its own methods, a single
497
+ * consumer that IS the client, or a request/response-only client that binds
498
+ * nothing.
499
+ */
500
+ export class DataConnectionWithEvents<
501
+ TTransfer extends TransferElement,
502
+ TServer extends DataServerProtocol<TTransfer, DiagnosticOf<TServer>> = DataServerProtocol<TTransfer>
503
+ > extends DataConnection<TTransfer, TServer, DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>> {
504
+ /** Server pushes, fanned out to as many local listeners as the host has. */
505
+ readonly events: DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>;
506
+
507
+ constructor(port: DataPort, options?: DataConnectionOptions<TTransfer, TServer>) {
508
+ // Built as a local because `this` is unavailable before `super`, then
509
+ // read back onto the field.
510
+ const events = new DataEvents<TTransfer, DiagnosticOf<TServer>, ProjectOf<TServer>>();
511
+ super(port, events, options);
512
+ this.events = events;
513
+ }
514
+
515
+ /** Disposes the fan-out it created, which no caller else holds. */
516
+ override dispose(): void {
517
+ super.dispose();
518
+ this.events.dispose();
519
+ }
520
+ }
@@ -8,7 +8,15 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { Emitter, type Event } from 'vscode-jsonrpc';
11
- import type { DataClientProtocol, ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from '../data';
11
+ import type {
12
+ DataClientProtocol,
13
+ ProjectsChangedEvent,
14
+ TransferDocumentDeletedEvent,
15
+ TransferDocumentDirtyChangedEvent,
16
+ TransferDocumentSavedEvent,
17
+ TransferDocumentsBuiltEvent,
18
+ TransferDocumentUpdatedEvent
19
+ } from '../data';
12
20
  import type { Project } from '../project';
13
21
  import type { TransferDiagnostic } from '../transfer-diagnostic';
14
22
  import type { TransferElement } from '../transfer-element';
@@ -40,12 +48,21 @@ export class DataEvents<
40
48
  > implements DataClientProtocol<TTransfer, TDiagnostic, TProject> {
41
49
  protected readonly documentUpdatedEmitter = new Emitter<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>>();
42
50
  protected readonly documentSavedEmitter = new Emitter<TransferDocumentSavedEvent<TTransfer, TDiagnostic>>();
51
+ protected readonly documentDirtyChangedEmitter = new Emitter<TransferDocumentDirtyChangedEvent>();
52
+ protected readonly documentDeletedEmitter = new Emitter<TransferDocumentDeletedEvent>();
53
+ protected readonly documentsBuiltEmitter = new Emitter<TransferDocumentsBuiltEvent>();
43
54
  protected readonly projectsChangedEmitter = new Emitter<ProjectsChangedEvent<TProject>>();
44
55
 
45
56
  /** A build-phase event for a watched document. Carries the originating `sourceClientId`. */
46
57
  readonly onDidUpdateDocument: Event<TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>> = this.documentUpdatedEmitter.event;
47
58
  /** A watched document was persisted to disk. */
48
59
  readonly onDidSaveDocument: Event<TransferDocumentSavedEvent<TTransfer, TDiagnostic>> = this.documentSavedEmitter.event;
60
+ /** A watched document's text started or stopped differing from its file. */
61
+ readonly onDidChangeDocumentDirty: Event<TransferDocumentDirtyChangedEvent> = this.documentDirtyChangedEmitter.event;
62
+ /** A document's backing file was removed, watched or not. Any watch survives. */
63
+ readonly onDidDeleteDocument: Event<TransferDocumentDeletedEvent> = this.documentDeletedEmitter.event;
64
+ /** Documents built that nobody watches — re-read anything derived from them. */
65
+ readonly onDidBuildDocuments: Event<TransferDocumentsBuiltEvent> = this.documentsBuiltEmitter.event;
49
66
  /** The project set changed. */
50
67
  readonly onDidChangeProjects: Event<ProjectsChangedEvent<TProject>> = this.projectsChangedEmitter.event;
51
68
 
@@ -59,6 +76,18 @@ export class DataEvents<
59
76
  this.documentSavedEmitter.fire(event);
60
77
  }
61
78
 
79
+ onDocumentDirtyChanged(event: TransferDocumentDirtyChangedEvent): void {
80
+ this.documentDirtyChangedEmitter.fire(event);
81
+ }
82
+
83
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void {
84
+ this.documentDeletedEmitter.fire(event);
85
+ }
86
+
87
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void {
88
+ this.documentsBuiltEmitter.fire(event);
89
+ }
90
+
62
91
  onProjectsChanged(event: ProjectsChangedEvent<TProject>): void {
63
92
  this.projectsChangedEmitter.fire(event);
64
93
  }
@@ -66,6 +95,9 @@ export class DataEvents<
66
95
  dispose(): void {
67
96
  this.documentUpdatedEmitter.dispose();
68
97
  this.documentSavedEmitter.dispose();
98
+ this.documentDirtyChangedEmitter.dispose();
99
+ this.documentDeletedEmitter.dispose();
100
+ this.documentsBuiltEmitter.dispose();
69
101
  this.projectsChangedEmitter.dispose();
70
102
  }
71
103
  }