@hydranium/protocol 1.0.0-next.12 → 1.0.0-next.123

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 (142) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +114 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +143 -0
  5. package/lib/client/data-connection.js.map +1 -0
  6. package/lib/client/data-events.d.ts +9 -1
  7. package/lib/client/data-events.d.ts.map +1 -1
  8. package/lib/client/data-events.js +14 -0
  9. package/lib/client/data-events.js.map +1 -1
  10. package/lib/client/data-port.d.ts +17 -22
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +235 -82
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +337 -108
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +10 -7
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +10 -7
  19. package/lib/client/index.js.map +1 -1
  20. package/lib/client/message-relay.d.ts +8 -2
  21. package/lib/client/message-relay.d.ts.map +1 -1
  22. package/lib/client/message-relay.js +10 -4
  23. package/lib/client/message-relay.js.map +1 -1
  24. package/lib/client/rpc-connection.d.ts +143 -0
  25. package/lib/client/rpc-connection.d.ts.map +1 -0
  26. package/lib/client/rpc-connection.js +171 -0
  27. package/lib/client/rpc-connection.js.map +1 -0
  28. package/lib/client-ids.d.ts +41 -0
  29. package/lib/client-ids.d.ts.map +1 -0
  30. package/lib/client-ids.js +44 -0
  31. package/lib/client-ids.js.map +1 -0
  32. package/lib/data/data-protocol-methods.d.ts +4 -4
  33. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  34. package/lib/data/data-protocol-methods.js +10 -1
  35. package/lib/data/data-protocol-methods.js.map +1 -1
  36. package/lib/data/data-server-protocol.d.ts +100 -31
  37. package/lib/data/data-server-protocol.d.ts.map +1 -1
  38. package/lib/data/events.d.ts +70 -3
  39. package/lib/data/events.d.ts.map +1 -1
  40. package/lib/data/requests.d.ts +67 -11
  41. package/lib/data/requests.d.ts.map +1 -1
  42. package/lib/errors.d.ts +91 -12
  43. package/lib/errors.d.ts.map +1 -1
  44. package/lib/errors.js +127 -18
  45. package/lib/errors.js.map +1 -1
  46. package/lib/index.d.ts +2 -0
  47. package/lib/index.d.ts.map +1 -1
  48. package/lib/index.js +5 -0
  49. package/lib/index.js.map +1 -1
  50. package/lib/latency-collector.d.ts +8 -4
  51. package/lib/latency-collector.d.ts.map +1 -1
  52. package/lib/latency-collector.js.map +1 -1
  53. package/lib/messages/index.d.ts +29 -0
  54. package/lib/messages/index.d.ts.map +1 -0
  55. package/lib/messages/index.js +55 -0
  56. package/lib/messages/index.js.map +1 -0
  57. package/lib/messages/primitives.d.ts +188 -0
  58. package/lib/messages/primitives.d.ts.map +1 -0
  59. package/lib/messages/primitives.js +161 -0
  60. package/lib/messages/primitives.js.map +1 -0
  61. package/lib/model-server.d.ts +44 -13
  62. package/lib/model-server.d.ts.map +1 -1
  63. package/lib/model-server.js +4 -2
  64. package/lib/model-server.js.map +1 -1
  65. package/lib/model-service/based-on.d.ts +57 -0
  66. package/lib/model-service/based-on.d.ts.map +1 -0
  67. package/lib/model-service/based-on.js +37 -0
  68. package/lib/model-service/based-on.js.map +1 -0
  69. package/lib/model-service/index.d.ts +1 -1
  70. package/lib/model-service/index.d.ts.map +1 -1
  71. package/lib/model-service/index.js +4 -5
  72. package/lib/model-service/index.js.map +1 -1
  73. package/lib/patch-merge.d.ts +28 -27
  74. package/lib/patch-merge.d.ts.map +1 -1
  75. package/lib/patch-merge.js +66 -22
  76. package/lib/patch-merge.js.map +1 -1
  77. package/lib/profile-session.d.ts +8 -4
  78. package/lib/profile-session.d.ts.map +1 -1
  79. package/lib/profile-session.js.map +1 -1
  80. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  81. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  82. package/lib/rpc/bind-rpc-methods.js +22 -3
  83. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  84. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  85. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  86. package/lib/rpc/create-rpc-proxy.js +6 -1
  87. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  88. package/lib/testing/catalogue-audit.d.ts +80 -0
  89. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  90. package/lib/testing/catalogue-audit.js +94 -0
  91. package/lib/testing/catalogue-audit.js.map +1 -0
  92. package/lib/testing/data-doubles.d.ts +11 -12
  93. package/lib/testing/data-doubles.d.ts.map +1 -1
  94. package/lib/testing/data-doubles.js +14 -5
  95. package/lib/testing/data-doubles.js.map +1 -1
  96. package/lib/testing/index.d.ts +1 -0
  97. package/lib/testing/index.d.ts.map +1 -1
  98. package/lib/testing/index.js +4 -1
  99. package/lib/testing/index.js.map +1 -1
  100. package/lib/transfer-diagnostic.d.ts +33 -0
  101. package/lib/transfer-diagnostic.d.ts.map +1 -1
  102. package/lib/transfer-diagnostic.js +23 -0
  103. package/lib/transfer-diagnostic.js.map +1 -1
  104. package/lib/transfer-document.d.ts +14 -5
  105. package/lib/transfer-document.d.ts.map +1 -1
  106. package/lib/transfer-document.js +14 -1
  107. package/lib/transfer-document.js.map +1 -1
  108. package/package.json +11 -2
  109. package/src/client/data-connection.ts +216 -0
  110. package/src/client/data-events.ts +24 -1
  111. package/src/client/data-port.ts +17 -23
  112. package/src/client/data-session.ts +447 -128
  113. package/src/client/index.ts +10 -7
  114. package/src/client/message-relay.ts +28 -6
  115. package/src/client/rpc-connection.ts +235 -0
  116. package/src/client-ids.ts +45 -0
  117. package/src/data/data-protocol-methods.ts +10 -3
  118. package/src/data/data-server-protocol.ts +119 -31
  119. package/src/data/events.ts +74 -3
  120. package/src/data/requests.ts +71 -11
  121. package/src/errors.ts +139 -20
  122. package/src/index.ts +5 -0
  123. package/src/latency-collector.ts +8 -3
  124. package/src/messages/index.ts +36 -0
  125. package/src/messages/primitives.ts +271 -0
  126. package/src/model-server.ts +47 -18
  127. package/src/model-service/based-on.ts +63 -0
  128. package/src/model-service/index.ts +4 -5
  129. package/src/patch-merge.ts +90 -37
  130. package/src/profile-session.ts +9 -4
  131. package/src/rpc/bind-rpc-methods.ts +49 -4
  132. package/src/rpc/create-rpc-proxy.ts +14 -1
  133. package/src/testing/catalogue-audit.ts +111 -0
  134. package/src/testing/data-doubles.ts +33 -17
  135. package/src/testing/index.ts +4 -1
  136. package/src/transfer-diagnostic.ts +40 -0
  137. package/src/transfer-document.ts +21 -6
  138. package/lib/model-service/args.d.ts +0 -64
  139. package/lib/model-service/args.d.ts.map +0 -1
  140. package/lib/model-service/args.js +0 -11
  141. package/lib/model-service/args.js.map +0 -1
  142. package/src/model-service/args.ts +0 -67
