@hydranium/protocol 1.0.0-next.27 → 1.0.0-next.271

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 (254) 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 +248 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +439 -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 +34 -24
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +571 -89
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +938 -113
  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 +4 -4
  25. package/lib/client/message-relay.js +4 -4
  26. package/lib/client/message-relay.js.map +1 -1
  27. package/lib/client/post-message-transport.d.ts +64 -3
  28. package/lib/client/post-message-transport.d.ts.map +1 -1
  29. package/lib/client/post-message-transport.js +175 -1
  30. package/lib/client/post-message-transport.js.map +1 -1
  31. package/lib/client/rpc-connection.d.ts +157 -0
  32. package/lib/client/rpc-connection.d.ts.map +1 -0
  33. package/lib/client/rpc-connection.js +214 -0
  34. package/lib/client/rpc-connection.js.map +1 -0
  35. package/lib/client-ids.d.ts +45 -0
  36. package/lib/client-ids.d.ts.map +1 -0
  37. package/lib/client-ids.js +48 -0
  38. package/lib/client-ids.js.map +1 -0
  39. package/lib/clock.d.ts +50 -10
  40. package/lib/clock.d.ts.map +1 -1
  41. package/lib/clock.js +36 -1
  42. package/lib/clock.js.map +1 -1
  43. package/lib/console-logger.d.ts +23 -0
  44. package/lib/console-logger.d.ts.map +1 -0
  45. package/lib/console-logger.js +39 -0
  46. package/lib/console-logger.js.map +1 -0
  47. package/lib/data/data-protocol-methods.d.ts +4 -4
  48. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  49. package/lib/data/data-protocol-methods.js +12 -1
  50. package/lib/data/data-protocol-methods.js.map +1 -1
  51. package/lib/data/data-server-protocol.d.ts +132 -41
  52. package/lib/data/data-server-protocol.d.ts.map +1 -1
  53. package/lib/data/events.d.ts +117 -21
  54. package/lib/data/events.d.ts.map +1 -1
  55. package/lib/data/requests.d.ts +69 -11
  56. package/lib/data/requests.d.ts.map +1 -1
  57. package/lib/debouncer.d.ts +3 -3
  58. package/lib/debouncer.d.ts.map +1 -1
  59. package/lib/debouncer.js +6 -9
  60. package/lib/debouncer.js.map +1 -1
  61. package/lib/errors.d.ts +178 -30
  62. package/lib/errors.d.ts.map +1 -1
  63. package/lib/errors.js +263 -32
  64. package/lib/errors.js.map +1 -1
  65. package/lib/glsp-request-model-args.d.ts +16 -0
  66. package/lib/glsp-request-model-args.d.ts.map +1 -0
  67. package/lib/glsp-request-model-args.js +19 -0
  68. package/lib/glsp-request-model-args.js.map +1 -0
  69. package/lib/glsp-save-model-actions.d.ts +50 -0
  70. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  71. package/lib/glsp-save-model-actions.js +28 -0
  72. package/lib/glsp-save-model-actions.js.map +1 -0
  73. package/lib/index.d.ts +6 -0
  74. package/lib/index.d.ts.map +1 -1
  75. package/lib/index.js +6 -0
  76. package/lib/index.js.map +1 -1
  77. package/lib/latency-collector.d.ts +8 -4
  78. package/lib/latency-collector.d.ts.map +1 -1
  79. package/lib/latency-collector.js.map +1 -1
  80. package/lib/logger.d.ts +27 -6
  81. package/lib/logger.d.ts.map +1 -1
  82. package/lib/logger.js +31 -3
  83. package/lib/logger.js.map +1 -1
  84. package/lib/messages/index.d.ts +4 -2
  85. package/lib/messages/index.d.ts.map +1 -1
  86. package/lib/messages/index.js +14 -4
  87. package/lib/messages/index.js.map +1 -1
  88. package/lib/messages/primitives.d.ts +71 -10
  89. package/lib/messages/primitives.d.ts.map +1 -1
  90. package/lib/messages/primitives.js +55 -3
  91. package/lib/messages/primitives.js.map +1 -1
  92. package/lib/model-server.d.ts +60 -13
  93. package/lib/model-server.d.ts.map +1 -1
  94. package/lib/model-server.js +4 -2
  95. package/lib/model-server.js.map +1 -1
  96. package/lib/model-service/base-version.d.ts +64 -0
  97. package/lib/model-service/base-version.d.ts.map +1 -0
  98. package/lib/model-service/base-version.js +43 -0
  99. package/lib/model-service/base-version.js.map +1 -0
  100. package/lib/model-service/index.d.ts +1 -1
  101. package/lib/model-service/index.d.ts.map +1 -1
  102. package/lib/model-service/index.js +4 -5
  103. package/lib/model-service/index.js.map +1 -1
  104. package/lib/model-service/reference-candidate.d.ts +5 -3
  105. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  106. package/lib/{model-service/args.js → node/index.d.ts} +2 -3
  107. package/lib/node/index.d.ts.map +1 -0
  108. package/lib/node/index.js +29 -0
  109. package/lib/node/index.js.map +1 -0
  110. package/lib/node/process-memory.d.ts +66 -0
  111. package/lib/node/process-memory.d.ts.map +1 -0
  112. package/lib/node/process-memory.js +291 -0
  113. package/lib/node/process-memory.js.map +1 -0
  114. package/lib/noop-logger.d.ts.map +1 -1
  115. package/lib/noop-logger.js.map +1 -1
  116. package/lib/observable-value.js.map +1 -1
  117. package/lib/patch-merge.d.ts +35 -32
  118. package/lib/patch-merge.d.ts.map +1 -1
  119. package/lib/patch-merge.js +67 -23
  120. package/lib/patch-merge.js.map +1 -1
  121. package/lib/profile-session.d.ts +8 -4
  122. package/lib/profile-session.d.ts.map +1 -1
  123. package/lib/profile-session.js.map +1 -1
  124. package/lib/random-uuid.d.ts +14 -0
  125. package/lib/random-uuid.d.ts.map +1 -0
  126. package/lib/random-uuid.js +24 -0
  127. package/lib/random-uuid.js.map +1 -0
  128. package/lib/reconcile-write.d.ts +65 -0
  129. package/lib/reconcile-write.d.ts.map +1 -0
  130. package/lib/reconcile-write.js +67 -0
  131. package/lib/reconcile-write.js.map +1 -0
  132. package/lib/rpc/bind-rpc-methods.d.ts +33 -3
  133. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  134. package/lib/rpc/bind-rpc-methods.js +32 -3
  135. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  136. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  137. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  138. package/lib/rpc/create-rpc-proxy.js +12 -2
  139. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  140. package/lib/rpc/index.d.ts +1 -0
  141. package/lib/rpc/index.d.ts.map +1 -1
  142. package/lib/rpc/index.js +1 -0
  143. package/lib/rpc/index.js.map +1 -1
  144. package/lib/rpc/send-by-method-name.d.ts +76 -0
  145. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  146. package/lib/rpc/send-by-method-name.js +120 -0
  147. package/lib/rpc/send-by-method-name.js.map +1 -0
  148. package/lib/rpc/wire-prefix.js.map +1 -1
  149. package/lib/testing/catalogue-audit.d.ts +80 -0
  150. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  151. package/lib/testing/catalogue-audit.js +94 -0
  152. package/lib/testing/catalogue-audit.js.map +1 -0
  153. package/lib/testing/data-doubles.d.ts +41 -12
  154. package/lib/testing/data-doubles.d.ts.map +1 -1
  155. package/lib/testing/data-doubles.js +56 -8
  156. package/lib/testing/data-doubles.js.map +1 -1
  157. package/lib/testing/fake-clock.d.ts +17 -2
  158. package/lib/testing/fake-clock.d.ts.map +1 -1
  159. package/lib/testing/fake-clock.js +61 -46
  160. package/lib/testing/fake-clock.js.map +1 -1
  161. package/lib/testing/index.d.ts +1 -0
  162. package/lib/testing/index.d.ts.map +1 -1
  163. package/lib/testing/index.js +5 -2
  164. package/lib/testing/index.js.map +1 -1
  165. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  166. package/lib/testing/node/duplex-connection.js +3 -2
  167. package/lib/testing/node/duplex-connection.js.map +1 -1
  168. package/lib/testing/node/duplex-stream.js.map +1 -1
  169. package/lib/testing/node/index.d.ts +1 -0
  170. package/lib/testing/node/index.d.ts.map +1 -1
  171. package/lib/testing/node/index.js +2 -2
  172. package/lib/testing/node/index.js.map +1 -1
  173. package/lib/testing/node/message-port-pair.d.ts +25 -0
  174. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  175. package/lib/testing/node/message-port-pair.js +26 -0
  176. package/lib/testing/node/message-port-pair.js.map +1 -0
  177. package/lib/testing/wait-for.d.ts +3 -2
  178. package/lib/testing/wait-for.d.ts.map +1 -1
  179. package/lib/testing/wait-for.js +40 -10
  180. package/lib/testing/wait-for.js.map +1 -1
  181. package/lib/tracer.d.ts.map +1 -1
  182. package/lib/tracer.js +5 -9
  183. package/lib/tracer.js.map +1 -1
  184. package/lib/transfer-diagnostic.d.ts +33 -0
  185. package/lib/transfer-diagnostic.d.ts.map +1 -1
  186. package/lib/transfer-diagnostic.js +23 -0
  187. package/lib/transfer-diagnostic.js.map +1 -1
  188. package/lib/transfer-document.d.ts +70 -32
  189. package/lib/transfer-document.d.ts.map +1 -1
  190. package/lib/transfer-document.js +17 -9
  191. package/lib/transfer-document.js.map +1 -1
  192. package/lib/uri.d.ts.map +1 -1
  193. package/lib/uri.js.map +1 -1
  194. package/lib/util.d.ts +8 -2
  195. package/lib/util.d.ts.map +1 -1
  196. package/lib/util.js +32 -4
  197. package/lib/util.js.map +1 -1
  198. package/package.json +24 -40
  199. package/src/abstract-logger.ts +8 -0
  200. package/src/client/data-connection.ts +535 -0
  201. package/src/client/data-events.ts +33 -1
  202. package/src/client/data-port.ts +36 -25
  203. package/src/client/data-session.ts +1198 -135
  204. package/src/client/index.ts +14 -9
  205. package/src/client/message-relay.ts +4 -4
  206. package/src/client/post-message-transport.ts +219 -4
  207. package/src/client/rpc-connection.ts +281 -0
  208. package/src/client-ids.ts +49 -0
  209. package/src/clock.ts +68 -10
  210. package/src/console-logger.ts +39 -0
  211. package/src/data/data-protocol-methods.ts +13 -4
  212. package/src/data/data-server-protocol.ts +157 -41
  213. package/src/data/events.ts +123 -21
  214. package/src/data/requests.ts +74 -11
  215. package/src/debouncer.ts +7 -10
  216. package/src/errors.ts +312 -40
  217. package/src/glsp-request-model-args.ts +16 -0
  218. package/src/glsp-save-model-actions.ts +59 -0
  219. package/src/index.ts +6 -0
  220. package/src/latency-collector.ts +8 -3
  221. package/src/logger.ts +33 -7
  222. package/src/messages/index.ts +4 -2
  223. package/src/messages/primitives.ts +102 -10
  224. package/src/model-server.ts +64 -19
  225. package/src/model-service/base-version.ts +72 -0
  226. package/src/model-service/index.ts +4 -5
  227. package/src/model-service/reference-candidate.ts +5 -3
  228. package/src/node/index.ts +14 -0
  229. package/src/node/process-memory.ts +299 -0
  230. package/src/patch-merge.ts +97 -42
  231. package/src/profile-session.ts +9 -4
  232. package/src/random-uuid.ts +21 -0
  233. package/src/reconcile-write.ts +124 -0
  234. package/src/rpc/README.md +6 -6
  235. package/src/rpc/bind-rpc-methods.ts +59 -4
  236. package/src/rpc/create-rpc-proxy.ts +20 -2
  237. package/src/rpc/index.ts +1 -0
  238. package/src/rpc/send-by-method-name.ts +140 -0
  239. package/src/testing/catalogue-audit.ts +111 -0
  240. package/src/testing/data-doubles.ts +141 -19
  241. package/src/testing/fake-clock.ts +76 -48
  242. package/src/testing/index.ts +5 -2
  243. package/src/testing/node/duplex-connection.ts +3 -2
  244. package/src/testing/node/index.ts +2 -2
  245. package/src/testing/node/message-port-pair.ts +40 -0
  246. package/src/testing/wait-for.ts +38 -11
  247. package/src/tracer.ts +5 -9
  248. package/src/transfer-diagnostic.ts +40 -0
  249. package/src/transfer-document.ts +87 -34
  250. package/src/util.ts +33 -6
  251. package/lib/model-service/args.d.ts +0 -64
  252. package/lib/model-service/args.d.ts.map +0 -1
  253. package/lib/model-service/args.js.map +0 -1
  254. package/src/model-service/args.ts +0 -67
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { TransferSaveArgs, TransferUpdateArgs } from '../model-service/args';
10
+ import type { BaseVersion } from '../model-service/base-version';
11
11
 
