@hydranium/protocol 1.0.0-next.19 → 1.0.0-next.193

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 (205) hide show
  1. package/README.md +35 -1
  2. package/lib/abstract-logger.d.ts.map +1 -1
  3. package/lib/abstract-logger.js.map +1 -1
  4. package/lib/client/data-connection.d.ts +157 -0
  5. package/lib/client/data-connection.d.ts.map +1 -0
  6. package/lib/client/data-connection.js +236 -0
  7. package/lib/client/data-connection.js.map +1 -0
  8. package/lib/client/data-events.d.ts +13 -1
  9. package/lib/client/data-events.d.ts.map +1 -1
  10. package/lib/client/data-events.js +21 -0
  11. package/lib/client/data-events.js.map +1 -1
  12. package/lib/client/data-port.d.ts +24 -22
  13. package/lib/client/data-port.d.ts.map +1 -1
  14. package/lib/client/data-session.d.ts +471 -81
  15. package/lib/client/data-session.d.ts.map +1 -1
  16. package/lib/client/data-session.js +737 -108
  17. package/lib/client/data-session.js.map +1 -1
  18. package/lib/client/index.d.ts +14 -9
  19. package/lib/client/index.d.ts.map +1 -1
  20. package/lib/client/index.js +14 -9
  21. package/lib/client/index.js.map +1 -1
  22. package/lib/client/message-relay.d.ts +9 -3
  23. package/lib/client/message-relay.d.ts.map +1 -1
  24. package/lib/client/message-relay.js +11 -5
  25. package/lib/client/message-relay.js.map +1 -1
  26. package/lib/client/post-message-transport.d.ts +64 -3
  27. package/lib/client/post-message-transport.d.ts.map +1 -1
  28. package/lib/client/post-message-transport.js +175 -1
  29. package/lib/client/post-message-transport.js.map +1 -1
  30. package/lib/client/rpc-connection.d.ts +149 -0
  31. package/lib/client/rpc-connection.d.ts.map +1 -0
  32. package/lib/client/rpc-connection.js +202 -0
  33. package/lib/client/rpc-connection.js.map +1 -0
  34. package/lib/client-ids.d.ts +45 -0
  35. package/lib/client-ids.d.ts.map +1 -0
  36. package/lib/client-ids.js +48 -0
  37. package/lib/client-ids.js.map +1 -0
  38. package/lib/clock.d.ts +38 -0
  39. package/lib/clock.d.ts.map +1 -1
  40. package/lib/clock.js +36 -1
  41. package/lib/clock.js.map +1 -1
  42. package/lib/data/data-protocol-methods.d.ts +4 -4
  43. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  44. package/lib/data/data-protocol-methods.js +12 -1
  45. package/lib/data/data-protocol-methods.js.map +1 -1
  46. package/lib/data/data-server-protocol.d.ts +131 -41
  47. package/lib/data/data-server-protocol.d.ts.map +1 -1
  48. package/lib/data/events.d.ts +117 -21
  49. package/lib/data/events.d.ts.map +1 -1
  50. package/lib/data/requests.d.ts +69 -11
  51. package/lib/data/requests.d.ts.map +1 -1
  52. package/lib/debouncer.d.ts.map +1 -1
  53. package/lib/debouncer.js.map +1 -1
  54. package/lib/errors.d.ts +181 -29
  55. package/lib/errors.d.ts.map +1 -1
  56. package/lib/errors.js +261 -29
  57. package/lib/errors.js.map +1 -1
  58. package/lib/glsp-save-model-actions.d.ts +50 -0
  59. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  60. package/lib/glsp-save-model-actions.js +28 -0
  61. package/lib/glsp-save-model-actions.js.map +1 -0
  62. package/lib/index.d.ts +4 -0
  63. package/lib/index.d.ts.map +1 -1
  64. package/lib/index.js +7 -0
  65. package/lib/index.js.map +1 -1
  66. package/lib/latency-collector.d.ts +8 -4
  67. package/lib/latency-collector.d.ts.map +1 -1
  68. package/lib/latency-collector.js.map +1 -1
  69. package/lib/logger.d.ts +22 -1
  70. package/lib/logger.d.ts.map +1 -1
  71. package/lib/logger.js +31 -3
  72. package/lib/logger.js.map +1 -1
  73. package/lib/messages/index.d.ts +29 -0
  74. package/lib/messages/index.d.ts.map +1 -0
  75. package/lib/messages/index.js +59 -0
  76. package/lib/messages/index.js.map +1 -0
  77. package/lib/messages/primitives.d.ts +188 -0
  78. package/lib/messages/primitives.d.ts.map +1 -0
  79. package/lib/messages/primitives.js +161 -0
  80. package/lib/messages/primitives.js.map +1 -0
  81. package/lib/model-server.d.ts +60 -13
  82. package/lib/model-server.d.ts.map +1 -1
  83. package/lib/model-server.js +4 -2
  84. package/lib/model-server.js.map +1 -1
  85. package/lib/model-service/base-version.d.ts +64 -0
  86. package/lib/model-service/base-version.d.ts.map +1 -0
  87. package/lib/model-service/base-version.js +43 -0
  88. package/lib/model-service/base-version.js.map +1 -0
  89. package/lib/model-service/index.d.ts +1 -1
  90. package/lib/model-service/index.d.ts.map +1 -1
  91. package/lib/model-service/index.js +4 -5
  92. package/lib/model-service/index.js.map +1 -1
  93. package/lib/model-service/reference-candidate.d.ts +5 -3
  94. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  95. package/lib/noop-logger.d.ts.map +1 -1
  96. package/lib/noop-logger.js.map +1 -1
  97. package/lib/observable-value.js.map +1 -1
  98. package/lib/patch-merge.d.ts +35 -32
  99. package/lib/patch-merge.d.ts.map +1 -1
  100. package/lib/patch-merge.js +67 -23
  101. package/lib/patch-merge.js.map +1 -1
  102. package/lib/profile-session.d.ts +8 -4
  103. package/lib/profile-session.d.ts.map +1 -1
  104. package/lib/profile-session.js.map +1 -1
  105. package/lib/reconcile-write.d.ts +65 -0
  106. package/lib/reconcile-write.d.ts.map +1 -0
  107. package/lib/reconcile-write.js +67 -0
  108. package/lib/reconcile-write.js.map +1 -0
  109. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  110. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  111. package/lib/rpc/bind-rpc-methods.js +22 -3
  112. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  113. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  114. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  115. package/lib/rpc/create-rpc-proxy.js +12 -2
  116. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  117. package/lib/rpc/wire-prefix.js.map +1 -1
  118. package/lib/testing/catalogue-audit.d.ts +80 -0
  119. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  120. package/lib/testing/catalogue-audit.js +94 -0
  121. package/lib/testing/catalogue-audit.js.map +1 -0
  122. package/lib/testing/data-doubles.d.ts +13 -12
  123. package/lib/testing/data-doubles.d.ts.map +1 -1
  124. package/lib/testing/data-doubles.js +19 -5
  125. package/lib/testing/data-doubles.js.map +1 -1
  126. package/lib/testing/fake-clock.d.ts +9 -1
  127. package/lib/testing/fake-clock.d.ts.map +1 -1
  128. package/lib/testing/fake-clock.js +54 -45
  129. package/lib/testing/fake-clock.js.map +1 -1
  130. package/lib/testing/index.d.ts +1 -0
  131. package/lib/testing/index.d.ts.map +1 -1
  132. package/lib/testing/index.js +5 -2
  133. package/lib/testing/index.js.map +1 -1
  134. package/lib/testing/node/duplex-connection.js.map +1 -1
  135. package/lib/testing/node/duplex-stream.js.map +1 -1
  136. package/lib/testing/node/index.d.ts +1 -0
  137. package/lib/testing/node/index.d.ts.map +1 -1
  138. package/lib/testing/node/index.js +2 -2
  139. package/lib/testing/node/index.js.map +1 -1
  140. package/lib/testing/node/message-port-pair.d.ts +25 -0
  141. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  142. package/lib/testing/node/message-port-pair.js +26 -0
  143. package/lib/testing/node/message-port-pair.js.map +1 -0
  144. package/lib/testing/wait-for.js.map +1 -1
  145. package/lib/tracer.d.ts.map +1 -1
  146. package/lib/tracer.js.map +1 -1
  147. package/lib/transfer-diagnostic.d.ts +33 -0
  148. package/lib/transfer-diagnostic.d.ts.map +1 -1
  149. package/lib/transfer-diagnostic.js +23 -0
  150. package/lib/transfer-diagnostic.js.map +1 -1
  151. package/lib/transfer-document.d.ts +70 -32
  152. package/lib/transfer-document.d.ts.map +1 -1
  153. package/lib/transfer-document.js +17 -9
  154. package/lib/transfer-document.js.map +1 -1
  155. package/lib/uri.d.ts.map +1 -1
  156. package/lib/uri.js.map +1 -1
  157. package/lib/util.d.ts +8 -0
  158. package/lib/util.d.ts.map +1 -1
  159. package/lib/util.js +32 -0
  160. package/lib/util.js.map +1 -1
  161. package/package.json +27 -18
  162. package/src/client/data-connection.ts +314 -0
  163. package/src/client/data-events.ts +33 -1
  164. package/src/client/data-port.ts +25 -23
  165. package/src/client/data-session.ts +945 -126
  166. package/src/client/index.ts +14 -9
  167. package/src/client/message-relay.ts +29 -7
  168. package/src/client/post-message-transport.ts +219 -4
  169. package/src/client/rpc-connection.ts +268 -0
  170. package/src/client-ids.ts +49 -0
  171. package/src/clock.ts +56 -0
  172. package/src/data/data-protocol-methods.ts +13 -4
  173. package/src/data/data-server-protocol.ts +156 -41
  174. package/src/data/events.ts +123 -21
  175. package/src/data/requests.ts +74 -11
  176. package/src/errors.ts +311 -36
  177. package/src/glsp-save-model-actions.ts +59 -0
  178. package/src/index.ts +7 -0
  179. package/src/latency-collector.ts +8 -3
  180. package/src/logger.ts +28 -2
  181. package/src/messages/index.ts +36 -0
  182. package/src/messages/primitives.ts +271 -0
  183. package/src/model-server.ts +63 -18
  184. package/src/model-service/base-version.ts +72 -0
  185. package/src/model-service/index.ts +4 -5
  186. package/src/model-service/reference-candidate.ts +5 -3
  187. package/src/patch-merge.ts +97 -42
  188. package/src/profile-session.ts +9 -4
  189. package/src/reconcile-write.ts +124 -0
  190. package/src/rpc/bind-rpc-methods.ts +49 -4
  191. package/src/rpc/create-rpc-proxy.ts +20 -2
  192. package/src/testing/catalogue-audit.ts +111 -0
  193. package/src/testing/data-doubles.ts +42 -17
  194. package/src/testing/fake-clock.ts +62 -47
  195. package/src/testing/index.ts +5 -2
  196. package/src/testing/node/index.ts +2 -2
  197. package/src/testing/node/message-port-pair.ts +40 -0
  198. package/src/transfer-diagnostic.ts +40 -0
  199. package/src/transfer-document.ts +87 -34
  200. package/src/util.ts +33 -0
  201. package/lib/model-service/args.d.ts +0 -64
  202. package/lib/model-service/args.d.ts.map +0 -1
  203. package/lib/model-service/args.js +0 -11
  204. package/lib/model-service/args.js.map +0 -1
  205. 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
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/errors.ts CHANGED
@@ -8,49 +8,93 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { ResponseError } from 'vscode-jsonrpc';
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
+ */
25
+
26
+ /**
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}.
30
+ *
31
+ * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
32
+ * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
33
+ * That tier only ever works untranslated, which is why it is the last resort
34
+ * behind the numeric code rather than the primary check.
35
+ */
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.'
39
+ );
40
+
41
+ /**
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;
11
62
 
12
63
  /**
13
- * Application-specific JSON-RPC error code for {@link ConflictError}.
14
- * Outside the reserved range (-32768 .. -32000) per JSON-RPC 2.0.
64
+ * JSON-RPC error code for {@link ConflictError}.
15
65
  *
16
66
  * The code is the load-bearing identifier across realm boundaries —
17
67
  * `code` is a first-class field on the JSON-RPC error envelope and
18
68
  * survives wire reconstruction; the custom `Error` subclass name does
19
69
  * not.
20
70
  */