@@ -13,8 +13,9 @@
13
13
  *
14
14
  * Where `./data` is the wire *contract* and `./rpc` is the machinery that lowers
15
15
  * it onto a connection, this is what a client wraps around both: the seam a host
16
- * fills in (`DataPort`), the lifecycle above it (`DataSession` —
17
- * readiness gate, open/watch ordering, echo recognition, reconnect), the inbound
16
+ * fills in (`DataPort`), the connection above it (`DataConnection` — readiness
17
+ * gate and reconnect), the participants on that connection (`DataSession` —
18
+ * identity, open/watch ordering, echo recognition), the inbound
18
19
  * fan-out (`DataEvents`), and the two halves of the hop for hosts whose
19
20
  * client cannot hold a socket — `createPostMessageTransport` on the client
20
21
  * side and `relayToPostMessageChannel` on the side that does hold it.
@@ -26,15 +27,17 @@
26
27
  * carries the entries.
27
28
  *
28
29
  * The Theia-specific mounting of the same contract lives in
29
- * `@hydranium/data-client-theia`: its `AbstractDataServiceFrontend` solves the
30
- * same problem against Theia's channel transport, and its `EmitterDataClient`
31
- * is the Theia-bound counterpart of `DataEvents`. Prefer this tier for
32
- * anything new, and reach for the Theia package only for what genuinely needs
33
- * Theia DI.
30
+ * `@hydranium/data-client-theia`, and is now only the TRANSPORT: its
31
+ * `ChannelDataPort` fills the `DataPort` seam over a Theia channel, and its
32
+ * `EmitterDataClient` is the Theia-bound counterpart of `DataEvents`.
33
+ * Everything above the port is here, so a Theia frontend and a browser page
34
+ * differ by which port they construct and nothing else.
34
35
  */
35
36
 
37
+ export * from './data-connection';
36
38
  export * from './data-events';
