@hydranium/protocol 1.0.0-next.37 → 1.0.0-next.370

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 (294) hide show
  1. package/README.md +44 -83
  2. package/lib/abstract-logger.d.ts +11 -0
  3. package/lib/abstract-logger.d.ts.map +1 -1
  4. package/lib/abstract-logger.js +16 -0
  5. package/lib/abstract-logger.js.map +1 -1
  6. package/lib/client/data-connection.d.ts +303 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +534 -0
  9. package/lib/client/data-connection.js.map +1 -0
  10. package/lib/client/data-events.d.ts +18 -1
  11. package/lib/client/data-events.d.ts.map +1 -1
  12. package/lib/client/data-events.js +26 -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 +691 -89
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +1155 -115
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +15 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +15 -9
  23. package/lib/client/index.js.map +1 -1
  24. package/lib/client/message-relay.d.ts +6 -4
  25. package/lib/client/message-relay.d.ts.map +1 -1
  26. package/lib/client/message-relay.js +4 -4
  27. package/lib/client/message-relay.js.map +1 -1
  28. package/lib/client/post-message-transport.d.ts +69 -3
  29. package/lib/client/post-message-transport.d.ts.map +1 -1
  30. package/lib/client/post-message-transport.js +175 -1
  31. package/lib/client/post-message-transport.js.map +1 -1
  32. package/lib/client/rpc-connection.d.ts +173 -0
  33. package/lib/client/rpc-connection.d.ts.map +1 -0
  34. package/lib/client/rpc-connection.js +225 -0
  35. package/lib/client/rpc-connection.js.map +1 -0
  36. package/lib/client/worker-handshake.d.ts +94 -0
  37. package/lib/client/worker-handshake.d.ts.map +1 -0
  38. package/lib/client/worker-handshake.js +51 -0
  39. package/lib/client/worker-handshake.js.map +1 -0
  40. package/lib/client-ids.d.ts +45 -0
  41. package/lib/client-ids.d.ts.map +1 -0
  42. package/lib/client-ids.js +48 -0
  43. package/lib/client-ids.js.map +1 -0
  44. package/lib/clock.d.ts +50 -10
  45. package/lib/clock.d.ts.map +1 -1
  46. package/lib/clock.js +36 -1
  47. package/lib/clock.js.map +1 -1
  48. package/lib/console-logger.d.ts +23 -0
  49. package/lib/console-logger.d.ts.map +1 -0
  50. package/lib/console-logger.js +39 -0
  51. package/lib/console-logger.js.map +1 -0
  52. package/lib/data/data-protocol-methods.d.ts +4 -4
  53. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  54. package/lib/data/data-protocol-methods.js +13 -1
  55. package/lib/data/data-protocol-methods.js.map +1 -1
  56. package/lib/data/data-server-protocol.d.ts +171 -48
  57. package/lib/data/data-server-protocol.d.ts.map +1 -1
  58. package/lib/data/events.d.ts +144 -33
  59. package/lib/data/events.d.ts.map +1 -1
  60. package/lib/data/requests.d.ts +76 -11
  61. package/lib/data/requests.d.ts.map +1 -1
  62. package/lib/debouncer.d.ts +7 -4
  63. package/lib/debouncer.d.ts.map +1 -1
  64. package/lib/debouncer.js +10 -10
  65. package/lib/debouncer.js.map +1 -1
  66. package/lib/errors.d.ts +218 -41
  67. package/lib/errors.d.ts.map +1 -1
  68. package/lib/errors.js +364 -55
  69. package/lib/errors.js.map +1 -1
  70. package/lib/format-log-arg.d.ts +33 -0
  71. package/lib/format-log-arg.d.ts.map +1 -0
  72. package/lib/format-log-arg.js +158 -0
  73. package/lib/format-log-arg.js.map +1 -0
  74. package/lib/glsp-edits-settled-actions.d.ts +54 -0
  75. package/lib/glsp-edits-settled-actions.d.ts.map +1 -0
  76. package/lib/glsp-edits-settled-actions.js +28 -0
  77. package/lib/glsp-edits-settled-actions.js.map +1 -0
  78. package/lib/glsp-request-model-args.d.ts +16 -0
  79. package/lib/glsp-request-model-args.d.ts.map +1 -0
  80. package/lib/glsp-request-model-args.js +19 -0
  81. package/lib/glsp-request-model-args.js.map +1 -0
  82. package/lib/glsp-save-model-actions.d.ts +55 -0
  83. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  84. package/lib/glsp-save-model-actions.js +28 -0
  85. package/lib/glsp-save-model-actions.js.map +1 -0
  86. package/lib/index.d.ts +11 -0
  87. package/lib/index.d.ts.map +1 -1
  88. package/lib/index.js +11 -0
  89. package/lib/index.js.map +1 -1
  90. package/lib/latency-collector.d.ts +10 -4
  91. package/lib/latency-collector.d.ts.map +1 -1
  92. package/lib/latency-collector.js +2 -0
  93. package/lib/latency-collector.js.map +1 -1
  94. package/lib/logger.d.ts +38 -7
  95. package/lib/logger.d.ts.map +1 -1
  96. package/lib/logger.js +42 -4
  97. package/lib/logger.js.map +1 -1
  98. package/lib/messages/index.d.ts +4 -2
  99. package/lib/messages/index.d.ts.map +1 -1
  100. package/lib/messages/index.js +16 -4
  101. package/lib/messages/index.js.map +1 -1
  102. package/lib/messages/primitives.d.ts +59 -4
  103. package/lib/messages/primitives.d.ts.map +1 -1
  104. package/lib/messages/primitives.js +97 -4
  105. package/lib/messages/primitives.js.map +1 -1
  106. package/lib/model-server.d.ts +60 -13
  107. package/lib/model-server.d.ts.map +1 -1
  108. package/lib/model-server.js +4 -2
  109. package/lib/model-server.js.map +1 -1
  110. package/lib/model-service/base-version.d.ts +67 -0
  111. package/lib/model-service/base-version.d.ts.map +1 -0
  112. package/lib/model-service/base-version.js +44 -0
  113. package/lib/model-service/base-version.js.map +1 -0
  114. package/lib/model-service/index.d.ts +1 -1
  115. package/lib/model-service/index.d.ts.map +1 -1
  116. package/lib/model-service/index.js +4 -5
  117. package/lib/model-service/index.js.map +1 -1
  118. package/lib/model-service/reference-candidate.d.ts +5 -3
  119. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  120. package/lib/node/index.d.ts +10 -0
  121. package/lib/node/index.d.ts.map +1 -0
  122. package/lib/node/index.js +29 -0
  123. package/lib/node/index.js.map +1 -0
  124. package/lib/node/process-memory.d.ts +66 -0
  125. package/lib/node/process-memory.d.ts.map +1 -0
  126. package/lib/node/process-memory.js +291 -0
  127. package/lib/node/process-memory.js.map +1 -0
  128. package/lib/noop-logger.d.ts.map +1 -1
  129. package/lib/noop-logger.js.map +1 -1
  130. package/lib/observable-value.js.map +1 -1
  131. package/lib/patch-merge.d.ts +63 -35
  132. package/lib/patch-merge.d.ts.map +1 -1
  133. package/lib/patch-merge.js +171 -25
  134. package/lib/patch-merge.js.map +1 -1
  135. package/lib/pending-work-tracker.d.ts +30 -0
  136. package/lib/pending-work-tracker.d.ts.map +1 -0
  137. package/lib/pending-work-tracker.js +47 -0
  138. package/lib/pending-work-tracker.js.map +1 -0
  139. package/lib/profile-session.d.ts +24 -8
  140. package/lib/profile-session.d.ts.map +1 -1
  141. package/lib/profile-session.js +13 -4
  142. package/lib/profile-session.js.map +1 -1
  143. package/lib/profiling.d.ts +15 -2
  144. package/lib/profiling.d.ts.map +1 -1
  145. package/lib/profiling.js.map +1 -1
  146. package/lib/project.d.ts +4 -1
  147. package/lib/project.d.ts.map +1 -1
  148. package/lib/project.js.map +1 -1
  149. package/lib/random-uuid.d.ts +14 -0
  150. package/lib/random-uuid.d.ts.map +1 -0
  151. package/lib/random-uuid.js +24 -0
  152. package/lib/random-uuid.js.map +1 -0
  153. package/lib/reconcile-write.d.ts +70 -0
  154. package/lib/reconcile-write.d.ts.map +1 -0
  155. package/lib/reconcile-write.js +69 -0
  156. package/lib/reconcile-write.js.map +1 -0
  157. package/lib/rpc/bind-rpc-methods.d.ts +6 -2
  158. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  159. package/lib/rpc/bind-rpc-methods.js +17 -7
  160. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  161. package/lib/rpc/create-rpc-proxy.d.ts +3 -0
  162. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  163. package/lib/rpc/create-rpc-proxy.js +6 -1
  164. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  165. package/lib/rpc/index.d.ts +1 -0
  166. package/lib/rpc/index.d.ts.map +1 -1
  167. package/lib/rpc/index.js +1 -0
  168. package/lib/rpc/index.js.map +1 -1
  169. package/lib/rpc/send-by-method-name.d.ts +76 -0
  170. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  171. package/lib/rpc/send-by-method-name.js +120 -0
  172. package/lib/rpc/send-by-method-name.js.map +1 -0
  173. package/lib/rpc/wire-prefix.js.map +1 -1
  174. package/lib/save-text-document.d.ts +40 -0
  175. package/lib/save-text-document.d.ts.map +1 -0
  176. package/lib/save-text-document.js +34 -0
  177. package/lib/save-text-document.js.map +1 -0
  178. package/lib/testing/catalogue-audit.js.map +1 -1
  179. package/lib/testing/data-doubles.d.ts +41 -12
  180. package/lib/testing/data-doubles.d.ts.map +1 -1
  181. package/lib/testing/data-doubles.js +56 -8
  182. package/lib/testing/data-doubles.js.map +1 -1
  183. package/lib/testing/fake-clock.d.ts +17 -2
  184. package/lib/testing/fake-clock.d.ts.map +1 -1
  185. package/lib/testing/fake-clock.js +61 -46
  186. package/lib/testing/fake-clock.js.map +1 -1
  187. package/lib/testing/index.d.ts +1 -0
  188. package/lib/testing/index.d.ts.map +1 -1
  189. package/lib/testing/index.js +4 -3
  190. package/lib/testing/index.js.map +1 -1
  191. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  192. package/lib/testing/node/duplex-connection.js +3 -2
  193. package/lib/testing/node/duplex-connection.js.map +1 -1
  194. package/lib/testing/node/duplex-stream.js.map +1 -1
  195. package/lib/testing/node/index.d.ts +1 -0
  196. package/lib/testing/node/index.d.ts.map +1 -1
  197. package/lib/testing/node/index.js +2 -2
  198. package/lib/testing/node/index.js.map +1 -1
  199. package/lib/testing/node/message-port-pair.d.ts +25 -0
  200. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  201. package/lib/testing/node/message-port-pair.js +26 -0
  202. package/lib/testing/node/message-port-pair.js.map +1 -0
  203. package/lib/testing/transfer-node-builder.d.ts +81 -0
  204. package/lib/testing/transfer-node-builder.d.ts.map +1 -0
  205. package/lib/testing/transfer-node-builder.js +47 -0
  206. package/lib/testing/transfer-node-builder.js.map +1 -0
  207. package/lib/testing/wait-for.d.ts +9 -3
  208. package/lib/testing/wait-for.d.ts.map +1 -1
  209. package/lib/testing/wait-for.js +57 -11
  210. package/lib/testing/wait-for.js.map +1 -1
  211. package/lib/tracer.d.ts.map +1 -1
  212. package/lib/tracer.js +5 -9
  213. package/lib/tracer.js.map +1 -1
  214. package/lib/transfer-diagnostic.js.map +1 -1
  215. package/lib/transfer-document.d.ts +96 -32
  216. package/lib/transfer-document.d.ts.map +1 -1
  217. package/lib/transfer-document.js +17 -9
  218. package/lib/transfer-document.js.map +1 -1
  219. package/lib/transfer-element.d.ts +4 -4
  220. package/lib/types.d.ts +32 -0
  221. package/lib/types.d.ts.map +1 -0
  222. package/lib/{model-service/args.js → types.js} +2 -2
  223. package/lib/types.js.map +1 -0
  224. package/lib/uri.d.ts.map +1 -1
  225. package/lib/uri.js.map +1 -1
  226. package/lib/util.d.ts +8 -2
  227. package/lib/util.d.ts.map +1 -1
  228. package/lib/util.js +32 -4
  229. package/lib/util.js.map +1 -1
  230. package/package.json +24 -40
  231. package/src/abstract-logger.ts +18 -0
  232. package/src/client/data-connection.ts +654 -0
  233. package/src/client/data-events.ts +38 -1
  234. package/src/client/data-port.ts +36 -25
  235. package/src/client/data-session.ts +1476 -137
  236. package/src/client/index.ts +15 -9
  237. package/src/client/message-relay.ts +6 -4
  238. package/src/client/post-message-transport.ts +224 -4
  239. package/src/client/rpc-connection.ts +302 -0
  240. package/src/client/worker-handshake.ts +121 -0
  241. package/src/client-ids.ts +49 -0
  242. package/src/clock.ts +68 -10
  243. package/src/console-logger.ts +39 -0
  244. package/src/data/data-protocol-methods.ts +14 -4
  245. package/src/data/data-server-protocol.ts +198 -48
  246. package/src/data/events.ts +150 -33
  247. package/src/data/requests.ts +82 -11
  248. package/src/debouncer.ts +11 -11
  249. package/src/errors.ts +453 -65
  250. package/src/format-log-arg.ts +176 -0
  251. package/src/glsp-edits-settled-actions.ts +62 -0
  252. package/src/glsp-request-model-args.ts +16 -0
  253. package/src/glsp-save-model-actions.ts +64 -0
  254. package/src/index.ts +11 -0
  255. package/src/latency-collector.ts +10 -3
  256. package/src/logger.ts +44 -8
  257. package/src/messages/index.ts +11 -2
  258. package/src/messages/primitives.ts +129 -5
  259. package/src/model-server.ts +64 -19
  260. package/src/model-service/base-version.ts +75 -0
  261. package/src/model-service/index.ts +4 -5
  262. package/src/model-service/reference-candidate.ts +5 -3
  263. package/src/node/index.ts +14 -0
  264. package/src/node/process-memory.ts +299 -0
  265. package/src/patch-merge.ts +230 -45
  266. package/src/pending-work-tracker.ts +47 -0
  267. package/src/profile-session.ts +31 -11
  268. package/src/profiling.ts +15 -2
  269. package/src/project.ts +4 -1
  270. package/src/random-uuid.ts +21 -0
  271. package/src/reconcile-write.ts +131 -0
  272. package/src/rpc/README.md +6 -6
  273. package/src/rpc/bind-rpc-methods.ts +18 -8
  274. package/src/rpc/create-rpc-proxy.ts +6 -1
  275. package/src/rpc/index.ts +1 -0
  276. package/src/rpc/send-by-method-name.ts +140 -0
  277. package/src/save-text-document.ts +39 -0
  278. package/src/testing/data-doubles.ts +141 -19
  279. package/src/testing/fake-clock.ts +76 -48
  280. package/src/testing/index.ts +4 -3
  281. package/src/testing/node/duplex-connection.ts +3 -2
  282. package/src/testing/node/index.ts +2 -2
  283. package/src/testing/node/message-port-pair.ts +40 -0
  284. package/src/testing/transfer-node-builder.ts +107 -0
  285. package/src/testing/wait-for.ts +61 -13
  286. package/src/tracer.ts +5 -9
  287. package/src/transfer-document.ts +116 -34
  288. package/src/transfer-element.ts +4 -4
  289. package/src/types.ts +30 -0
  290. package/src/util.ts +33 -6
  291. package/lib/model-service/args.d.ts +0 -64
  292. package/lib/model-service/args.d.ts.map +0 -1
  293. package/lib/model-service/args.js.map +0 -1
  294. package/src/model-service/args.ts +0 -67