21
- export const CONFLICT_ERROR_CODE = 1001;
71
+ export const CONFLICT_ERROR_CODE = HYDRANIUM_ERROR_CODES.conflict;
22
72
 
23
- /**
24
- * Structured payload carried in {@link ConflictError.data}, and the only place
25
- * a post-RPC caller can read the version mismatch from.
26
- */
27
- export interface ConflictErrorData {
73
+ /** Structured payload carried in {@link ConflictError.data}. */
74
+ export interface ConflictErrorData extends HydraniumMessageData {
28
75
  readonly uri: string;
29
- /** The based-on version the caller authored against. */
30
- readonly expected: number;
76
+ /** The base version the caller authored against. */
77
+ readonly baseVersion: ModelVersion;
31
78
  /** The server's current text-document version at the time of the throw. */
32
- readonly actual: number;
79
+ readonly actualVersion: TextVersion;
33
80
  }
34
81
 
35
82
  /**
36
- * Thrown by `ModelService.update` / `ModelService.save` when the caller-
37
- * 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-
38
85
  * document version for the same URI — i.e. the snapshot the caller
39
86
  * authored against has been superseded by an intervening edit.
40
87
  *
41
88
  * Extends vscode-jsonrpc's {@link ResponseError} so the typed
42
89
  * {@link ConflictErrorData} payload rides on the standard JSON-RPC
43
90
  * error envelope (`code`, `message`, `data`) — all three fields are
44
- * preserved by RPC reconstruction. Adopters that catch the error on
45
- * the receiving side of an RPC call read the version mismatch from
46
- * `err.data` (the instance is reconstructed as a generic
47
- * `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.
48
94
  *
49
- * Detection is opt-in via the optional `baseVersion` field on
50
- * `TransferUpdateArgs` / `TransferSaveArgs`; callers that omit the field get
51
- * no gating. This mirrors LSP's `OptionalVersionedTextDocumentIdentifier`
52
- * posture, so headless / CLI / batch tooling with no meaningful based-on
53
- * 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.
54
98
  *
55
99
  * Three reasonable adopter recovery strategies:
56
100
  *
@@ -64,18 +108,23 @@ export interface ConflictErrorData {
64
108
  * No auto-retry or auto-merge ships by default.
65
109
  */
66
110
  export class ConflictError extends ResponseError<ConflictErrorData> {
67
- constructor(uri: string, expected: number, actual: number) {
68
- super(CONFLICT_ERROR_CODE, `Stale-based update for ${uri}: expected v${expected}, server is at v${actual}`, {
111
+ constructor(uri: string, baseVersion: ModelVersion, actualVersion: TextVersion) {
112
+ // The identity rides alongside the typed payload rather than replacing
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 }), {
69
116
  uri,
70
- expected,
71
- actual
117
+ baseVersion,
118
+ actualVersion,
119
+ ...messageData(STALE_BASE_VERSION_UPDATE, { uri })
72
120
  });
73
121
  this.name = 'ConflictError';
74
122
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
75
123
  // ResponseError.prototype)` to keep its own prototype chain intact across
76
124
  // transpilation targets; that resets us to ResponseError, hiding the
77
125
  // ConflictError-specific getters. Restore the prototype here so
78
- // `err.uri` / `.expected` / `.actual` resolve through this class.
126
+ // `err.uri` / `.baseVersion` / `.actualVersion` resolve through this
127
+ // class.
79
128
  Object.setPrototypeOf(this, ConflictError.prototype);
80
129
  }
81
130
 
@@ -83,19 +132,244 @@ export class ConflictError extends ResponseError<ConflictErrorData> {
83
132
  return this.data!.uri;
84
133
  }
85
134
 
86
- get expected(): number {
87
- 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;
88
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
+ );
89
210
 
90
- get actual(): number {
91
- return this.data!.actual;
211
+ /** Structured payload carried in {@link DocumentNotOpenError.data}. */
212
+ export interface DocumentNotOpenErrorData extends HydraniumMessageData {
213
+ readonly uri: string;
214
+ readonly clientId: string;
215
+ }
216
+
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;
92
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
+ * `error` as an instance of the typed error class its code names, with its
325
+ * message, data and stack kept, or `error` itself when its code names none or
326
+ * its data lacks the fields that class reads.
327
+ * An RPC reconstructs every rejection as a plain `ResponseError`, which has
328
+ * none of the class getters.
329
+ */
330
+ export function reviveProtocolError(error: unknown): unknown {
331
+ if (!(error instanceof ResponseError) || error.data === null || typeof error.data !== 'object') {
332
+ return error;
333
+ }
334
+ const revived = PROTOCOL_ERROR_REVIVERS.get(error.code)?.(error.data);
335
+ if (!revived) {
336
+ return error;
337
+ }
338
+ return Object.assign(revived, { message: error.message, data: error.data, stack: error.stack });
339
+ }
340
+
341
+ /**
342
+ * Whether `error` is a {@link SessionClosedError}: by name in-process, by code
343
+ * when it arrives as a plain `ResponseError`, through a path that does not
344
+ * {@link reviveProtocolError revive} it.
345
+ */
346
+ export function isSessionClosedError(error: unknown): error is SessionClosedError {
347
+ return hasErrorIdentity(error, 'SessionClosedError', SESSION_CLOSED_ERROR_CODE);
348
+ }
349
+
350
+ /** Whether `error` is a {@link DocumentNotOpenError}; see {@link isSessionClosedError}. */
351
+ export function isDocumentNotOpenError(error: unknown): error is DocumentNotOpenError {
352
+ return hasErrorIdentity(error, 'DocumentNotOpenError', DOCUMENT_NOT_OPEN_ERROR_CODE);
353
+ }
354
+
355
+ /** Whether `error` is a {@link DuplicateClientIdError}; see {@link isSessionClosedError}. */
356
+ export function isDuplicateClientIdError(error: unknown): error is DuplicateClientIdError {
357
+ return hasErrorIdentity(error, 'DuplicateClientIdError', DUPLICATE_CLIENT_ID_ERROR_CODE);
358
+ }
359
+
360
+ /** Whether `error` is a {@link ReservedClientIdError}; see {@link isSessionClosedError}. */
361
+ export function isReservedClientIdError(error: unknown): error is ReservedClientIdError {
362
+ return hasErrorIdentity(error, 'ReservedClientIdError', RESERVED_CLIENT_ID_ERROR_CODE);
363
+ }
364
+
365
+ function hasErrorIdentity(error: unknown, name: string, code: number): boolean {
366
+ return error instanceof Error && (error.name === name || (error as Partial<ResponseError<unknown>>).code === code);
93
367
  }
94
368
 
95
369
  /** Marker substring present in every {@link ConflictError} message, used by
96
370
  * {@link isConflictError} as a fallback when a transport re-wraps the error
97
371
  * and drops the JSON-RPC code. */
98
- const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
372
+ const CONFLICT_ERROR_MESSAGE_MARKER = ': it was made to an older version of the document';
99
373
 
100
374
  /**
101
375
  * Type guard for {@link ConflictError}. Detection ladder:
@@ -106,11 +380,12 @@ const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
106
380
  * canonical wire-side check; the JSON-RPC `code` field is preserved
107
381
  * across reconstruction, so any adopter catching after an RPC call
108
382
  * hits this branch.
109
- * 3. `error.message.includes('Stale-based update for ')` — fallback
110
- * for transports that re-wrap the message and drop the code (rare).
383
+ * 3. `error.message` contains the marker {@link STALE_BASE_VERSION_UPDATE}'s
384
+ * English carries — fallback for transports that re-wrap the message
385
+ * and drop the code (rare).
111
386
  *
112
- * `instanceof ConflictError` alone would silently return `false` on the
113
- * reconstructed shape, so callers do not use it.
387
+ * `instanceof ConflictError` alone returns `false` on a rejection that was
388
+ * not {@link reviveProtocolError revived}, so callers do not use it.
114
389
  */
115
390
  export function isConflictError(error: unknown): error is ConflictError {
116
391
  if (!(error instanceof Error)) {
@@ -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
+ }
package/src/index.ts CHANGED
@@ -16,15 +16,22 @@
16
16
 
17
17
  export * from './abstract-logger';
18
18
  export * from './client';
19
+ export * from './client-ids';
19
20
  export * from './clock';
20
21
  export * from './data';
21
22
  export * from './browser-runtime';
22
23
  export * from './debouncer';
24
+ export * from './glsp-save-model-actions';
23
25
  export * from './errors';
24
26
  export * from './host-diagnostics';
25
27
  export * from './logger';
26
28
  export * from './latency-collector';
29
+ // The primitives only. The `./messages` subpath additionally enumerates this
30
+ // package's own declarations, which the root barrel already re-exports through
31
+ // the modules that raise them.
32
+ export * from './messages/primitives';
27
33
  export * from './patch-merge';
34
+ export * from './reconcile-write';
28
35
  export * from './noop-logger';
29
36
  export * from './observable-value';
30
37
  export * from './profile-session';
@@ -87,8 +87,13 @@ export interface LatencyReport {
87
87
  */
88
88
  export type LatencyRetention = { readonly kind: 'keep-all' } | { readonly kind: 'ring-buffer'; readonly maxSamplesPerMethod: number };
89
89
 
90
- /** Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime totals. */
91
- interface MethodAccumulator {
90
+ /**
91
+ * Per-method state: retained samples (bounded in ring-buffer mode) plus lifetime
92
+ * totals. The mutable tally behind {@link MethodLatency}, which is the derived
93
+ * report row. Held by the `protected` {@link LatencyCollector.durations}, so a
94
+ * subclass recording its own samples has to name it.
95
+ */
96
+ export interface MethodLatencyTally {
92
97
  /** Retained durations for percentile estimation; capped in ring-buffer mode. Order is irrelevant (report sorts). */
93
98
  readonly samples: number[];
94
99
  /** Next slot to overwrite once the ring buffer is full (ring-buffer mode only). */
@@ -119,7 +124,7 @@ function percentile(sortedAscending: readonly number[], percent: number): number
119
124
  * deterministic on a fake clock.
120
125
  */
121
126
  export class LatencyCollector {
122
- protected readonly durations = new Map<string, MethodAccumulator>();
127
+ protected readonly durations = new Map<string, MethodLatencyTally>();
123
128
  protected window: Stopwatch;
124
129
 
125
130
  constructor(