37
39
  export * from './data-port';
38
40
  export * from './data-session';
39
41
  export * from './message-relay';
40
42
  export * from './post-message-transport';
43
+ export * from './rpc-connection';
@@ -8,8 +8,29 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { Emitter, type Disposable, type Event, type Message, type MessageReader, type MessageWriter } from 'vscode-jsonrpc';
11
+ import { defineMessage, describeError, resolve, type ResolvedMessage } from '../messages/primitives';
11
12
  import type { PostMessageChannel } from './post-message-transport';
12
13
 
14
+ export const RELAY_TRANSPORT_OPEN_FAILED = defineMessage(
15
+ 'hydranium/protocol/relay-transport-open-failed',
16
+ 'Could not open the transport to relay: {detail}'
17
+ );
18
+
19
+ export const RELAY_TRANSPORT_READ_FAILED = defineMessage(
20
+ 'hydranium/protocol/relay-transport-read-failed',
21
+ 'Could not read from the relayed transport: {detail}'
22
+ );
23
+
24
+ export const RELAY_TRANSPORT_WRITE_FAILED = defineMessage(
25
+ 'hydranium/protocol/relay-transport-write-failed',
26
+ 'Could not write to the relayed transport: {detail}'
27
+ );
28
+
29
+ export const RELAY_REPLAY_FAILED = defineMessage(
30
+ 'hydranium/protocol/relay-replay-failed',
31
+ 'Could not replay a buffered message to the relayed transport: {detail}'
32
+ );
33
+
13
34
  /**
14
35
  * The framed side of a relay: the reader/writer pair over whatever transport the
15
36
  * host actually holds — a TCP socket to the data-server, a child process' stdio,
@@ -30,13 +51,14 @@ export interface RelayTransport {
30
51
  export interface MessageRelayOptions {
31
52
  /**
32
53
  * Surface a failure the way the host does. Same contract as
33
- * `DataPort.reportError`: `context` names what was being attempted.
54
+ * `DataPort.reportError`: `reported` is a complete sentence plus the identity
55
+ * needed to render it in another language.
34
56
  *
35
57
  * A relay has no other way to report — it sits between two transports and
36
58
  * owns neither, so a swallowed error here presents as a form that never
37
59
  * populates.
38
60
  */
39
- readonly reportError?: (error: unknown, context: string) => void;
61
+ readonly reportError?: (error: unknown, reported: ResolvedMessage) => void;
40
62
  }
41
63
 
42
64
  /** A live relay. Dispose to tear both directions down. */
@@ -143,7 +165,7 @@ export function relayToPostMessageChannel(
143
165
  bufferSubscription?.dispose();
144
166
  bufferSubscription = undefined;
145
167
  buffered.length = 0;
146
- options.reportError?.(error, 'opening the transport to relay');
168
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_OPEN_FAILED, { detail: describeError(error) }));
147
169
  closeFramedSide();
148
170
  return false;
149
171
  }
@@ -166,12 +188,12 @@ export function relayToPostMessageChannel(
166
188
  opened.reader.listen(message => channel.post(message)),
167
189
  opened.reader.onClose(() => closeFramedSide()),
168
190
  opened.reader.onError(error => {
169
- options.reportError?.(error, 'reading from the relayed transport');
191
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_READ_FAILED, { detail: describeError(error) }));
170
192
  closeFramedSide();
171
193
  }),
172
194
  channel.onMessage(message => {
173
195
  void opened.writer.write(message).catch((error: unknown) => {
174
- options.reportError?.(error, 'writing to the relayed transport');
196
+ options.reportError?.(error, resolve(RELAY_TRANSPORT_WRITE_FAILED, { detail: describeError(error) }));
175
197
  });
176
198
  })
177
199
  );