package/src/errors.ts CHANGED
@@ -9,62 +9,103 @@
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';
12
13
 
13
- /**
14
- * The catalogue declaration behind {@link ConflictError}'s sentence.
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`.
15
20
  *
16
- * Its English must keep containing {@link CONFLICT_ERROR_MESSAGE_MARKER}: the
17
- * marker is tier 3 of {@link isConflictError}'s ladder, and it matches on text.
18
- * That tier only ever works untranslated, which is why it is the last resort
19
- * behind the numeric code rather than the primary check.
20
- */
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}'
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
+ export const STALE_BASE_VERSION_UPDATE = defineMessage(
32
+ 'hydranium/protocol/stale-base-version-update',
33
+ 'The edit to {uri} was not applied: it was made to an older version of the document.'
34
+ );
35
+
36
+ /**
37
+ * {@link STALE_BASE_VERSION_UPDATE}'s counterpart for an editor's save the
38
+ * server refused, since the editor's buffer is not the text it holds.
39
+ */
40
+ export const STALE_BASE_VERSION_SAVE = defineMessage(
41
+ 'hydranium/protocol/stale-base-version-save',
42
+ 'The save of {uri} was not applied: it was made to an older version of the document.'
24
43
  );
25
44
 
26
45
  /**
27
- * Application-specific JSON-RPC error code for {@link ConflictError}.
28
- * Outside the reserved range (-32768 .. -32000) per JSON-RPC 2.0.
46
+ * Every JSON-RPC error code the framework raises, from any package, keyed by
47
+ * the error it identifies.
48
+ *
49
+ * The framework reserves the block 42000 to 42999 for these, and an adopter's
50
+ * own codes stay outside it: after an RPC the proxy revives an error by its
51
+ * code, so an adopter's error carrying one of these can read as the
52
+ * framework's. A new code takes the next unused number in the block, whichever
53
+ * package raises it, and is declared here, where tests hold every code distinct
54
+ * and inside the block.
55
+ * The block sits clear of the range JSON-RPC 2.0 reserves for itself, -32768
56
+ * to -32000.
57
+ */
58
+ export const HYDRANIUM_ERROR_CODES = {
59
+ conflict: 42001,
60
+ noActiveProfile: 42002,
61
+ referenceSettleTimeout: 42003,
62
+ sessionClosed: 42004,
63
+ documentNotOpen: 42005,
64
+ duplicateClientId: 42006,
65
+ reservedClientId: 42007,
66
+ saveFailed: 42008
67
+ } as const;
68
+
69
+ /**
70
+ * JSON-RPC error code for {@link ConflictError}.
29
71
  *
30
72
  * The code is the load-bearing identifier across realm boundaries —
31
73
  * `code` is a first-class field on the JSON-RPC error envelope and
32
74
  * survives wire reconstruction; the custom `Error` subclass name does
33
75
  * not.
34
76
  */