12
12
  /** Get the current state of a single document. The server returns the latest built version. */
13
13
  export interface GetModelDocumentArgs {
@@ -41,24 +41,87 @@ export interface GetProjectForUriArgs {
41
41
  }
42
42
 
43
43
  /**
44
- * Update a document's content. Wire-side projection of the facade's
45
- * {@link TransferUpdateArgs}; structurally identical so the data-server RPC
46
- * handler can forward straight to the in-process `ModelService.update`
47
- * without an args mapping.
44
+ * Update a document the session `clientId` has open. Generic over `TTransfer`
45
+ * so adopters parameterise the structured shape against their grammar's
46
+ * transfer-model overlay; passing a string is always allowed.
48
47
  */
49
- export type TransferUpdateDocumentArgs<TTransfer> = TransferUpdateArgs<TTransfer>;
48
+ export interface TransferUpdateDocumentArgs<TTransfer> {
49
+ /** Document URI. */
50
+ uri: string;
51
+ /** The id of a live session registered on this connection. */
52
+ clientId: string;
53
+ /** The whole structured model root, or its serialised textual form. */
54
+ model: TTransfer | string;
55
+ /**
56
+ * What this write was authored against. A `ModelVersion` is compared
57
+ * against the server's current text-document version for `uri` and throws
58
+ * `ConflictError` on mismatch; `'any'` writes unconditionally.
59
+ *
60
+ * **Required so that an ungated write is a decision rather than an
61
+ * omission.** An optional gate is indistinguishable from a forgotten one at
62
+ * the call site, and a file of twenty writes hides the one that lost the
63
+ * field. Nothing else here can see that, since the defect is an absence.
64
+ */
65
+ baseVersion: BaseVersion;
66
+ }
50
67
 
51
- /** Persist a document to disk. Wire-side projection of {@link TransferSaveArgs}. */
52
- export type TransferSaveDocumentArgs<TTransfer> = TransferSaveArgs<TTransfer>;
68
+ /** Update a document the session `clientId` has open, then persist it to disk. */
69
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- save names its own args; it adds no field to update's
70
+ export interface TransferSaveDocumentArgs<TTransfer> extends TransferUpdateDocumentArgs<TTransfer> {}
71
+
72
+ /** Persist the text the server holds for a document the session `clientId` has open, without writing a model. */
73
+ export type TransferPersistDocumentArgs = Omit<TransferUpdateDocumentArgs<never>, 'model'>;
74
+
75
+ /** Register a client session on the connection. */
76
+ export interface CreateSessionArgs {
77
+ /** The session's id, minted by the client; unique in the server process while the session is live. */
78
+ clientId: string;
79
+ /** What the participant is; kept as the server session's `label`. */
80
+ label?: string;
81
+ /**
82
+ * A token the client keeps for the session's lifetime. It is no secret: the
83
+ * wire carries no authentication. A later `createSession` for the same id
84
+ * carrying the same token, from any connection, ends the session it names
85
+ * and registers the id afresh, so a client whose connection dropped before
86
+ * the server noticed can register again. Without it the id stays refused
87
+ * until the server notices.
88
+ */
89
+ resumeToken?: string;
90
+ }
91
+
92
+ /** End a client session registered on the connection. */
93
+ export interface CloseSessionArgs {
94
+ clientId: string;
95
+ }
96
+
97
+ /** Create a document that exists nowhere yet, open for the session creating it. */
98
+ export interface CreateModelDocumentArgs {
99
+ uri: string;
100
+ /** The id of a live session registered on this connection. */
101
+ clientId: string;
102
+ /** The document's initial content; it reaches disk with the first save. */
103
+ text: string;
104
+ }
105
+
106
+ /**
107
+ * Write several documents a session has open, all or none. `clientId` is on
108
+ * the set rather than on each update: an id per update would allow a set
109
+ * mixing clients, which the server would have to refuse.
110
+ */
111
+ export interface TransferUpdateDocumentsArgs<TTransfer> {
112
+ /** The id of a live session registered on this connection. */
113
+ clientId: string;
114
+ updates: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>[];
115
+ }
53
116
 
54
117
  /**
55
118
  * Identifies a per-document watch on the data server. Shared by both
56
119
  * `watchModelDocument` and `unwatchModelDocument` — the `(uri, clientId)`
57
120
  * pair is the watch key, so unwatching names the same watch that was
58
121
  * started. The `clientId` identifies the originator the same way it does
59
- * on facade-side mutations (`TransferUpdateArgs.clientId`,
60
- * `TransferSaveArgs.clientId`): it keys the per-`(uri, clientId)` watch
61
- * bucket so multiple watchers on the same wire stay distinct, AND it lets
122
+ * on the document writes (`TransferUpdateDocumentArgs.clientId`,
123
+ * `TransferSaveDocumentArgs.clientId`): it keys the per-`(uri, clientId)`
124
+ * watch bucket so multiple watchers on the same wire stay distinct, AND it lets
62
125
  * each watcher recognise its own echo on inbound `onDocumentUpdated` events
63
126
  * (the wire shape's `sourceClientId` carries the originating mutation's
64
127
  * `clientId`).
package/src/debouncer.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { type Clock } from './clock';
10
+ import { type Clock, type Stopwatch } from './clock';
11
11
  import { ObservableValue, type MaybeObservableValue } from './observable-value';
12
12
  import { type Disposable } from './util';
13
13
 
@@ -53,8 +53,8 @@ export class Debouncer implements Disposable {
53
53
  protected readonly delay: ObservableValue<number>;
54
54
  protected readonly maxWaitMs?: number;
55
55
  protected timer?: Disposable;
56
- /** Virtual time of the first {@link schedule} of the current pending window; drives {@link DebouncerOptions.maxWaitMs}. */
57
- protected firstScheduledAt?: number;
56
+ /** Running since the first {@link schedule} of the current pending window; drives {@link DebouncerOptions.maxWaitMs}. */
57
+ protected sinceFirstSchedule?: Stopwatch;
58
58
 
59
59
  constructor(
60
60
  protected readonly clock: Clock,
@@ -77,13 +77,10 @@ export class Debouncer implements Disposable {
77
77
  * elapses since the first pending call.
78
78
  */
79
79
  schedule(): void {
80
- const now = this.clock.now();
81
- if (this.firstScheduledAt === undefined) {
82
- this.firstScheduledAt = now;
83
- }
80
+ this.sinceFirstSchedule ??= this.clock.stopwatch();
84
81
  let wait = Math.max(0, this.delay.value);
85
82
  if (this.maxWaitMs !== undefined) {
86
- const untilCeiling = this.firstScheduledAt + this.maxWaitMs - now;
83
+ const untilCeiling = this.maxWaitMs - this.sinceFirstSchedule.elapsedMs;
87
84
  wait = Math.min(wait, Math.max(0, untilCeiling));
88
85
  }
89
86
  this.timer?.dispose();
@@ -101,7 +98,7 @@ export class Debouncer implements Disposable {
101
98
  cancel(): void {
102
99
  this.timer?.dispose();
103
100
  this.timer = undefined;
104
- this.firstScheduledAt = undefined;
101
+ this.sinceFirstSchedule = undefined;
105
102
  }
106
103
 
107
104
  /** Cancel any pending fire and release. */
@@ -112,7 +109,7 @@ export class Debouncer implements Disposable {
112
109
  protected fire(): void {
113
110
  this.timer?.dispose();
114
111
  this.timer = undefined;
115
- this.firstScheduledAt = undefined;
112
+ this.sinceFirstSchedule = undefined;
116
113
  this.fn();
117
114
  }
118
115
  }
package/src/errors.ts CHANGED
@@ -9,62 +9,92 @@
9
9
 
10
10
  import { ResponseError } from 'vscode-jsonrpc';
11
11
  import { defineMessage, type HydraniumMessageData, messageData } from './messages/primitives';
12
+ import { asModelVersion, type ModelVersion, type TextVersion } from './model-service/base-version';
13
+
14
+ /*
15
+ * Every error here is a typed error: a caller reacts to it, so it has a class,
16
+ * a JSON-RPC code and an `is*` guard, and an English message. A typed error
17
+ * also carries a message identity where the framework can write an end-user
18
+ * sentence that needs no context. A URI may stay in that sentence; a client id
19
+ * or a raw version stays out of it, worded or left to `data`.
20
+ *
21
+ * An error nothing reacts to does not belong here: it stays a plain `Error`, or
22
+ * a named subclass without a code, at its throw site, since a code and a guard
23
+ * are public API that no caller would use.
24
+ */
12
25
 
13
26
  /**
14
- * The catalogue declaration behind {@link ConflictError}'s sentence.
27
+ * The catalogue declaration behind {@link ConflictError}'s sentence. It words
28
+ * the version mismatch rather than stating it: the two numbers mean nothing to
29
+ * an end user, and they stay in {@link ConflictErrorData}.
15
30
  *
16
31
  * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
17
32
  * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
18
33
  * That tier only ever works untranslated, which is why it is the last resort
19
34
  * behind the numeric code rather than the primary check.
20
35
  */
21
- export const STALE_BASED_UPDATE = defineMessage(
22
- 'hydranium/protocol/stale-based-update',
23
- 'Stale-based update for {uri}: expected v{expected}, server is at v{actual}'
36
+ export const STALE_BASE_VERSION_UPDATE = defineMessage(
37
+ 'hydranium/protocol/stale-base-version-update',
38
+ 'The edit to {uri} was not applied: it was made to an older version of the document.'
24
39
  );
25
40
 
26
41
  /**
27
- * Application-specific JSON-RPC error code for {@link ConflictError}.
28
- * Outside the reserved range (-32768 .. -32000) per JSON-RPC 2.0.
42
+ * Every JSON-RPC error code the framework raises, from any package, keyed by
43
+ * the error it identifies.
44
+ *
45
+ * The framework reserves the block 42000 to 42999 for these, and an adopter's
46
+ * own codes stay outside it: after an RPC a guard matches on the code alone, so
47
+ * an adopter's error carrying one of these reads as the framework's. A new code
48
+ * takes the next unused number in the block, whichever package raises it, and
49
+ * is declared here, where tests hold every code distinct and inside the block.
50
+ * The block sits clear of the range JSON-RPC 2.0 reserves for itself, -32768
51
+ * to -32000.
52
+ */
53
+ export const HYDRANIUM_ERROR_CODES = {
54
+ conflict: 42001,
55
+ noActiveProfile: 42002,
56
+ referenceSettleTimeout: 42003,
57
+ sessionClosed: 42004,
58
+ documentNotOpen: 42005,
59
+ duplicateClientId: 42006,
60
+ reservedClientId: 42007
61
+ } as const;
62
+
63
+ /**
64
+ * JSON-RPC error code for {@link ConflictError}.
29
65
  *
30
66
  * The code is the load-bearing identifier across realm boundaries —
31
67
  * `code` is a first-class field on the JSON-RPC error envelope and
32
68
  * survives wire reconstruction; the custom `Error` subclass name does
33
69
  * not.
34
70
  */
35
- export const CONFLICT_ERROR_CODE = 1001;
71
+ export const CONFLICT_ERROR_CODE = HYDRANIUM_ERROR_CODES.conflict;
36
72
 
37
- /**
38
- * Structured payload carried in {@link ConflictError.data}, and the only place
39
- * a post-RPC caller can read the version mismatch from.
40
- */
73
+ /** Structured payload carried in {@link ConflictError.data}. */
41
74
  export interface ConflictErrorData extends HydraniumMessageData {
42
75
  readonly uri: string;
43
- /** The based-on version the caller authored against. */
44
- readonly expected: number;
76
+ /** The base version the caller authored against. */
77
+ readonly baseVersion: ModelVersion;
45
78
  /** The server's current text-document version at the time of the throw. */
46
- readonly actual: number;
79
+ readonly actualVersion: TextVersion;
47
80
  }
48
81
 
49
82
  /**
50
- * Thrown by `ModelService.update` / `ModelService.save` when the caller-
51
- * supplied based-on version no longer matches the server's current text-
83
+ * Thrown by a client session's `update` / `save` when the caller-
84
+ * supplied base version no longer matches the server's current text-
52
85
  * document version for the same URI — i.e. the snapshot the caller
53
86
  * authored against has been superseded by an intervening edit.
54
87
  *
55
88
  * Extends vscode-jsonrpc's {@link ResponseError} so the typed
56
89
  * {@link ConflictErrorData} payload rides on the standard JSON-RPC
57
90
  * error envelope (`code`, `message`, `data`) — all three fields are
58
- * preserved by RPC reconstruction. Adopters that catch the error on
59
- * the receiving side of an RPC call read the version mismatch from
60
- * `err.data` (the instance is reconstructed as a generic
61
- * `ResponseError`, so subclass getters / fields do not survive).
91
+ * preserved by RPC reconstruction. `createRpcProxy` revives it into
92
+ * this class on the receiving side; a path that does not leaves a
93
+ * plain `ResponseError`, readable through `err.data` only.
62
94
  *
63
- * Detection is opt-in via the optional `baseVersion` field on
64
- * `TransferUpdateArgs` / `TransferSaveArgs`; callers that omit the field get
65
- * no gating. This mirrors LSP's `OptionalVersionedTextDocumentIdentifier`
66
- * posture, so headless / CLI / batch tooling with no meaningful based-on
67
- * version can opt out explicitly.
95
+ * Detection is driven by the required `baseVersion` field of every write
96
+ * request; a caller with no meaningful base version passes
97
+ * `'any'` and gets no gating.
68
98
  *
69
99
  * Three reasonable adopter recovery strategies:
70
100
  *
@@ -78,18 +108,23 @@ export interface ConflictErrorData extends HydraniumMessageData {
78
108
  * No auto-retry or auto-merge ships by default.
79
109
  */
80
110
  export class ConflictError extends ResponseError<ConflictErrorData> {
81
- constructor(uri: string, expected: number, actual: number) {
82
- const params = { uri, expected, actual };
111
+ constructor(uri: string, baseVersion: ModelVersion, actualVersion: TextVersion) {
83
112
  // The identity rides alongside the typed payload rather than replacing
84
- // it: this class's getters and `isConflictError`'s name check are surface
85
- // an adopter may bind, so the payload widens rather than changing shape.
86
- super(CONFLICT_ERROR_CODE, STALE_BASED_UPDATE.format(params), { ...params, ...messageData(STALE_BASED_UPDATE, params) });
113
+ // it: `isConflictError`'s name check is surface an adopter may bind, so
114
+ // adding the identity widens the payload rather than reshaping it.
115
+ super(CONFLICT_ERROR_CODE, STALE_BASE_VERSION_UPDATE.format({ uri }), {
116
+ uri,
117
+ baseVersion,
118
+ actualVersion,
119
+ ...messageData(STALE_BASE_VERSION_UPDATE, { uri })
120
+ });
87
121
  this.name = 'ConflictError';
88
122
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
89
123
  // ResponseError.prototype)` to keep its own prototype chain intact across
90
124
  // transpilation targets; that resets us to ResponseError, hiding the
91
125
  // ConflictError-specific getters. Restore the prototype here so
92
- // `err.uri` / `.expected` / `.actual` resolve through this class.
126
+ // `err.uri` / `.baseVersion` / `.actualVersion` resolve through this
127
+ // class.
93
128
  Object.setPrototypeOf(this, ConflictError.prototype);
94
129
  }
95
130
 
@@ -97,19 +132,255 @@ export class ConflictError extends ResponseError<ConflictErrorData> {
97
132
  return this.data!.uri;
98
133
  }
99
134
 
100
- get expected(): number {
101
- return this.data!.expected;
135
+ /**
136
+ * The base version the caller authored against.
137
+ *
138
+ * Must not be renamed to `expected`, nor its sibling to `actual`: a test
139
+ * reporter reads an error carrying both as an assertion failure, and
140
+ * vitest's formatter then ASSIGNS to them, which throws on an accessor and
141
+ * replaces the real failure with a `TypeError`.
142
+ */
143
+ get baseVersion(): ModelVersion {
144
+ return this.data!.baseVersion;
145
+ }
146
+
147
+ /** The server's version at the time of the throw. Not `actual` — see {@link baseVersion}. */
148
+ get actualVersion(): TextVersion {
149
+ return this.data!.actualVersion;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * JSON-RPC code for {@link SessionClosedError}, beside {@link CONFLICT_ERROR_CODE}
155
+ * and for the same reason: the code survives reconstruction, the class does not.
156
+ */
157
+ export const SESSION_CLOSED_ERROR_CODE = HYDRANIUM_ERROR_CODES.sessionClosed;
158
+ /** JSON-RPC code for {@link DocumentNotOpenError}. */
159
+ export const DOCUMENT_NOT_OPEN_ERROR_CODE = HYDRANIUM_ERROR_CODES.documentNotOpen;
160
+ /** JSON-RPC code for {@link DuplicateClientIdError}. */
161
+ export const DUPLICATE_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.duplicateClientId;
162
+ /** JSON-RPC code for {@link ReservedClientIdError}. */
163
+ export const RESERVED_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.reservedClientId;
164
+
165
+ /**
166
+ * The catalogue declaration behind {@link SessionClosedError}'s default
167
+ * sentence. It names no client id: the sentence can reach an end user, and the
168
+ * id stays in {@link SessionClosedErrorData.clientId} for whoever needs it.
169
+ */
170
+ export const SESSION_CLOSED = defineMessage('hydranium/protocol/session-closed', 'The editing session has ended.');
171
+
172
+ /** Structured payload carried in {@link SessionClosedError.data}. */
173
+ export interface SessionClosedErrorData extends HydraniumMessageData {
174
+ readonly clientId: string;
175
+ }
176
+
177
+ /**
178
+ * Thrown by every call on a client session after it ended, and by an open that
179
+ * was still in flight when its session ended: by the server for its sessions,
180
+ * and by a client-side `DataSession` once disposed, so a caller handles both
181
+ * the same way. A caller recognises it with {@link isSessionClosedError}, never
182
+ * by its sentence.
183
+ */
184
+ export class SessionClosedError extends ResponseError<SessionClosedErrorData> {
185
+ /**
186
+ * `message` replaces the default English, for a caller that knows more than
187
+ * that the session is gone. The identity stays {@link SESSION_CLOSED}'s, so a
188
+ * translating renderer renders the catalogue sentence in its place.
189
+ */
190
+ constructor(clientId: string, message = SESSION_CLOSED.format()) {
191
+ super(SESSION_CLOSED_ERROR_CODE, message, { clientId, ...messageData(SESSION_CLOSED) });
192
+ this.name = 'SessionClosedError';
193
+ // `ResponseError` resets the prototype to its own; see `ConflictError`.
194
+ Object.setPrototypeOf(this, SessionClosedError.prototype);
195
+ }
196
+
197
+ get clientId(): string {
198
+ return this.data!.clientId;
102
199
  }
200
+ }
201
+
202
+ /**
203
+ * The catalogue declaration behind {@link DocumentNotOpenError}'s sentence. The
204
+ * client id stays in {@link DocumentNotOpenErrorData.clientId}.
205
+ */
206
+ export const DOCUMENT_NOT_OPEN = defineMessage(
207
+ 'hydranium/protocol/document-not-open',
208
+ 'The document {uri} is not open in this editing session.'
209
+ );
210
+
211
+ /** Structured payload carried in {@link DocumentNotOpenError.data}. */
212
+ export interface DocumentNotOpenErrorData extends HydraniumMessageData {
213
+ readonly uri: string;
214
+ readonly clientId: string;
215
+ }
103
216
 
104
- get actual(): number {
105
- return this.data!.actual;
217
+ /**
218
+ * Thrown when a client session writes a document it does not have open.
219
+ *
220
+ * A session writes only what it has open, so this is the answer both to a write
221
+ * that never opened and to one whose open was closed underneath it — by the
222
+ * session itself, or by the document being deleted.
223
+ */
224
+ export class DocumentNotOpenError extends ResponseError<DocumentNotOpenErrorData> {
225
+ constructor(uri: string, clientId: string) {
226
+ super(DOCUMENT_NOT_OPEN_ERROR_CODE, DOCUMENT_NOT_OPEN.format({ uri }), {
227
+ uri,
228
+ clientId,
229
+ ...messageData(DOCUMENT_NOT_OPEN, { uri })
230
+ });
231
+ this.name = 'DocumentNotOpenError';
232
+ Object.setPrototypeOf(this, DocumentNotOpenError.prototype);
233
+ }
234
+
235
+ get uri(): string {
236
+ return this.data!.uri;
106
237
  }
238
+
239
+ get clientId(): string {
240
+ return this.data!.clientId;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * The catalogue declaration behind {@link DuplicateClientIdError}'s sentence.
246
+ * The client id stays in {@link DuplicateClientIdErrorData.clientId}.
247
+ */
248
+ export const DUPLICATE_CLIENT_ID = defineMessage(
249
+ 'hydranium/protocol/duplicate-client-id',
250
+ 'Could not start an editing session: its identifier is still in use by another editor.'
251
+ );
252
+
253
+ /** Structured payload carried in {@link DuplicateClientIdError.data}. */
254
+ export interface DuplicateClientIdErrorData extends HydraniumMessageData {
255
+ readonly clientId: string;
256
+ }
257
+
258
+ /**
259
+ * Thrown when a client session is started under an id that is already live in
260
+ * the process. The id frees up once its holder ends or closes its last
261
+ * document, so a caller may retry.
262
+ *
263
+ * Ids are unique process-wide because the id is also the author label on every
264
+ * version and the key a client recognises its own echoes by; two participants
265
+ * sharing one would each take the other's writes for their own.
266
+ */
267
+ export class DuplicateClientIdError extends ResponseError<DuplicateClientIdErrorData> {
268
+ constructor(clientId: string) {
269
+ super(DUPLICATE_CLIENT_ID_ERROR_CODE, DUPLICATE_CLIENT_ID.format(), { clientId, ...messageData(DUPLICATE_CLIENT_ID) });
270
+ this.name = 'DuplicateClientIdError';
271
+ Object.setPrototypeOf(this, DuplicateClientIdError.prototype);
272
+ }
273
+
274
+ get clientId(): string {
275
+ return this.data!.clientId;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Thrown when a client session is started under an id the framework reserves
281
+ * for one of its own participants. A reserved id never frees up, so a caller
282
+ * that retries on {@link DuplicateClientIdError} stops on this one.
283
+ *
284
+ * It carries no message identity: a host that picks a reserved id has a bug,
285
+ * and no sentence addressed to an end user is true for it.
286
+ */
287
+ export class ReservedClientIdError extends ResponseError<{ readonly clientId: string }> {
288
+ constructor(clientId: string) {
289
+ super(RESERVED_CLIENT_ID_ERROR_CODE, `Client id ${clientId} is reserved for a framework participant`, { clientId });
290
+ this.name = 'ReservedClientIdError';
291
+ Object.setPrototypeOf(this, ReservedClientIdError.prototype);
292
+ }
293
+
294
+ get clientId(): string {
295
+ return this.data!.clientId;
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Rebuilds one typed error from the `data` that crossed the wire, or
301
+ * `undefined` when `data` lacks the fields the class reads.
302
+ */
303
+ type ProtocolErrorReviver = (data: Readonly<Record<string, unknown>>) => ResponseError<unknown> | undefined;
304
+
305
+ /** One entry per typed error class, keyed by its code; a class without one reaches a caller as a plain `ResponseError`. */
306
+ const PROTOCOL_ERROR_REVIVERS: ReadonlyMap<number, ProtocolErrorReviver> = new Map<number, ProtocolErrorReviver>([
307
+ [
308
+ CONFLICT_ERROR_CODE,
309
+ ({ uri, baseVersion, actualVersion }) =>
310
+ typeof uri === 'string' && typeof baseVersion === 'number' && typeof actualVersion === 'number'
311
+ ? new ConflictError(uri, asModelVersion(baseVersion), actualVersion)
312
+ : undefined
313
+ ],
314
+ [SESSION_CLOSED_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new SessionClosedError(clientId) : undefined)],
315
+ [
316
+ DOCUMENT_NOT_OPEN_ERROR_CODE,
317
+ ({ uri, clientId }) => (typeof uri === 'string' && typeof clientId === 'string' ? new DocumentNotOpenError(uri, clientId) : undefined)
318
+ ],
319
+ [DUPLICATE_CLIENT_ID_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new DuplicateClientIdError(clientId) : undefined)],
320
+ [RESERVED_CLIENT_ID_ERROR_CODE, ({ clientId }) => (typeof clientId === 'string' ? new ReservedClientIdError(clientId) : undefined)]
321
+ ]);
322
+
323
+ /**
324
+ * Whether `error` is a `ResponseError` from any copy of `vscode-jsonrpc`. An
325
+ * install holds several copies, and `instanceof` recognises only its own. An
326
+ * error that merely carries an integer `code` has no `toJson`, and is not one.
327
+ */
328
+ export function isResponseError(error: unknown): error is ResponseError<unknown> {
329
+ return (
330
+ error instanceof Error && 'code' in error && Number.isInteger(error.code) && 'toJson' in error && typeof error.toJson === 'function'
331
+ );
332
+ }
333
+
334
+ /**
335
+ * `error` as an instance of the typed error class its code names, with its
336
+ * message, data and stack kept, or `error` itself when its code names none or
337
+ * its data lacks the fields that class reads.
338
+ * An RPC reconstructs every rejection as a plain `ResponseError`, which has
339
+ * none of the class getters.
340
+ */
341
+ export function reviveProtocolError(error: unknown): unknown {
342
+ if (!isResponseError(error) || error.data === null || typeof error.data !== 'object') {
343
+ return error;
344
+ }
345
+ const revived = PROTOCOL_ERROR_REVIVERS.get(error.code)?.({ ...error.data });
346
+ if (!revived) {
347
+ return error;
348
+ }
349
+ return Object.assign(revived, { message: error.message, data: error.data, stack: error.stack });
350
+ }
351
+
352
+ /**
353
+ * Whether `error` is a {@link SessionClosedError}: by name in-process, by code
354
+ * when it arrives as a plain `ResponseError`, through a path that does not
355
+ * {@link reviveProtocolError revive} it.
356
+ */
357
+ export function isSessionClosedError(error: unknown): error is SessionClosedError {
358
+ return hasErrorIdentity(error, 'SessionClosedError', SESSION_CLOSED_ERROR_CODE);
359
+ }
360
+
361
+ /** Whether `error` is a {@link DocumentNotOpenError}; see {@link isSessionClosedError}. */
362
+ export function isDocumentNotOpenError(error: unknown): error is DocumentNotOpenError {
363
+ return hasErrorIdentity(error, 'DocumentNotOpenError', DOCUMENT_NOT_OPEN_ERROR_CODE);
364
+ }
365
+
366
+ /** Whether `error` is a {@link DuplicateClientIdError}; see {@link isSessionClosedError}. */
367
+ export function isDuplicateClientIdError(error: unknown): error is DuplicateClientIdError {
368
+ return hasErrorIdentity(error, 'DuplicateClientIdError', DUPLICATE_CLIENT_ID_ERROR_CODE);
369
+ }
370
+
371
+ /** Whether `error` is a {@link ReservedClientIdError}; see {@link isSessionClosedError}. */
372
+ export function isReservedClientIdError(error: unknown): error is ReservedClientIdError {
373
+ return hasErrorIdentity(error, 'ReservedClientIdError', RESERVED_CLIENT_ID_ERROR_CODE);
374
+ }
375
+
376
+ function hasErrorIdentity(error: unknown, name: string, code: number): boolean {
377
+ return error instanceof Error && (error.name === name || (error as Partial<ResponseError<unknown>>).code === code);
107
378
  }
108
379
 
109
380
  /** Marker substring present in every {@link ConflictError} message, used by
110
381
  * {@link isConflictError} as a fallback when a transport re-wraps the error
111
382
  * and drops the JSON-RPC code. */
112
- const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
383
+ const CONFLICT_ERROR_MESSAGE_MARKER = ': it was made to an older version of the document';
113
384
 
114
385
  /**
115
386
  * Type guard for {@link ConflictError}. Detection ladder:
@@ -120,11 +391,12 @@ const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
120
391
  * canonical wire-side check; the JSON-RPC `code` field is preserved
121
392
  * across reconstruction, so any adopter catching after an RPC call
122
393
  * hits this branch.
123
- * 3. `error.message.includes('Stale-based update for ')` — fallback
124
- * for transports that re-wrap the message and drop the code (rare).
394
+ * 3. `error.message` contains the marker {@link STALE_BASE_VERSION_UPDATE}'s
395
+ * English carries — fallback for transports that re-wrap the message
396
+ * and drop the code (rare).
125
397
  *
126
- * `instanceof ConflictError` alone would silently return `false` on the
127
- * reconstructed shape, so callers do not use it.
398
+ * `instanceof ConflictError` alone returns `false` on a rejection that was
399
+ * not {@link reviveProtocolError revived}, so callers do not use it.
128
400
  */
129
401
  export function isConflictError(error: unknown): error is ConflictError {
130
402
  if (!(error instanceof Error)) {
@@ -0,0 +1,16 @@
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
+ * The `RequestModelAction` option carrying a diagram's resume token. A load
12
+ * whose token matches the one the live session under its client id was started
13
+ * with takes that session over, so a diagram that reconnects or reloads keeps
14
+ * its unsaved text; without it, the id held by another session is refused.
15
+ */
16
+ export const RESUME_TOKEN_ARG = 'hydraniumResumeToken';
@@ -0,0 +1,59 @@
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
+ // Declared field by field rather than extending GLSP's action types: this
11
+ // package carries no GLSP dependency, and both GLSP heads already depend on it.
12
+ // The fields are GLSP's own, so both actions are assignable to GLSP's
13
+ // `RequestAction` and `ResponseAction`.
14
+
15
+ /**
16
+ * A save of a diagram's model that the server answers, with a
17
+ * {@link ModelSavedAction} once the save has finished or a GLSP
18
+ * `RejectAction` when it fails.
19
+ *
20
+ * It carries what GLSP's `SaveModelAction` carries, and the server saves it the
21
+ * same way. GLSP's `SaveModelAction` is not answered: the server's only
22
+ * reply is a dirty-state change, which the client drops when the dirty flag
23
+ * does not change, so a client cannot tell which save an answer belongs to or
24
+ * whether a save failed.
25
+ */
26
+ export interface RequestSaveModelAction {
27
+ kind: typeof RequestSaveModelAction.KIND;
28
+ /** The id the response echoes as its `responseId`. Empty until the dispatcher assigns one. */
29
+ requestId: string;
30
+ /** How long the receiver waits for its own handler, in milliseconds. */
31
+ timeout?: number;
32
+ /** The file to save to, as in GLSP's `SaveModelAction`; absent saves to the diagram's source. */
33
+ fileUri?: string;
34
+ /** GLSP's typing marker for the response. Never set. */
35
+ readonly _?: ModelSavedAction;
36
+ }
37
+
38
+ export namespace RequestSaveModelAction {
39
+ export const KIND = 'hydraniumRequestSaveModel';
40
+
41
+ export function create(options: { fileUri?: string; requestId?: string } = {}): RequestSaveModelAction {
42
+ return { kind: KIND, requestId: '', ...options };
43
+ }
44
+ }
45
+
46
+ /** The server's answer to a {@link RequestSaveModelAction} that saved. */
47
+ export interface ModelSavedAction {
48
+ kind: typeof ModelSavedAction.KIND;
49
+ /** The `requestId` of the save this answers. The server's dispatcher sets it. */
50
+ responseId: string;
51
+ }
52
+
53
+ export namespace ModelSavedAction {
54
+ export const KIND = 'hydraniumModelSaved';
55
+
56
+ export function create(options: { responseId?: string } = {}): ModelSavedAction {
57
+ return { kind: KIND, responseId: '', ...options };
58
+ }
59
+ }