@@ -183,7 +205,7 @@ export function relayToPostMessageChannel(
183
205
 
184
206
  for (const message of buffered) {
185
207
  void opened.writer.write(message).catch((error: unknown) => {
186
- options.reportError?.(error, 'replaying a buffered message to the relayed transport');
208
+ options.reportError?.(error, resolve(RELAY_REPLAY_FAILED, { detail: describeError(error) }));
187
209
  });
188
210
  }
189
211
  buffered.length = 0;
@@ -0,0 +1,235 @@
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 type { MessageConnection } from 'vscode-jsonrpc';
11
+ import { type ResolvedMessage, defineMessage, describeError, resolve } from '../messages/primitives';
12
+ import { type RpcProxy, createRpcProxy } from '../rpc';
13
+ import type { DataPort } from './data-port';
14
+
15
+ /**
16
+ * The transport never opened. A complete sentence rather than a fragment: a
17
+ * fragment is nested inside a sentence the framework does not own, so no
18
+ * translator controls the whole and the composition cannot be made to read
19
+ * correctly in every language.
20
+ */
21
+ export const DATA_SERVER_CONNECT_FAILED = defineMessage(
22
+ 'hydranium/protocol/data-server-connect-failed',
23
+ 'Could not connect to the data server: {detail}'
24
+ );
25
+
26
+ export const DATA_SERVER_NOT_READY = defineMessage(
27
+ 'hydranium/protocol/data-server-not-ready',
28
+ 'The data server did not become ready: {detail}'
29
+ );
30
+
31
+ /** The one method a connection needs of any server: its startup gate. */
32
+ export interface ReadyServer {
33
+ waitForReady(): Promise<void>;
34
+ }
35
+
36
+ /**
37
+ * Lifecycle reporting, for a host that raises warm-up UI around the two waits.
38
+ *
39
+ * Nothing fires until something asks for the connection — the generation is
40
+ * built on the first {@link RpcConnection.connected}. A host that wants the
41
+ * sequence at startup drives that call itself, or a workspace where nobody
42
+ * opens a document reports neither the connect nor the readiness its UI waits
43
+ * on.
44
+ */
45
+ export interface RpcConnectionLifecycle {
46
+ /** A generation is opening its transport, including on each reconnect. */
47
+ readonly onConnecting?: () => void;
48
+ /** The server's readiness gate has settled for a generation. */
49
+ readonly onReady?: () => void;
50
+ /**
51
+ * A generation failed to connect or to become ready. The failure is still
52
+ * reported through {@link DataPort.reportError} and still rejects the
53
+ * awaiting caller; this is for a host that also drives its own UI.
54
+ */
55
+ readonly onFailed?: (error: unknown) => void;
56
+ }
57
+
58
+ /** Everything {@link RpcConnection} needs once a subclass has resolved its defaults. */
59
+ export interface ResolvedRpcConnectionOptions<TClient extends object> {
60
+ readonly methodNamespace: string;
61
+ readonly clientMethods: readonly (keyof TClient & string)[];
62
+ readonly lifecycle: RpcConnectionLifecycle;
63
+ }
64
+
65
+ /**
66
+ * One connection generation: its connection, its proxy, and its readiness.
67
+ *
68
+ * Named by the `protected` reconnect seams {@link RpcConnection.currentGeneration}
69
+ * and {@link RpcConnection.awaitReady}, so an override has to name it too.
70
+ */
71
+ export interface RpcConnectionGeneration<TServer extends object> {
72
+ readonly connection: Promise<MessageConnection>;
73
+ readonly server: RpcProxy<TServer>;
74
+ /** Set on first use; the shared readiness gate for this generation. */
75
+ ready?: Promise<void>;
76
+ }
77
+
78
+ /**
79
+ * One JSON-RPC connection to a head, with the three jobs every host adapter
80
+ * would otherwise re-derive above {@link DataPort}:
81
+ *
82
+ * 1. **Build the typed proxy** over the port's connection, with the caller's
83
+ * wire prefix and client-method allowlist.
84
+ * 2. **Own the readiness gate** — `waitForReady` once per connection, shared
85
+ * across concurrent callers. A client can connect before the workspace walk
86
+ * finishes, and an early request is then answered correctly from an empty
87
+ * registry, which reads as a broken project tier rather than as a race.
88
+ * 3. **Own the reconnect policy**, by dropping its generation when the port
89
+ * disposes and building a fresh one on the next request.
90
+ *
91
+ * Bounded only by {@link ReadyServer}, so a head serving a slice of the data
92
+ * protocol — diagnostics alone, or one with methods excluded — is still a
93
+ * legal server here. `DataConnection` narrows the bound because its sessions
94
+ * call the document methods; nothing at this layer does.
95
+ */
96
+ export class RpcConnection<TServer extends ReadyServer, TClient extends object> {
97
+ protected readonly methodNamespace: string;
98
+ protected readonly clientMethods: readonly (keyof TClient & string)[];
99
+ protected readonly lifecycle: RpcConnectionLifecycle;
100
+ /** The current generation, or `undefined` before the first request / after a teardown. */
101
+ protected generation?: RpcConnectionGeneration<TServer>;
102
+ protected disposed = false;
103
+ protected readonly portDisposeListener: { dispose(): void };
104
+
105
+ constructor(
106
+ protected readonly port: DataPort,
107
+ protected readonly client: TClient,
108
+ options: ResolvedRpcConnectionOptions<TClient>
109
+ ) {
110
+ this.methodNamespace = options.methodNamespace;
111
+ this.clientMethods = options.clientMethods;
112
+ this.lifecycle = options.lifecycle;
113
+ this.portDisposeListener = this.port.onDispose(() => this.dropGeneration());
114
+ }
115
+
116
+ /**
117
+ * The connected, READY server proxy.
118
+ *
119
+ * Returns the proxy rather than `void` on purpose. A reconnect replaces the
120
+ * proxy, so a caller that cached one from an earlier call would go on
121
+ * addressing a dead connection with no error — handing it back per call
122
+ * makes the stale reference unrepresentable.
123
+ *
124
+ * Concurrent callers share one readiness promise, so `waitForReady` is
125
+ * awaited once per generation and not once per caller.
126
+ */
127
+ async connected(): Promise<RpcProxy<TServer>> {
128
+ this.assertLive();
129
+ const generation = this.currentGeneration();
130
+ if (!generation.ready) {
131
+ generation.ready = this.awaitReady(generation);
132
+ }
133
+ await generation.ready;
134
+ return generation.server;
135
+ }
136
+
137
+ /**
138
+ * The current generation's proxy WITHOUT awaiting readiness — calls queue
139
+ * against the connection promise.
140
+ *
141
+ * **Protected, and that is the point.** An early request is answered
142
+ * correctly from a registry the workspace walk has not filled yet, which
143
+ * reads as a broken project tier rather than as a race — so every caller has
144
+ * to interpose the gate, and every caller forgetting to is a silent bug.
145
+ * {@link connected} is the public route and returns this same proxy once the
146
+ * gate has settled, which leaves nothing to forget. The one caller that
147
+ * cannot use it is {@link awaitReady}, whose whole job is running the gate.
148
+ *
149
+ * Read per access, never cached: a reconnect replaces the generation, and a
150
+ * held reference would address the dead one.
151
+ */
152
+ protected get server(): RpcProxy<TServer> {
153
+ this.assertLive();
154
+ return this.currentGeneration().server;
155
+ }
156
+
157
+ /**
158
+ * Surface a failure the way this host does, through the port's sink.
159
+ *
160
+ * Here rather than only on the port so every participant sharing the
161
+ * connection reports through one route without being handed the transport.
162
+ */
163
+ reportError(error: unknown, reported: ResolvedMessage): void {
164
+ this.port.reportError(error, reported);
165
+ }
166
+
167
+ /** Tear down the current connection and stop tracking the port. Idempotent. */
168
+ dispose(): void {
169
+ if (this.disposed) {
170
+ return;
171
+ }
172
+ this.disposed = true;
173
+ this.portDisposeListener.dispose();
174
+ this.dropGeneration();
175
+ }
176
+
177
+ /** The live generation, building one if there is none. */
178
+ protected currentGeneration(): RpcConnectionGeneration<TServer> {
179
+ if (this.generation) {
180
+ return this.generation;
181
+ }
182
+ this.lifecycle.onConnecting?.();
183
+ const connection = this.port.connect();
184
+ // Rejection is reported here rather than left to float: an unhandled
185
+ // rejection on a connection promise is the failure mode that reads as
186
+ // "the model is empty" instead of "the transport never opened".
187
+ connection.catch((error: unknown) =>
188
+ this.port.reportError(error, resolve(DATA_SERVER_CONNECT_FAILED, { detail: describeError(error) }))
189
+ );
190
+ const server = createRpcProxy<TServer, TClient>(connection, {
191
+ methodNamespace: this.methodNamespace,
192
+ localTarget: this.client,
193
+ localMethods: this.clientMethods
194
+ });
195
+ this.generation = { connection, server };
196
+ return this.generation;
197
+ }
198
+
199
+ /** Await the connection and the server's startup gate for one generation. */
200
+ protected async awaitReady(generation: RpcConnectionGeneration<TServer>): Promise<void> {
201
+ try {
202
+ await generation.connection;
203
+ await generation.server.waitForReady();
204
+ this.lifecycle.onReady?.();
205
+ } catch (error: unknown) {
206
+ this.lifecycle.onFailed?.(error);
207
+ // Drop the generation so the next request retries rather than
208
+ // re-awaiting a settled rejection forever.
209
+ if (this.generation === generation) {
210
+ this.generation = undefined;
211
+ }
212
+ this.port.reportError(error, resolve(DATA_SERVER_NOT_READY, { detail: describeError(error) }));
213
+ throw error;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Discard the current generation, disposing its connection if it opened.
219
+ * The next {@link connected} builds a fresh one.
220
+ */
221
+ protected dropGeneration(): void {
222
+ const generation = this.generation;
223
+ this.generation = undefined;
224
+ if (!generation) {
225
+ return;
226
+ }
227
+ generation.connection.then(connection => connection.dispose()).catch(() => undefined);
228
+ }
229
+
230
+ protected assertLive(): void {
231
+ if (this.disposed) {
232
+ throw new Error(`${this.constructor.name} is disposed`);
233
+ }
234
+ }
235
+ }
@@ -0,0 +1,45 @@
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
+ /**
11
+ * Well-known values of the wire's `clientId` / `sourceClientId` field.
12
+ *
13
+ * The framework tracks each document as belonging to one or more "clients" —
14
+ * typically an LSP-text client (Monaco, VS Code, …), a GLSP diagram client,
15
+ * and/or a structured-form client — and keys its holds and watches per
16
+ * `(uri, clientId)`. These three values are not real participants, so a client
17
+ * minting its own id must avoid them.
18
+ *
19
+ * **Here rather than in the server package, because the side that has to
20
+ * RECOGNISE them is the client.** An inbound `onDocumentUpdated` carries
21
+ * `sourceClientId`, and a consumer deciding what to do with it is asking which
22
+ * of these it is — so a frontend would otherwise have to depend on the server
23
+ * tier to name three strings, and in practice retypes the literal instead.
24
+ */
25
+
26
+ /** Identifier for an LSP-text client (Monaco, VS Code, …). */
27
+ export const LANGUAGE_CLIENT_ID = 'language-client';
28
+
29
+ /** Fallback identifier when a document's author is unknown (e.g. cold workspace-init load). */
30
+ export const UNKNOWN_CLIENT_ID = 'unknown';
31
+
32
+ /**
33
+ * Synthetic author id on the `onDocumentUpdated` broadcast a data-server
34
+ * emits after the LAST client closed a document and the framework rebuilt it
35
+ * from its disk content (discarding unsaved in-session edits). Not a real
36
+ * client: it lets consumers distinguish the revert broadcast from
37
+ * client-authored updates.
38
+ */
39
+ export const REVERT_ON_CLOSE_CLIENT_ID = 'revert-on-close';
40
+
41
+ /**
42
+ * Every id the framework reserves, for a client checking that the identity it
43
+ * is about to mint collides with none of them.
44
+ */
45
+ export const FRAMEWORK_CLIENT_IDS: readonly string[] = [LANGUAGE_CLIENT_ID, UNKNOWN_CLIENT_ID, REVERT_ON_CLOSE_CLIENT_ID];
@@ -20,6 +20,10 @@ import type {
20
20
 
21
21
  /** Request-method names on {@link DocumentServerProtocol}. */
22
22
  export const DOCUMENT_SERVER_PROTOCOL_METHODS = [
23
+ 'createSession',
24
+ 'closeSession',
25
+ 'createModelDocument',
26
+ 'updateModelDocuments',
23
27
  'openModelDocument',
24
28
  'closeModelDocument',
25
29
  'getModelDocument',
@@ -59,9 +63,12 @@ export const REFERENCE_SERVER_PROTOCOL_METHODS = [
59
63
  ] as const satisfies ReadonlyArray<keyof ReferenceServerProtocol<TransferElement> & string>;
60
64
 
61
65
  /** Notification-method names on {@link DocumentClientProtocol}. */
62
- export const DOCUMENT_CLIENT_PROTOCOL_METHODS = ['onDocumentUpdated', 'onDocumentSaved'] as const satisfies ReadonlyArray<
63
- keyof DocumentClientProtocol<TransferElement> & string
64
- >;
66
+ export const DOCUMENT_CLIENT_PROTOCOL_METHODS = [
67
+ 'onDocumentUpdated',
68
+ 'onDocumentSaved',
69
+ 'onDocumentDeleted',
70
+ 'onDocumentsBuilt'
71
+ ] as const satisfies ReadonlyArray<keyof DocumentClientProtocol<TransferElement> & string>;
65
72
 
66
73
  /** Notification-method names on {@link ProjectClientProtocol}. */
67
74
  export const PROJECT_CLIENT_PROTOCOL_METHODS = ['onProjectsChanged'] as const satisfies ReadonlyArray<keyof ProjectClientProtocol & string>;
@@ -13,13 +13,23 @@ import type { Project } from '../project';
13
13
  import type { TransferDocument } from '../transfer-document';
14
14
  import type { CloseModelArgs, FindNextNameArgs, OpenModelArgs, ReferenceContext, ReferenceRequest } from '../model-server';
15
15
  import type { ReferenceCandidate, ReferenceTarget } from '../model-service/reference-candidate';
16
- import type { ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from './events';
17
16
  import type {
17
+ ProjectsChangedEvent,
18
+ TransferDocumentDeletedEvent,
19
+ TransferDocumentSavedEvent,
20
+ TransferDocumentsBuiltEvent,
21
+ TransferDocumentUpdatedEvent
22
+ } from './events';
23
+ import type {
24
+ CloseSessionArgs,
25
+ CreateModelDocumentArgs,
26
+ CreateSessionArgs,
18
27
  GetModelDocumentArgs,
19
28
  GetProjectForUriArgs,
20
29
  TransferSaveDocumentArgs,
21
30
  WatchModelDocumentArgs,
22
- TransferUpdateDocumentArgs
31
+ TransferUpdateDocumentArgs,
32
+ TransferUpdateDocumentsArgs
23
33
  } from './requests';
24
34
 
25
35
  /**
@@ -40,35 +50,74 @@ import type {
40
50
  */
41
51
  export interface DocumentServerProtocol<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic = TransferDiagnostic> {
42
52
  /**
43
- * Open a document for an editor session and return its current state.
44
- * Registers `(uri, clientId)` with the multi-client document manager
45
- * (so concurrent editors share one built document) and returns the
46
- * document at the server's configured target phase — the same shape
47
- * {@link getModelDocument} returns, except that `version` is taken from
48
- * the text-document store so the caller's first `baseVersion` write
49
- * cannot self-conflict. Idempotent in registration terms: opening an
50
- * already-open document refreshes the client registration. Note it does
51
- * NOT avoid a rebuild — a second client attaching triggers
52
- * `refreshContent`, which fires a change event, so mounting a form on a
53
- * document already open in a text editor rebuilds it.
53
+ * Register `args.clientId` as a client session owned by this connection.
54
+ * Rejects with a `DuplicateClientIdError` code when the id is live anywhere
55
+ * in the server process or reserved by the framework.
56
+ *
57
+ * A request carrying a registered id acts as that session: it writes only
58
+ * what the session has open, failing with a `DocumentNotOpenError` code
59
+ * otherwise, and opens nothing implicitly; its open reads the file and takes
60
+ * no `languageId`, `version` or `text` seed. The session ends with
61
+ * {@link closeSession} or when the connection closes, and either closes
62
+ * every document it has open.
54
63
  *
55
- * The default `DataServer` impl delegates to `ModelService.open` then
56
- * reads the built state. Pair with {@link watchModelDocument} to receive
57
- * subsequent build-phase events (open returns a one-shot snapshot;
58
- * later validation diagnostics arrive on the watch channel).
64
+ * A registration carrying the `resumeToken` an earlier registration of the
65
+ * same id carried ends that session first, from any connection, so a client
66
+ * whose connection dropped can register again before the server notices.
67
+ */
68
+ createSession(args: CreateSessionArgs): Promise<void>;
69
+
70
+ /**
71
+ * End a session this connection registered: close every document it has
72
+ * open, drop its watches, and free its id. A no-op for an id this
73
+ * connection did not register.
74
+ */
75
+ closeSession(args: CloseSessionArgs): Promise<void>;
76
+
77
+ /**
78
+ * Create a document with `args.text`, open for the session, and return it
79
+ * as {@link openModelDocument} does. It reaches disk with the first save.
80
+ * Fails when the file exists or any client has the URI open, and with a
81
+ * `SessionClosedError` code when `args.clientId` is not a session
82
+ * registered on this connection.
59
83
  */
60
- openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
84
+ createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
61
85
 
62
86
  /**
63
- * Close an editor session for `(uri, clientId)`. Counterpart to
64
- * {@link openModelDocument}; the underlying document stays built until
65
- * every registered client has closed. The default `DataServer` impl
66
- * delegates to `ModelService.close` and ALSO releases any watch for the
67
- * same `(uri, clientId)` (closing a session frees its own watch — a
68
- * forgotten {@link unwatchModelDocument} would otherwise leak dispatch;
69
- * the implicit unwatch is idempotent). `watchModelDocument` is NOT
70
- * coupled the other way: opening does not force a watch, so a snapshot
71
- * reader can open without streaming.
87
+ * Write several documents the session has open, all or none: a conflict or
88
+ * a document not open fails the whole set before any text applies.
89
+ * Resolves to the documents in the order given. Only for a session
90
+ * registered on this connection.
91
+ */
92
+ updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]>;
93
+
94
+ /**
95
+ * Open a document for the client session `clientId` and return its current
96
+ * state. `clientId` must be a session this connection registered with
97
+ * {@link createSession}; any other id fails with the closed-session code,
98
+ * as every document request here does. The document is read from disk
99
+ * unless a client has it open already, so the request carries no
100
+ * `languageId`, `version` or `text` seed. Returns the document at
101
+ * the server's configured target phase — the same shape
102
+ * {@link getModelDocument} returns, except that `version` is taken from the
103
+ * text-document store so the caller's first `basedOn` write cannot
104
+ * self-conflict. A repeat open changes nothing.
105
+ *
106
+ * Pair with {@link watchModelDocument} to receive subsequent build-phase
107
+ * events (open returns a one-shot snapshot; later validation diagnostics
108
+ * arrive on the watch channel).
109
+ */
110
+ openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
111
+
112
+ /**
113
+ * Close the session's open of `uri`. Counterpart to
114
+ * {@link openModelDocument}; the document stays open until every client
115
+ * has closed it, and the last close reverts it to disk. The default
116
+ * `DataServer` impl ALSO releases any watch for the same
117
+ * `(uri, clientId)` (a forgotten {@link unwatchModelDocument} would
118
+ * otherwise leak dispatch; the implicit unwatch is idempotent).
119
+ * `watchModelDocument` is NOT coupled the other way: opening does not force
120
+ * a watch, so a snapshot reader can open without streaming.
72
121
  */
73
122
  closeModelDocument(args: CloseModelArgs): Promise<void>;
74
123
 
@@ -81,14 +130,15 @@ export interface DocumentServerProtocol<TTransfer extends TransferElement, TDiag
81
130
  getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
82
131
 
83
132
  /**
84
- * Update a document's content. The response carries the latest built
85
- * state including diagnostics; callers observe convergence via that
86
- * response.
133
+ * Update a document's content as the session `clientId`, which must have
134
+ * it open. The response carries the latest built state including
135
+ * diagnostics; callers observe convergence via that response.
87
136
  */
88
137
  updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
89
138
 
90
139
  /**
91
- * Persist a document to disk. The response is the post-save document
140
+ * Write a document as the session `clientId`, which must have it open, and
141
+ * persist it to disk. The response is the post-save document
92
142
  * state (matches the file on disk). Save semantics depend on the
93
143
  * filesystem-provider wiring; rejection paths surface as awaited
94
144
  * promise rejections.
@@ -194,6 +244,22 @@ export interface DataServerProtocol<
194
244
  >
195
245
  extends DocumentServerProtocol<TTransfer, TDiagnostic>, ProjectServerProtocol<TProject> {}
196
246
 
247
+ /**
248
+ * The diagnostic shape a server answers with, read back off its own
249
+ * declaration.
250
+ *
251
+ * This is what lets a client tier stay generic over the server alone and still
252
+ * describe what it hands back. Both parameters must be inferred: naming
253
+ * {@link TransferElement} for the transfer instead fails to match while that
254
+ * parameter is still generic, and a default declared against the constraint
255
+ * then stops satisfying it.
256
+ */
257
+ export type DiagnosticOf<TServer> =
258
+ TServer extends DocumentServerProtocol<infer _TTransfer, infer TDiagnostic> ? TDiagnostic : TransferDiagnostic;
259
+
260
+ /** The project shape a server answers with, read back off its own declaration. */
261
+ export type ProjectOf<TServer> = TServer extends ProjectServerProtocol<infer TProject> ? TProject : Project;
262
+
197
263
  /**
198
264
  * Cross-reference / naming slice of the server surface — scope-aware
199
265
  * queries that resolve against the language's reference services. NOT part
@@ -262,6 +328,28 @@ export interface DocumentClientProtocol<TTransfer extends TransferElement, TDiag
262
328
  * codepath, not a subscription codepath).
263
329
  */
264
330
  onDocumentSaved(event: TransferDocumentSavedEvent<TTransfer, TDiagnostic>): void;
331
+
332
+ /**
333
+ * Delivered when a document's backing file was removed. Separate from
334
+ * {@link onDocumentUpdated} for the same reason as {@link onDocumentSaved},
335
+ * and more strongly: there is no built state to deliver, and the build-phase
336
+ * path cannot report a deletion at all.
337
+ *
338
+ * Ungated, because on a browser host — where the workspace lives behind the
339
+ * head — no other source can observe a file disappearing. Recipients that
340
+ * only care about their own documents filter by URI.
341
+ */
342
+ onDocumentDeleted(event: TransferDocumentDeletedEvent): void;
343
+
344
+ /**
345
+ * Delivered once per build, naming the documents that reached the
346
+ * subscription phase and that
347
+ * nobody on this connection watches — chiefly the ones rebuilt as a cascade
348
+ * from a dependency's change, which no filesystem watcher can see because
349
+ * their own files did not change. The complement of
350
+ * {@link onDocumentUpdated}; carries URIs and no documents.
351
+ */
352
+ onDocumentsBuilt(event: TransferDocumentsBuiltEvent): void;
265
353
  }
266
354
 
267
355
  /**