35
- export const CONFLICT_ERROR_CODE = 1001;
77
+ export const CONFLICT_ERROR_CODE = HYDRANIUM_ERROR_CODES.conflict;
36
78
 
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
- */
79
+ /** Structured payload carried in {@link ConflictError.data}. */
41
80
  export interface ConflictErrorData extends HydraniumMessageData {
81
+ /**
82
+ * The document whose version moved. A write of several documents names
83
+ * the first stale one in request order, and others may be stale too.
84
+ */
42
85
  readonly uri: string;
43
- /** The based-on version the caller authored against. */
44
- readonly expected: number;
86
+ /** The base version the caller authored against. */
87
+ readonly baseVersion: ModelVersion;
45
88
  /** The server's current text-document version at the time of the throw. */
46
- readonly actual: number;
89
+ readonly actualVersion: TextVersion;
47
90
  }
48
91
 
49
92
  /**
50
- * Thrown by `ModelService.update` / `ModelService.save` when the caller-
51
- * supplied based-on version no longer matches the server's current text-
93
+ * Thrown by a client session's `update` / `save` when the caller-
94
+ * supplied base version no longer matches the server's current text-
52
95
  * document version for the same URI — i.e. the snapshot the caller
53
96
  * authored against has been superseded by an intervening edit.
54
97
  *
55
98
  * Extends vscode-jsonrpc's {@link ResponseError} so the typed
56
99
  * {@link ConflictErrorData} payload rides on the standard JSON-RPC
57
100
  * 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).
101
+ * preserved by RPC reconstruction. `createRpcProxy` revives it into
102
+ * this class on the receiving side; a path that does not leaves a
103
+ * plain `ResponseError`, readable through `err.data` only and refused
104
+ * by {@link isConflictError}.
62
105
  *
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.
106
+ * Detection is driven by the required `baseVersion` field of every write
107
+ * request; a caller with no meaningful base version passes
108
+ * `'any'` and gets no gating.
68
109
  *
69
110
  * Three reasonable adopter recovery strategies:
70
111
  *
@@ -78,64 +119,411 @@ export interface ConflictErrorData extends HydraniumMessageData {
78
119
  * No auto-retry or auto-merge ships by default.
79
120
  */
80
121
  export class ConflictError extends ResponseError<ConflictErrorData> {
81
- constructor(uri: string, expected: number, actual: number) {
82
- const params = { uri, expected, actual };
122
+ /** `message` words what was refused: an edit, or with {@link STALE_BASE_VERSION_SAVE} a save. */
123
+ constructor(
124
+ uri: string,
125
+ baseVersion: ModelVersion,
126
+ actualVersion: TextVersion,
127
+ message: typeof STALE_BASE_VERSION_UPDATE | typeof STALE_BASE_VERSION_SAVE = STALE_BASE_VERSION_UPDATE
128
+ ) {
83
129
  // 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) });
130
+ // it. The getters, the guard and the reviver read the payload's fields,
131
+ // so adding the identity widens the payload rather than reshaping it.
132
+ super(CONFLICT_ERROR_CODE, message.format({ uri }), {
133
+ uri,
134
+ baseVersion,
135
+ actualVersion,
136
+ ...messageData(message, { uri })
137
+ });
87
138
  this.name = 'ConflictError';
88
139
  // ResponseError's constructor calls `Object.setPrototypeOf(this,
89
140
  // ResponseError.prototype)` to keep its own prototype chain intact across
90
141
  // transpilation targets; that resets us to ResponseError, hiding the
91
142
  // ConflictError-specific getters. Restore the prototype here so
92
- // `err.uri` / `.expected` / `.actual` resolve through this class.
143
+ // `err.uri` / `.baseVersion` / `.actualVersion` resolve through this
144
+ // class.
93
145
  Object.setPrototypeOf(this, ConflictError.prototype);
94
146
  }
95
147
 
148
+ /** The document whose version moved, see {@link ConflictErrorData.uri}. */
96
149
  get uri(): string {
97
150
  return this.data!.uri;
98
151
  }
99
152
 
100
- get expected(): number {
101
- return this.data!.expected;
153
+ /**
154
+ * The base version the caller authored against. Not `expected`, and its
155
+ * sibling not `actual`: a test reporter reads that pair as an assertion
156
+ * failure and reports nothing of the real one.
157
+ */
158
+ get baseVersion(): ModelVersion {
159
+ return this.data!.baseVersion;
102
160
  }
103
161
 
104
- get actual(): number {
105
- return this.data!.actual;
162
+ /** The server's version at the time of the throw. Not `actual`, see {@link baseVersion}. */
163
+ get actualVersion(): TextVersion {
164
+ return this.data!.actualVersion;
106
165
  }
107
166
  }
108
167
 
109
- /** Marker substring present in every {@link ConflictError} message, used by
110
- * {@link isConflictError} as a fallback when a transport re-wraps the error
111
- * and drops the JSON-RPC code. */
112
- const CONFLICT_ERROR_MESSAGE_MARKER = 'Stale-based update for ';
168
+ /**
169
+ * JSON-RPC code for {@link SessionClosedError}, beside {@link CONFLICT_ERROR_CODE}
170
+ * and for the same reason: the code survives reconstruction, the class does not.
171
+ */
172
+ export const SESSION_CLOSED_ERROR_CODE = HYDRANIUM_ERROR_CODES.sessionClosed;
173
+ /** JSON-RPC code for {@link DocumentNotOpenError}. */
174
+ export const DOCUMENT_NOT_OPEN_ERROR_CODE = HYDRANIUM_ERROR_CODES.documentNotOpen;
175
+ /** JSON-RPC code for {@link DuplicateClientIdError}. */
176
+ export const DUPLICATE_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.duplicateClientId;
177
+ /** JSON-RPC code for {@link ReservedClientIdError}. */
178
+ export const RESERVED_CLIENT_ID_ERROR_CODE = HYDRANIUM_ERROR_CODES.reservedClientId;
179
+ /** JSON-RPC code for {@link SaveFailedError}. */
180
+ export const SAVE_FAILED_ERROR_CODE = HYDRANIUM_ERROR_CODES.saveFailed;
181
+
182
+ /**
183
+ * The catalogue declaration behind {@link SessionClosedError}'s default
184
+ * sentence. It names no client id: the sentence can reach an end user, and the
185
+ * id stays in {@link SessionClosedErrorData.clientId} for whoever needs it.
186
+ */
187
+ export const SESSION_CLOSED = defineMessage('hydranium/protocol/session-closed', 'The editing session has ended.');
188
+
189
+ /** Structured payload carried in {@link SessionClosedError.data}. */
190
+ export interface SessionClosedErrorData extends HydraniumMessageData {
191
+ readonly clientId: string;
192
+ }
193
+
194
+ /**
195
+ * Thrown by every call on a client session after it ended, and by an open that
196
+ * was still in flight when its session ended: by the server for its sessions,
197
+ * and by a client-side `DataSession` once disposed, so a caller handles both
198
+ * the same way. A caller recognises it with {@link isSessionClosedError}, never
199
+ * by its sentence.
200
+ */
201
+ export class SessionClosedError extends ResponseError<SessionClosedErrorData> {
202
+ /**
203
+ * `message` replaces the default English, for a caller that knows more than
204
+ * that the session is gone. The identity stays {@link SESSION_CLOSED}'s, so a
205
+ * translating renderer renders the catalogue sentence in its place.
206
+ */
207
+ constructor(clientId: string, message = SESSION_CLOSED.format()) {
208
+ super(SESSION_CLOSED_ERROR_CODE, message, { clientId, ...messageData(SESSION_CLOSED) });
209
+ this.name = 'SessionClosedError';
210
+ // `ResponseError` resets the prototype to its own; see `ConflictError`.
211
+ Object.setPrototypeOf(this, SessionClosedError.prototype);
212
+ }
213
+
214
+ get clientId(): string {
215
+ return this.data!.clientId;
216
+ }
217
+ }
113
218
 
114
219
  /**
115
- * Type guard for {@link ConflictError}. Detection ladder:
220
+ * The catalogue declaration behind {@link DocumentNotOpenError}'s sentence. The
221
+ * client id stays in {@link DocumentNotOpenErrorData.clientId}.
222
+ */
223
+ export const DOCUMENT_NOT_OPEN = defineMessage(
224
+ 'hydranium/protocol/document-not-open',
225
+ 'The document {uri} is not open in this editing session.'
226
+ );
227
+
228
+ /** Structured payload carried in {@link DocumentNotOpenError.data}. */
229
+ export interface DocumentNotOpenErrorData extends HydraniumMessageData {
230
+ readonly uri: string;
231
+ readonly clientId: string;
232
+ }
233
+
234
+ /**
235
+ * Thrown when a client session writes a document it does not have open.
116
236
  *
117
- * 1. `error.name === 'ConflictError'` — direct in-process throw, no
118
- * RPC round-trip.
119
- * 2. `(error as ResponseError).code === CONFLICT_ERROR_CODE` — the
120
- * canonical wire-side check; the JSON-RPC `code` field is preserved
121
- * across reconstruction, so any adopter catching after an RPC call
122
- * 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).
237
+ * A session writes only what it has open, so this is the answer both to a write
238
+ * that never opened and to one whose open was closed underneath it — by the
239
+ * session itself, or by the document being deleted.
240
+ */
241
+ export class DocumentNotOpenError extends ResponseError<DocumentNotOpenErrorData> {
242
+ constructor(uri: string, clientId: string) {
243
+ super(DOCUMENT_NOT_OPEN_ERROR_CODE, DOCUMENT_NOT_OPEN.format({ uri }), {
244
+ uri,
245
+ clientId,
246
+ ...messageData(DOCUMENT_NOT_OPEN, { uri })
247
+ });
248
+ this.name = 'DocumentNotOpenError';
249
+ Object.setPrototypeOf(this, DocumentNotOpenError.prototype);
250
+ }
251
+
252
+ get uri(): string {
253
+ return this.data!.uri;
254
+ }
255
+
256
+ get clientId(): string {
257
+ return this.data!.clientId;
258
+ }
259
+ }
260
+
261
+ /**
262
+ * The catalogue declaration behind {@link DuplicateClientIdError}'s sentence.
263
+ * The client id stays in {@link DuplicateClientIdErrorData.clientId}.
264
+ */
265
+ export const DUPLICATE_CLIENT_ID = defineMessage(
266
+ 'hydranium/protocol/duplicate-client-id',
267
+ 'Could not start an editing session: its identifier is still in use by another editor.'
268
+ );
269
+
270
+ /** Structured payload carried in {@link DuplicateClientIdError.data}. */
271
+ export interface DuplicateClientIdErrorData extends HydraniumMessageData {
272
+ readonly clientId: string;
273
+ }
274
+
275
+ /**
276
+ * Thrown when a client session is started under an id that is already live in
277
+ * the process. The id frees up once its holder ends or closes its last
278
+ * document, so a caller may retry.
125
279
  *
126
- * `instanceof ConflictError` alone would silently return `false` on the
127
- * reconstructed shape, so callers do not use it.
280
+ * Ids are unique process-wide because the id is also the author label on every
281
+ * version and the key a client recognises its own echoes by; two participants
282
+ * sharing one would each take the other's writes for their own.
128
283
  */
129
- export function isConflictError(error: unknown): error is ConflictError {
130
- if (!(error instanceof Error)) {
131
- return false;
284
+ export class DuplicateClientIdError extends ResponseError<DuplicateClientIdErrorData> {
285
+ constructor(clientId: string) {
286
+ super(DUPLICATE_CLIENT_ID_ERROR_CODE, DUPLICATE_CLIENT_ID.format(), { clientId, ...messageData(DUPLICATE_CLIENT_ID) });
287
+ this.name = 'DuplicateClientIdError';
288
+ Object.setPrototypeOf(this, DuplicateClientIdError.prototype);
289
+ }
290
+
291
+ get clientId(): string {
292
+ return this.data!.clientId;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Thrown when a client session is started under an id the framework reserves
298
+ * for one of its own participants. A reserved id never frees up, so a caller
299
+ * that retries on {@link DuplicateClientIdError} stops on this one.
300
+ *
301
+ * It carries no message identity: a host that picks a reserved id has a bug,
302
+ * and no sentence addressed to an end user is true for it.
303
+ */
304
+ export class ReservedClientIdError extends ResponseError<{ readonly clientId: string }> {
305
+ constructor(clientId: string) {
306
+ super(RESERVED_CLIENT_ID_ERROR_CODE, `Client id ${clientId} is reserved for a framework participant`, { clientId });
307
+ this.name = 'ReservedClientIdError';
308
+ Object.setPrototypeOf(this, ReservedClientIdError.prototype);
309
+ }
310
+
311
+ get clientId(): string {
312
+ return this.data!.clientId;
313
+ }
314
+ }
315
+
316
+ /**
317
+ * The catalogue declaration behind {@link SaveFailedError}'s message. Its
318
+ * `failures` names each document with the writer's own reason, which stays as
319
+ * written.
320
+ */
321
+ export const SAVE_FAILED = defineMessage('hydranium/protocol/save-failed', 'Could not save {failures}.');
322
+
323
+ /** One document a save could not write, and why. */
324
+ export interface SaveFailure {
325
+ readonly uri: string;
326
+ readonly reason: string;
327
+ }
328
+
329
+ /** Structured payload carried in {@link SaveFailedError.data}. */
330
+ export interface SaveFailedErrorData extends HydraniumMessageData {
331
+ readonly failures: readonly SaveFailure[];
332
+ }
333
+
334
+ /**
335
+ * Thrown by a save that could not write one or more of its documents. A save
336
+ * of several documents writes the others, so the files on disk can be a mix
337
+ * until a later save succeeds.
338
+ */
339
+ export class SaveFailedError extends ResponseError<SaveFailedErrorData> {
340
+ constructor(failures: readonly SaveFailure[]) {
341
+ const named = failures.map(failure => `${failure.uri} (${failure.reason})`).join(', ');
342
+ super(SAVE_FAILED_ERROR_CODE, SAVE_FAILED.format({ failures: named }), {
343
+ failures,
344
+ ...messageData(SAVE_FAILED, { failures: named })
345
+ });
346
+ this.name = 'SaveFailedError';
347
+ Object.setPrototypeOf(this, SaveFailedError.prototype);
132
348
  }
133
- if (error.name === 'ConflictError') {
134
- return true;
349
+
350
+ get failures(): readonly SaveFailure[] {
351
+ return this.data!.failures;
135
352
  }
136
- const code = (error as Partial<ResponseError<unknown>>).code;
137
- if (code === CONFLICT_ERROR_CODE) {
138
- return true;
353
+ }
354
+
355
+ /**
356
+ * Rebuilds one typed error from the `data` that crossed the wire, or
357
+ * `undefined` when `data` lacks the fields the class reads.
358
+ */
359
+ type ProtocolErrorReviver = (data: Readonly<Record<string, unknown>>) => ResponseError<unknown> | undefined;
360
+
361
+ /** One entry per typed error class, keyed by its code; a class without one reaches a caller as a plain `ResponseError`. */
362
+ const PROTOCOL_ERROR_REVIVERS: ReadonlyMap<number, ProtocolErrorReviver> = new Map<number, ProtocolErrorReviver>([
363
+ [
364
+ CONFLICT_ERROR_CODE,
365
+ data => (hasConflictFields(data) ? new ConflictError(data.uri, asModelVersion(data.baseVersion), data.actualVersion) : undefined)
366
+ ],
367
+ [SESSION_CLOSED_ERROR_CODE, data => (hasClientId(data) ? new SessionClosedError(data.clientId) : undefined)],
368
+ [DOCUMENT_NOT_OPEN_ERROR_CODE, data => (hasDocumentNotOpenFields(data) ? new DocumentNotOpenError(data.uri, data.clientId) : undefined)],
369
+ [DUPLICATE_CLIENT_ID_ERROR_CODE, data => (hasClientId(data) ? new DuplicateClientIdError(data.clientId) : undefined)],
370
+ [RESERVED_CLIENT_ID_ERROR_CODE, data => (hasClientId(data) ? new ReservedClientIdError(data.clientId) : undefined)],
371
+ [SAVE_FAILED_ERROR_CODE, data => (hasSaveFailures(data) ? new SaveFailedError(data.failures) : undefined)]
372
+ ]);
373
+
374
+ // One check per class of the fields its getters read, run by its reviver on
375
+ // `data` and by its guard on the error, through the getters.
376
+ function hasConflictFields(value: unknown): value is { uri: string; baseVersion: number; actualVersion: TextVersion } {
377
+ return (
378
+ isRecord(value) && typeof value.uri === 'string' && typeof value.baseVersion === 'number' && typeof value.actualVersion === 'number'
379
+ );
380
+ }
381
+
382
+ function hasClientId(value: unknown): value is { clientId: string } {
383
+ return isRecord(value) && typeof value.clientId === 'string';
384
+ }
385
+
386
+ function hasDocumentNotOpenFields(value: unknown): value is { uri: string; clientId: string } {
387
+ return isRecord(value) && typeof value.uri === 'string' && typeof value.clientId === 'string';
388
+ }
389
+
390
+ function hasSaveFailures(value: unknown): value is { failures: SaveFailure[] } {
391
+ return isRecord(value) && isSaveFailureList(value.failures);
392
+ }
393
+
394
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
395
+ return typeof value === 'object' && value !== null;
396
+ }
397
+
398
+ function isSaveFailureList(value: unknown): value is SaveFailure[] {
399
+ return (
400
+ Array.isArray(value) &&
401
+ value.every(
402
+ (failure: unknown) =>
403
+ typeof failure === 'object' &&
404
+ failure !== null &&
405
+ 'uri' in failure &&
406
+ typeof failure.uri === 'string' &&
407
+ 'reason' in failure &&
408
+ typeof failure.reason === 'string'
409
+ )
410
+ );
411
+ }
412
+
413
+ /**
414
+ * Whether `error` is a `ResponseError` from any copy of `vscode-jsonrpc`. An
415
+ * install holds several copies, and `instanceof` recognises only its own. An
416
+ * error that merely carries an integer `code` has no `toJson`, and is not one.
417
+ */
418
+ export function isResponseError(error: unknown): error is ResponseError<unknown> {
419
+ return (
420
+ error instanceof Error && 'code' in error && Number.isInteger(error.code) && 'toJson' in error && typeof error.toJson === 'function'
421
+ );
422
+ }
423
+
424
+ /**
425
+ * `error` as an instance of the typed error class its code names, with its
426
+ * message, data and stack kept, or `error` itself when its code names none or
427
+ * its data lacks the fields that class reads.
428
+ * An RPC reconstructs every rejection as a plain `ResponseError`, which has
429
+ * none of the class getters.
430
+ */
431
+ export function reviveProtocolError(error: unknown): unknown {
432
+ if (!isResponseError(error) || error.data === null || typeof error.data !== 'object') {
433
+ return error;
434
+ }
435
+ const revived = PROTOCOL_ERROR_REVIVERS.get(error.code)?.({ ...error.data });
436
+ if (!revived) {
437
+ return error;
438
+ }
439
+ return Object.assign(revived, { message: error.message, data: error.data, stack: error.stack });
440
+ }
441
+
442
+ /**
443
+ * The error the JSON text `json` describes, as `JSON.stringify(error.toJson())`
444
+ * writes it, revived to its typed class as {@link reviveProtocolError} does, or
445
+ * `undefined` when `json` is not a JSON-RPC error envelope. For a transport
446
+ * that carries the error as text, such as a GLSP `RejectAction`'s `detail`.
447
+ */
448
+ export function reviveProtocolErrorJson(json: string): ResponseError<unknown> | undefined {
449
+ let envelope: unknown;
450
+ try {
451
+ envelope = JSON.parse(json);
452
+ } catch {
453
+ return undefined;
454
+ }
455
+ if (typeof envelope !== 'object' || envelope === null || !('code' in envelope) || !('message' in envelope)) {
456
+ return undefined;
457
+ }
458
+ const { code, message } = envelope;
459
+ if (typeof code !== 'number' || !Number.isInteger(code) || typeof message !== 'string') {
460
+ return undefined;
139
461
  }
140
- return typeof error.message === 'string' && error.message.includes(CONFLICT_ERROR_MESSAGE_MARKER);
462
+ const revived = reviveProtocolError(new ResponseError(code, message, 'data' in envelope ? envelope.data : undefined));
463
+ return isResponseError(revived) ? revived : undefined;
464
+ }
465
+
466
+ /**
467
+ * Mark `errorClass`'s prototype with a brand its guard checks, so every
468
+ * instance and every subclass carries it, and nothing else does. `Symbol.for`
469
+ * gives each copy of this package the same symbol, which `instanceof` does
470
+ * not, so the key must stay the same across releases.
471
+ */
472
+ function brand(errorClass: { readonly prototype: object }, name: string): symbol {
473
+ const key = Symbol.for(`hydranium/protocol/${name}`);
474
+ Object.defineProperty(errorClass.prototype, key, { value: true });
475
+ return key;
476
+ }
477
+
478
+ const CONFLICT_BRAND = brand(ConflictError, 'ConflictError');
479
+ const SESSION_CLOSED_BRAND = brand(SessionClosedError, 'SessionClosedError');
480
+ const DOCUMENT_NOT_OPEN_BRAND = brand(DocumentNotOpenError, 'DocumentNotOpenError');
481
+ const DUPLICATE_CLIENT_ID_BRAND = brand(DuplicateClientIdError, 'DuplicateClientIdError');
482
+ const RESERVED_CLIENT_ID_BRAND = brand(ReservedClientIdError, 'ReservedClientIdError');
483
+ const SAVE_FAILED_BRAND = brand(SaveFailedError, 'SaveFailedError');
484
+
485
+ /**
486
+ * Whether `error` is a {@link SessionClosedError} whose getters read valid
487
+ * fields: one thrown, or one {@link reviveProtocolError revived}, from any
488
+ * copy of this package, or a subclass. A bare `ResponseError` is not one,
489
+ * whatever its name and fields, since it lacks the class's brand.
490
+ * `createRpcProxy` revives every rejection, so only a caller on a connection
491
+ * of its own needs to revive first. Each guard below works the same way.
492
+ */
493
+ export function isSessionClosedError(error: unknown): error is SessionClosedError {
494
+ return hasBrand(error, SESSION_CLOSED_BRAND) && hasClientId(error);
495
+ }
496
+
497
+ /** Whether `error` is a {@link DocumentNotOpenError}. See {@link isSessionClosedError}. */
498
+ export function isDocumentNotOpenError(error: unknown): error is DocumentNotOpenError {
499
+ return hasBrand(error, DOCUMENT_NOT_OPEN_BRAND) && hasDocumentNotOpenFields(error);
500
+ }
501
+
502
+ /** Whether `error` is a {@link DuplicateClientIdError}. See {@link isSessionClosedError}. */
503
+ export function isDuplicateClientIdError(error: unknown): error is DuplicateClientIdError {
504
+ return hasBrand(error, DUPLICATE_CLIENT_ID_BRAND) && hasClientId(error);
505
+ }
506
+
507
+ /** Whether `error` is a {@link ReservedClientIdError}. See {@link isSessionClosedError}. */
508
+ export function isReservedClientIdError(error: unknown): error is ReservedClientIdError {
509
+ return hasBrand(error, RESERVED_CLIENT_ID_BRAND) && hasClientId(error);
510
+ }
511
+
512
+ /** Whether `error` is a {@link SaveFailedError}. See {@link isSessionClosedError}. */
513
+ export function isSaveFailedError(error: unknown): error is SaveFailedError {
514
+ return hasBrand(error, SAVE_FAILED_BRAND) && hasSaveFailures(error);
515
+ }
516
+
517
+ /** Whether `error` is a {@link ConflictError}. See {@link isSessionClosedError}. */
518
+ export function isConflictError(error: unknown): error is ConflictError {
519
+ return hasBrand(error, CONFLICT_BRAND) && hasConflictFields(error);
520
+ }
521
+
522
+ /**
523
+ * Whether `error` carries the brand `key` and the `data` record its getters
524
+ * read, so a guard can check the fields through them. A copy whose class
525
+ * lacks a getter fails that check, since the brand alone is public.
526
+ */
527
+ function hasBrand(error: unknown, key: symbol): error is ResponseError<unknown> {
528
+ return isResponseError(error) && Reflect.get(error, key) === true && isRecord(error.data);
141
529
  }