@hydranium/protocol 1.0.0-next.23 → 1.0.0-next.232

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 (246) hide show
  1. package/README.md +40 -3
  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 +236 -0
  7. package/lib/client/data-connection.d.ts.map +1 -0
  8. package/lib/client/data-connection.js +404 -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 +27 -22
  15. package/lib/client/data-port.d.ts.map +1 -1
  16. package/lib/client/data-session.d.ts +473 -81
  17. package/lib/client/data-session.d.ts.map +1 -1
  18. package/lib/client/data-session.js +743 -108
  19. package/lib/client/data-session.js.map +1 -1
  20. package/lib/client/index.d.ts +14 -9
  21. package/lib/client/index.d.ts.map +1 -1
  22. package/lib/client/index.js +14 -9
  23. package/lib/client/index.js.map +1 -1
  24. package/lib/client/message-relay.d.ts +9 -3
  25. package/lib/client/message-relay.d.ts.map +1 -1
  26. package/lib/client/message-relay.js +11 -5
  27. package/lib/client/message-relay.js.map +1 -1
  28. package/lib/client/post-message-transport.d.ts +64 -3
  29. package/lib/client/post-message-transport.d.ts.map +1 -1
  30. package/lib/client/post-message-transport.js +175 -1
  31. package/lib/client/post-message-transport.js.map +1 -1
  32. package/lib/client/rpc-connection.d.ts +157 -0
  33. package/lib/client/rpc-connection.d.ts.map +1 -0
  34. package/lib/client/rpc-connection.js +214 -0
  35. package/lib/client/rpc-connection.js.map +1 -0
  36. package/lib/client-ids.d.ts +45 -0
  37. package/lib/client-ids.d.ts.map +1 -0
  38. package/lib/client-ids.js +48 -0
  39. package/lib/client-ids.js.map +1 -0
  40. package/lib/clock.d.ts +38 -0
  41. package/lib/clock.d.ts.map +1 -1
  42. package/lib/clock.js +36 -1
  43. package/lib/clock.js.map +1 -1
  44. package/lib/console-logger.d.ts +23 -0
  45. package/lib/console-logger.d.ts.map +1 -0
  46. package/lib/console-logger.js +39 -0
  47. package/lib/console-logger.js.map +1 -0
  48. package/lib/data/data-protocol-methods.d.ts +4 -4
  49. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  50. package/lib/data/data-protocol-methods.js +12 -1
  51. package/lib/data/data-protocol-methods.js.map +1 -1
  52. package/lib/data/data-server-protocol.d.ts +132 -41
  53. package/lib/data/data-server-protocol.d.ts.map +1 -1
  54. package/lib/data/events.d.ts +117 -21
  55. package/lib/data/events.d.ts.map +1 -1
  56. package/lib/data/requests.d.ts +69 -11
  57. package/lib/data/requests.d.ts.map +1 -1
  58. package/lib/debouncer.d.ts.map +1 -1
  59. package/lib/debouncer.js.map +1 -1
  60. package/lib/errors.d.ts +187 -29
  61. package/lib/errors.d.ts.map +1 -1
  62. package/lib/errors.js +270 -29
  63. package/lib/errors.js.map +1 -1
  64. package/lib/glsp-request-model-args.d.ts +16 -0
  65. package/lib/glsp-request-model-args.d.ts.map +1 -0
  66. package/lib/glsp-request-model-args.js +19 -0
  67. package/lib/glsp-request-model-args.js.map +1 -0
  68. package/lib/glsp-save-model-actions.d.ts +50 -0
  69. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  70. package/lib/glsp-save-model-actions.js +28 -0
  71. package/lib/glsp-save-model-actions.js.map +1 -0
  72. package/lib/index.d.ts +7 -0
  73. package/lib/index.d.ts.map +1 -1
  74. package/lib/index.js +10 -0
  75. package/lib/index.js.map +1 -1
  76. package/lib/latency-collector.d.ts +8 -4
  77. package/lib/latency-collector.d.ts.map +1 -1
  78. package/lib/latency-collector.js.map +1 -1
  79. package/lib/logger.d.ts +22 -1
  80. package/lib/logger.d.ts.map +1 -1
  81. package/lib/logger.js +31 -3
  82. package/lib/logger.js.map +1 -1
  83. package/lib/messages/index.d.ts +30 -0
  84. package/lib/messages/index.d.ts.map +1 -0
  85. package/lib/messages/index.js +62 -0
  86. package/lib/messages/index.js.map +1 -0
  87. package/lib/messages/primitives.d.ts +188 -0
  88. package/lib/messages/primitives.d.ts.map +1 -0
  89. package/lib/messages/primitives.js +161 -0
  90. package/lib/messages/primitives.js.map +1 -0
  91. package/lib/model-server.d.ts +60 -13
  92. package/lib/model-server.d.ts.map +1 -1
  93. package/lib/model-server.js +4 -2
  94. package/lib/model-server.js.map +1 -1
  95. package/lib/model-service/base-version.d.ts +64 -0
  96. package/lib/model-service/base-version.d.ts.map +1 -0
  97. package/lib/model-service/base-version.js +43 -0
  98. package/lib/model-service/base-version.js.map +1 -0
  99. package/lib/model-service/index.d.ts +1 -1
  100. package/lib/model-service/index.d.ts.map +1 -1
  101. package/lib/model-service/index.js +4 -5
  102. package/lib/model-service/index.js.map +1 -1
  103. package/lib/model-service/reference-candidate.d.ts +5 -3
  104. package/lib/model-service/reference-candidate.d.ts.map +1 -1
  105. package/lib/{model-service/args.js → node/index.d.ts} +2 -3
  106. package/lib/node/index.d.ts.map +1 -0
  107. package/lib/node/index.js +29 -0
  108. package/lib/node/index.js.map +1 -0
  109. package/lib/node/process-memory.d.ts +66 -0
  110. package/lib/node/process-memory.d.ts.map +1 -0
  111. package/lib/node/process-memory.js +291 -0
  112. package/lib/node/process-memory.js.map +1 -0
  113. package/lib/noop-logger.d.ts.map +1 -1
  114. package/lib/noop-logger.js.map +1 -1
  115. package/lib/observable-value.js.map +1 -1
  116. package/lib/patch-merge.d.ts +35 -32
  117. package/lib/patch-merge.d.ts.map +1 -1
  118. package/lib/patch-merge.js +67 -23
  119. package/lib/patch-merge.js.map +1 -1
  120. package/lib/profile-session.d.ts +8 -4
  121. package/lib/profile-session.d.ts.map +1 -1
  122. package/lib/profile-session.js.map +1 -1
  123. package/lib/random-uuid.d.ts +14 -0
  124. package/lib/random-uuid.d.ts.map +1 -0
  125. package/lib/random-uuid.js +24 -0
  126. package/lib/random-uuid.js.map +1 -0
  127. package/lib/reconcile-write.d.ts +65 -0
  128. package/lib/reconcile-write.d.ts.map +1 -0
  129. package/lib/reconcile-write.js +67 -0
  130. package/lib/reconcile-write.js.map +1 -0
  131. package/lib/rpc/bind-rpc-methods.d.ts +33 -3
  132. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  133. package/lib/rpc/bind-rpc-methods.js +32 -3
  134. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  135. package/lib/rpc/create-rpc-proxy.d.ts +10 -0
  136. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  137. package/lib/rpc/create-rpc-proxy.js +12 -2
  138. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  139. package/lib/rpc/index.d.ts +1 -0
  140. package/lib/rpc/index.d.ts.map +1 -1
  141. package/lib/rpc/index.js +1 -0
  142. package/lib/rpc/index.js.map +1 -1
  143. package/lib/rpc/send-by-method-name.d.ts +76 -0
  144. package/lib/rpc/send-by-method-name.d.ts.map +1 -0
  145. package/lib/rpc/send-by-method-name.js +120 -0
  146. package/lib/rpc/send-by-method-name.js.map +1 -0
  147. package/lib/rpc/wire-prefix.js.map +1 -1
  148. package/lib/testing/catalogue-audit.d.ts +80 -0
  149. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  150. package/lib/testing/catalogue-audit.js +94 -0
  151. package/lib/testing/catalogue-audit.js.map +1 -0
  152. package/lib/testing/data-doubles.d.ts +42 -15
  153. package/lib/testing/data-doubles.d.ts.map +1 -1
  154. package/lib/testing/data-doubles.js +58 -10
  155. package/lib/testing/data-doubles.js.map +1 -1
  156. package/lib/testing/fake-clock.d.ts +9 -1
  157. package/lib/testing/fake-clock.d.ts.map +1 -1
  158. package/lib/testing/fake-clock.js +54 -45
  159. package/lib/testing/fake-clock.js.map +1 -1
  160. package/lib/testing/index.d.ts +1 -0
  161. package/lib/testing/index.d.ts.map +1 -1
  162. package/lib/testing/index.js +5 -2
  163. package/lib/testing/index.js.map +1 -1
  164. package/lib/testing/node/duplex-connection.d.ts.map +1 -1
  165. package/lib/testing/node/duplex-connection.js +3 -2
  166. package/lib/testing/node/duplex-connection.js.map +1 -1
  167. package/lib/testing/node/duplex-stream.js.map +1 -1
  168. package/lib/testing/node/index.d.ts +1 -0
  169. package/lib/testing/node/index.d.ts.map +1 -1
  170. package/lib/testing/node/index.js +2 -2
  171. package/lib/testing/node/index.js.map +1 -1
  172. package/lib/testing/node/message-port-pair.d.ts +25 -0
  173. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  174. package/lib/testing/node/message-port-pair.js +26 -0
  175. package/lib/testing/node/message-port-pair.js.map +1 -0
  176. package/lib/testing/wait-for.js.map +1 -1
  177. package/lib/tracer.d.ts.map +1 -1
  178. package/lib/tracer.js.map +1 -1
  179. package/lib/transfer-diagnostic.d.ts +33 -0
  180. package/lib/transfer-diagnostic.d.ts.map +1 -1
  181. package/lib/transfer-diagnostic.js +23 -0
  182. package/lib/transfer-diagnostic.js.map +1 -1
  183. package/lib/transfer-document.d.ts +70 -32
  184. package/lib/transfer-document.d.ts.map +1 -1
  185. package/lib/transfer-document.js +17 -9
  186. package/lib/transfer-document.js.map +1 -1
  187. package/lib/uri.d.ts.map +1 -1
  188. package/lib/uri.js.map +1 -1
  189. package/lib/util.d.ts +8 -0
  190. package/lib/util.d.ts.map +1 -1
  191. package/lib/util.js +32 -0
  192. package/lib/util.js.map +1 -1
  193. package/package.json +29 -37
  194. package/src/abstract-logger.ts +8 -0
  195. package/src/client/data-connection.ts +502 -0
  196. package/src/client/data-events.ts +33 -1
  197. package/src/client/data-port.ts +29 -23
  198. package/src/client/data-session.ts +951 -126
  199. package/src/client/index.ts +14 -9
  200. package/src/client/message-relay.ts +29 -7
  201. package/src/client/post-message-transport.ts +219 -4
  202. package/src/client/rpc-connection.ts +281 -0
  203. package/src/client-ids.ts +49 -0
  204. package/src/clock.ts +56 -0
  205. package/src/console-logger.ts +39 -0
  206. package/src/data/data-protocol-methods.ts +13 -4
  207. package/src/data/data-server-protocol.ts +157 -41
  208. package/src/data/events.ts +123 -21
  209. package/src/data/requests.ts +74 -11
  210. package/src/errors.ts +322 -36
  211. package/src/glsp-request-model-args.ts +16 -0
  212. package/src/glsp-save-model-actions.ts +59 -0
  213. package/src/index.ts +10 -0
  214. package/src/latency-collector.ts +8 -3
  215. package/src/logger.ts +28 -2
  216. package/src/messages/index.ts +37 -0
  217. package/src/messages/primitives.ts +271 -0
  218. package/src/model-server.ts +63 -18
  219. package/src/model-service/base-version.ts +72 -0
  220. package/src/model-service/index.ts +4 -5
  221. package/src/model-service/reference-candidate.ts +5 -3
  222. package/src/node/index.ts +14 -0
  223. package/src/node/process-memory.ts +299 -0
  224. package/src/patch-merge.ts +97 -42
  225. package/src/profile-session.ts +9 -4
  226. package/src/random-uuid.ts +21 -0
  227. package/src/reconcile-write.ts +124 -0
  228. package/src/rpc/README.md +4 -5
  229. package/src/rpc/bind-rpc-methods.ts +59 -4
  230. package/src/rpc/create-rpc-proxy.ts +20 -2
  231. package/src/rpc/index.ts +1 -0
  232. package/src/rpc/send-by-method-name.ts +140 -0
  233. package/src/testing/catalogue-audit.ts +111 -0
  234. package/src/testing/data-doubles.ts +145 -25
  235. package/src/testing/fake-clock.ts +62 -47
  236. package/src/testing/index.ts +5 -2
  237. package/src/testing/node/duplex-connection.ts +3 -2
  238. package/src/testing/node/index.ts +2 -2
  239. package/src/testing/node/message-port-pair.ts +40 -0
  240. package/src/transfer-diagnostic.ts +40 -0
  241. package/src/transfer-document.ts +87 -34
  242. package/src/util.ts +33 -0
  243. package/lib/model-service/args.d.ts +0 -64
  244. package/lib/model-service/args.d.ts.map +0 -1
  245. package/lib/model-service/args.js.map +0 -1
  246. package/src/model-service/args.ts +0 -67
@@ -0,0 +1,124 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { type ConflictError, isConflictError } from './errors';
11
+ import { type BaseVersion, type ModelVersion } from './model-service/base-version';
12
+ import { type ConflictResolver } from './patch-merge';
13
+
14
+ const DEFAULT_MAX_WRITES = 3;
15
+
16
+ /** A model and the version of the text it was read from, which a write based on it names. */
17
+ export interface VersionedModel<TModel> {
18
+ readonly model: TModel;
19
+ readonly baseVersion: ModelVersion;
20
+ }
21
+
22
+ /** The I/O and policy a {@link reconcileWrite} call needs. */
23
+ export interface ReconcileWriteHooks<TModel> {
24
+ /**
25
+ * Write `model`. Called with the caller's own `baseVersion` first, with the
26
+ * refetch's on a merged write, and with `'any'` for a merge that refetched
27
+ * nothing, where the resolver has already decided to win.
28
+ */
29
+ persist(model: TModel, baseVersion: BaseVersion): Promise<void>;
30
+ /**
31
+ * Current server-side model, or `undefined` when unavailable. Its version is
32
+ * read in the tick its text is: a later one lets a merged write overwrite an
33
+ * edit the merge never saw.
34
+ */
35
+ refetch(): Promise<VersionedModel<TModel> | undefined>;
36
+ /** The last in-sync model the user's intent is measured against. */
37
+ readonly base: TModel;
38
+ readonly conflictResolver: ConflictResolver;
39
+ /** Writes, the first included, after which a still-conflicting edit is dropped; 3 when absent. */
40
+ readonly maxWrites?: number;
41
+ /** Runs when the refetch is unavailable; absent, the edit is left unwritten. */
42
+ onUnavailable?(model: TModel, conflict: ConflictError): Promise<void>;
43
+ }
44
+
45
+ /**
46
+ * What {@link reconcileWrite} did. Every status but `persisted` follows a
47
+ * conflict, and carries the last one and the writes made, the first included.
48
+ */
49
+ export type ReconcileWriteOutcome =
50
+ /** The first write landed. */
51
+ | { readonly status: 'persisted' }
52
+ | {
53
+ /**
54
+ * `merged`: a merged write landed. `unchanged`: the edit was empty, so the
55
+ * caller is behind the server. `conflict`: the resolver found a same-path
56
+ * collision. `dropped`: the writes ran out. `unavailable`: the refetch
57
+ * produced nothing and {@link ReconcileWriteHooks.onUnavailable} ran.
58
+ */
59
+ readonly status: 'merged' | 'unchanged' | 'conflict' | 'dropped' | 'unavailable';
60
+ readonly conflict: ConflictError;
61
+ readonly writes: number;
62
+ };
63
+
64
+ /**
65
+ * Persist `model`, and on a `ConflictError` reconcile the user's `base → model`
66
+ * intent onto the refetched server model and write the merge, gated on the
67
+ * refetch's version, again on each conflict up to `maxWrites` writes. A
68
+ * non-conflict error is re-thrown.
69
+ */
70
+ export async function reconcileWrite<TModel extends object>(
71
+ model: TModel,
72
+ baseVersion: BaseVersion,
73
+ hooks: ReconcileWriteHooks<TModel>
74
+ ): Promise<ReconcileWriteOutcome> {
75
+ let candidate = model;
76
+ let candidateBaseVersion = baseVersion;
77
+ let previous: ConflictError | undefined;
78
+ const maxWrites = hooks.maxWrites ?? DEFAULT_MAX_WRITES;
79
+ for (let writes = 1; ; writes++) {
80
+ const conflict = await persistOrConflict(hooks, candidate, candidateBaseVersion);
81
+ if (!conflict) {
82
+ return previous ? { status: 'merged', conflict: previous, writes } : { status: 'persisted' };
83
+ }
84
+ previous = conflict;
85
+ if (writes >= maxWrites) {
86
+ return { status: 'dropped', conflict, writes };
87
+ }
88
+ let refetched: VersionedModel<TModel> | undefined;
89
+ const outcome = await hooks.conflictResolver.resolve(hooks.base, model, async () => {
90
+ refetched = await hooks.refetch();
91
+ return refetched?.model;
92
+ });
93
+ switch (outcome.status) {
94
+ case 'merged':
95
+ candidate = outcome.merged;
96
+ candidateBaseVersion = refetched?.baseVersion ?? 'any';
97
+ continue;
98
+ case 'no-op':
99
+ return { status: 'unchanged', conflict, writes };
100
+ case 'conflict':
101
+ return { status: 'conflict', conflict, writes };
102
+ case 'unavailable':
103
+ await hooks.onUnavailable?.(model, conflict);
104
+ return { status: 'unavailable', conflict, writes };
105
+ }
106
+ }
107
+ }
108
+
109
+ /** The `ConflictError` the write raised, or `undefined` when it landed. */
110
+ async function persistOrConflict<TModel>(
111
+ hooks: ReconcileWriteHooks<TModel>,
112
+ model: TModel,
113
+ baseVersion: BaseVersion
114
+ ): Promise<ConflictError | undefined> {
115
+ try {
116
+ await hooks.persist(model, baseVersion);
117
+ return undefined;
118
+ } catch (err: unknown) {
119
+ if (!isConflictError(err)) {
120
+ throw err;
121
+ }
122
+ return err;
123
+ }
124
+ }
package/src/rpc/README.md CHANGED
@@ -1,9 +1,8 @@
1
1
  # JSON-RPC primitives
2
2
 
3
3
  Exported from the package root, `@hydranium/protocol`. There is no
4
- `@hydranium/protocol/rpc` subpath: the package's `exports` map publishes `.`,
5
- `./client`, `./data` and `./testing` (plus their `./lib/*` twins), so importing
6
- this directory by path fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`.
4
+ `@hydranium/protocol/rpc` subpath: the package's `exports` map declares none,
5
+ so importing this directory by path fails with `ERR_PACKAGE_PATH_NOT_EXPORTED`.
7
6
 
8
7
  Generic JSON-RPC primitives for typed protocol heads over a vscode-jsonrpc
9
8
  `MessageConnection`. This page is the reference; the shape of the pattern and
@@ -44,8 +43,8 @@ data-server head ships with `'data-server/'` by default; adopters that
44
43
  combine the data-server with their own protocol head under one prefix pass
45
44
  their adopter namespace (e.g. `'myapp/'`) on both sides.
46
45
 
47
- Trailing-slash discipline is the adopter's responsibility — `'foo'` is a
48
- literal prefix, not interpreted as a namespace segment.
46
+ A namespace ends in `/` or is empty: `bindRpcMethods` and `createRpcProxy`
47
+ throw a `TypeError` for `'foo'`.
49
48
 
50
49
  ### Notification discrimination: `isNotification`
51
50
 
@@ -7,7 +7,8 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import type { MessageConnection } from 'vscode-jsonrpc';
10
+ import { ResponseError, type MessageConnection } from 'vscode-jsonrpc';
11
+ import { isResponseError } from '../errors';
11
12
  import type { LatencyCollector } from '../latency-collector';
12
13
  import { type Disposable, DisposableCollection } from '../util';
13
14
  import { defaultIsNotification } from './create-rpc-proxy';
@@ -70,6 +71,44 @@ export interface BindRpcMethodsOptions {
70
71
  * Requests and notifications are both timed. Absent by default (no overhead).
71
72
  */
72
73
  readonly latency?: LatencyCollector;
74
+
75
+ /**
76
+ * Produce the `message` an outgoing rejection carries, so a user-facing
77
+ * error is rendered by the side that knows the reading user's language.
78
+ * Applied at this one chokepoint, which is what covers a caller's
79
+ * additional methods as well as the framework's own.
80
+ *
81
+ * Only a `ResponseError` is routed through it — a plain `Error` carries no
82
+ * identity to render from, and rewriting its message would relabel a
83
+ * developer-facing failure as a translated one. The rejection is
84
+ * RECONSTRUCTED rather than mutated, because the thrown value may be a
85
+ * shared constant; nothing is lost, since only `code`, `message` and `data`
86
+ * cross the wire and `instanceof` does not survive reconstruction anyway.
87
+ *
88
+ * Notifications are not covered, and "they have no reply channel" is only
89
+ * half the reason — a notification's own PAYLOAD can carry prose. What makes
90
+ * this sound is where that prose comes from: the only user-facing text on
91
+ * the data head's client surface is the diagnostics riding the
92
+ * document-updated and document-saved events, and those are read off
93
+ * `LangiumDocument.diagnostics`, which the document builder has already
94
+ * rendered at `Validated`. So they arrive rendered rather than escaping
95
+ * unrendered. A notification that ever carries prose of its OWN needs its
96
+ * own render at the raise site, as GLSP's actions do.
97
+ */
98
+ readonly renderErrorMessage?: (error: ResponseError<unknown>) => string;
99
+ }
100
+
101
+ /**
102
+ * The rejection to throw in place of `err`. A `ResponseError` from another copy
103
+ * of `vscode-jsonrpc` is rebuilt on this package's, since a connection keeps the
104
+ * code only of its own copy's errors; one from this copy is thrown as is, so a
105
+ * subclass keeps its `toJson`, unless `render` rewrites its message.
106
+ */
107
+ function renderRejection(err: unknown, render?: (error: ResponseError<unknown>) => string): unknown {
108
+ if (!isResponseError(err) || (!render && err instanceof ResponseError)) {
109
+ return err;
110
+ }
111
+ return new ResponseError(err.code, render ? render(err) : err.message, err.data);
73
112
  }
74
113
 
75
114
  /**
@@ -91,8 +130,14 @@ export interface BindRpcMethodsOptions {
91
130
  *
92
131
  * Errors thrown synchronously from a request handler — or surfaced as a
93
132
  * rejected promise — propagate back to the caller through vscode-jsonrpc's
94
- * standard error envelope. Errors from a notification handler cannot, and are
95
- * routed to {@link BindRpcMethodsOptions.onNotificationError} instead.
133
+ * standard error envelope, its message rendered when
134
+ * {@link BindRpcMethodsOptions.renderErrorMessage} is supplied. A
135
+ * `ResponseError` from another copy of `vscode-jsonrpc` is rebuilt on this
136
+ * package's copy, so its code and data reach the caller when `connection` comes
137
+ * from that copy too, as the framework's own connections do; over a connection
138
+ * from another copy the caller receives a generic `InternalError`. Errors from a
139
+ * notification handler cannot propagate, and are routed to
140
+ * {@link BindRpcMethodsOptions.onNotificationError} instead.
96
141
  *
97
142
  * Accepts either a ready connection or a `Promise<MessageConnection>` —
98
143
  * registrations queue until the connection resolves, then attach. The
@@ -154,7 +199,17 @@ export function bindRpcMethods<T extends object>(
154
199
  })
155
200
  );
156
201
  } else {
157
- disposables.push(resolved.onRequest(wireName, async (params: unknown) => dispatch(params)));
202
+ const render = options.renderErrorMessage;
203
+ disposables.push(
204
+ resolved.onRequest(wireName, async (params: unknown) => {
205
+ try {
206
+ // Awaited inside the try, or a rejected promise escapes it.
207
+ return await dispatch(params);
208
+ } catch (err: unknown) {
209
+ throw renderRejection(err, render);
210
+ }
211
+ })
212
+ );
158
213
  }
159
214
  }
160
215
  };
@@ -8,6 +8,7 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import { Emitter, type Event, type MessageConnection } from 'vscode-jsonrpc';
11
+ import { reviveProtocolError } from '../errors';
11
12
  import { type BindRpcMethodsOptions, bindRpcMethods } from './bind-rpc-methods';
12
13
  import { assertValidMethodNamespace } from './wire-prefix';
13
14
 
@@ -136,6 +137,14 @@ export interface CreateRpcProxyOptions<TLocal extends object = never> {
136
137
  * `bindRpcMethods` call) still capture per-method latency. Absent by default.
137
138
  */
138
139
  readonly latency?: BindRpcMethodsOptions['latency'];
140
+
141
+ /**
142
+ * Forwarded to the inbound {@link localTarget} binding: renders the message
143
+ * an outgoing rejection carries. Only the inbound direction has rejections
144
+ * to render — the outbound proxy is this side making requests, and a
145
+ * rejection it receives was rendered by whoever answered.
146
+ */
147
+ readonly renderErrorMessage?: BindRpcMethodsOptions['renderErrorMessage'];
139
148
  }
140
149
 
141
150
  /**
@@ -190,6 +199,9 @@ function assertSingleArg(wireName: string, args: unknown[]): void {
190
199
  * params, results and errors, and a second layer here would double every
191
200
  * traced line.
192
201
  *
202
+ * A rejection whose code names one of the framework's typed errors is rethrown
203
+ * as that class, through {@link reviveProtocolError}.
204
+ *
193
205
  * Accepts either a ready connection or a `Promise<MessageConnection>` —
194
206
  * proxy methods called before the promise resolves queue until it does,
195
207
  * then dispatch, so adopters can wire the proxy before its underlying
@@ -225,7 +237,12 @@ export function createRpcProxy<T extends object, TLocal extends object = never>(
225
237
  // connection; see `localTarget` for why no `Disposable` is surfaced.
226
238
  const { localTarget, localMethods } = options;
227
239
  if (localTarget && localMethods && localMethods.length > 0) {
228
- const binding = bindRpcMethods(connection, localTarget, localMethods, { methodNamespace, isNotification, latency: options.latency });
240
+ const binding = bindRpcMethods(connection, localTarget, localMethods, {
241
+ methodNamespace,
242
+ isNotification,
243
+ latency: options.latency,
244
+ renderErrorMessage: options.renderErrorMessage
245
+ });
229
246
  resolvedConnection.then(conn => conn.onClose(() => binding.dispose())).catch(() => undefined);
230
247
  }
231
248
 
@@ -280,7 +297,8 @@ export function createRpcProxy<T extends object, TLocal extends object = never>(
280
297
  const capturedError = new Error(`RPC request '${wireName}' failed`);
281
298
  return resolvedConnection
282
299
  .then(connection => connection.sendRequest(wireName, args[0]))
283
- .catch((err: unknown) => {
300
+ .catch((rejection: unknown) => {
301
+ const err = reviveProtocolError(rejection);
284
302
  if (err instanceof Error && capturedError.stack) {
285
303
  err.stack = `${err.stack ?? err.message}\nCaused by request from:\n${capturedError.stack}`;
286
304
  }
package/src/rpc/index.ts CHANGED
@@ -13,4 +13,5 @@
13
13
 
14
14
  export * from './bind-rpc-methods';
15
15
  export * from './create-rpc-proxy';
16
+ export * from './send-by-method-name';
16
17
  export * from './wire-prefix';
@@ -0,0 +1,140 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { CancellationToken } from 'vscode-jsonrpc';
11
+
12
+ /**
13
+ * `connection` with `sendRequest` and `sendNotification` sending a typed message
14
+ * by its method name, so it survives a message type built by another copy of
15
+ * `vscode-jsonrpc`. Wrap a connection wherever it is handed to code that sends
16
+ * another copy's typed messages, GLSP's clients and launchers in particular.
17
+ *
18
+ * **Why an install holds several copies.** Upstream pins exactly:
19
+ * - `@eclipse-glsp/*` 2.x pin `vscode-jsonrpc` `8.2.0`, and npm can nest a copy
20
+ * under each GLSP package, so GLSP's packages can split from each other: a
21
+ * connection one of them creates rejects the typed messages another builds.
22
+ * GLSP's upgrade to 9.x, which could let it share the framework's copy, is
23
+ * open as https://github.com/eclipse-glsp/glsp/issues/1720.
24
+ * - `vscode-languageserver@10.0.1` pins `vscode-languageserver-protocol`
25
+ * `3.18.1`, which pins `vscode-jsonrpc` `9.0.0`.
26
+ * - Theia brings protocol `3.17.5` and with it `vscode-jsonrpc` 8.
27
+ *
28
+ * npm hoists one version per name and nests the rest. `overrides` are read from
29
+ * the root manifest alone and never ship with a package, so the framework cannot
30
+ * collapse an adopter's tree.
31
+ *
32
+ * **What breaks across copies.**
33
+ * - Sending: a connection compares a typed message's parameter structure with
34
+ * its own copy's `ParameterStructures.auto` singleton by identity, so a
35
+ * `RequestType` or `NotificationType` built by another copy throws
36
+ * `Unknown parameter structure auto`. GLSP sends typed messages, in
37
+ * `BaseJsonrpcGLSPClient` and in `JsonrpcClientProxy.process`.
38
+ * `vscode-languageserver`'s connection resends by method name already, which
39
+ * is why LSP sends are unaffected.
40
+ * - Types: `ParameterStructures` has a private member, so TypeScript treats each
41
+ * copy's `MessageConnection` as a different type.
42
+ * - Errors: a connection keeps a thrown `ResponseError`'s code and data only
43
+ * when the error is an instance of its own copy's class, and sends a returned
44
+ * one of another copy as a successful result.
45
+ *
46
+ * **What is copy-safe.** Receiving a typed message from another copy, since the
47
+ * receive path compares only against its own `byName` and `byPosition`. With
48
+ * sends by method name, the LSP, data and GLSP heads run over a tree whose GLSP
49
+ * packages keep `vscode-jsonrpc` `8.2.0`.
50
+ *
51
+ * **How it works.** A `Proxy` whose `sendRequest` and `sendNotification` pass the
52
+ * typed message's `method` string; every other member is the connection's own.
53
+ * The parameters go out as the typed send packs them: the first
54
+ * `numberOfParams`, missing ones `null`, and a request's cancellation token
55
+ * from the position after them. Sent by method name, a single parameter goes by
56
+ * name when it is an object and by position otherwise, which matches `auto` and
57
+ * `byName` with an object, as `vscode-languageserver-protocol`'s types use it. A
58
+ * `byPosition` object or a `byName` non-object throws rather than going out in
59
+ * another shape, the packing read from the type's `toString()` since it cannot
60
+ * be compared by identity. So wrapping narrows what a connection accepts: its
61
+ * own copy sends such a type unwrapped. The result is typed as whichever copy's
62
+ * connection its context expects, or as `connection`'s own type without one.
63
+ * That type is the caller's assertion: it holds for the members both copies
64
+ * share, since the sends go by name and the receives are copy-safe.
65
+ *
66
+ * **Where it stops.** Errors: a rejection it produces is still its own copy's
67
+ * `ResponseError`, so recognise errors with `isResponseError`, and build a
68
+ * connection whose errors must keep their code from the framework's copy.
69
+ *
70
+ * See https://github.com/eclipse-emfcloud/hydranium/issues/279.
71
+ */
72
+ export function sendByMethodName<
73
+ In extends {
74
+ sendRequest<R>(method: string, ...params: unknown[]): Promise<R>;
75
+ sendNotification(method: string, ...params: unknown[]): Promise<void>;
76
+ },
77
+ Out extends {
78
+ sendRequest<R>(method: string, ...params: unknown[]): Promise<R>;
79
+ sendNotification(method: string, ...params: unknown[]): Promise<void>;
80
+ } = In
81
+ >(connection: In): Out {
82
+ const sendRequest = (type: string | TypedMessage, ...params: unknown[]) =>
83
+ typeof type === 'string'
84
+ ? connection.sendRequest(type, ...params)
85
+ : connection.sendRequest(type.method, ...argsOf(type, params, true));
86
+ const sendNotification = (type: string | TypedMessage, ...params: unknown[]) =>
87
+ typeof type === 'string'
88
+ ? connection.sendNotification(type, ...params)
89
+ : connection.sendNotification(type.method, ...argsOf(type, params, false));
90
+ const wrapped: Pick<In, 'sendRequest' | 'sendNotification'> = new Proxy(connection, {
91
+ get(target, property, receiver) {
92
+ if (property === 'sendRequest') {
93
+ return sendRequest;
94
+ }
95
+ if (property === 'sendNotification') {
96
+ return sendNotification;
97
+ }
98
+ return Reflect.get(target, property, receiver);
99
+ }
100
+ });
101
+ // Typed as the connection its context expects, which the doc above justifies.
102
+ return wrapped as Out;
103
+ }
104
+
105
+ /** A typed message as any copy of `vscode-jsonrpc` builds it, read by shape rather than identity. */
106
+ interface TypedMessage {
107
+ readonly method: string;
108
+ readonly numberOfParams: number;
109
+ readonly parameterStructures: { toString(): string };
110
+ }
111
+
112
+ /** Whether `vscode-jsonrpc` sends `param` by name under `auto`. */
113
+ function isNamedParam(param: unknown): boolean {
114
+ return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object';
115
+ }
116
+
117
+ /**
118
+ * The arguments that send `type` by method name with the typed send's params:
119
+ * the first `numberOfParams` of `params`, missing ones `null`, then a request's
120
+ * cancellation token, which the typed send takes from that position. A request
121
+ * always ends in a token, `CancellationToken.None` when it has none, since a
122
+ * send by method name takes a token-shaped last argument for its token. Throws
123
+ * for the one-parameter packing a send by method name cannot express.
124
+ */
125
+ function argsOf(type: TypedMessage, params: unknown[], isRequest: boolean): unknown[] {
126
+ const args = Array.from({ length: type.numberOfParams }, (_, i) => (i < params.length ? params[i] : null));
127
+ if (type.numberOfParams === 1) {
128
+ const packing = String(type.parameterStructures);
129
+ if ((packing === 'byPosition' && isNamedParam(args[0])) || (packing === 'byName' && !isNamedParam(args[0]))) {
130
+ throw new Error(
131
+ `sendByMethodName cannot send '${type.method}' ${packing}: by method name, a single object goes by name and anything else by position.`
132
+ );
133
+ }
134
+ }
135
+ if (!isRequest) {
136
+ return args;
137
+ }
138
+ const token = params[type.numberOfParams];
139
+ return [...args, CancellationToken.is(token) ? token : CancellationToken.None];
140
+ }
@@ -0,0 +1,111 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ import { collectMessages } from '../messages/primitives';
11
+
12
+ /**
13
+ * Audit a translation catalogue against the codes that actually exist.
14
+ *
15
+ * **The one failure mode a catalogue has, and the only one nothing else
16
+ * catches.** A key naming no declared code falls back to the English — which is
17
+ * byte-identical to a deliberate omission, so a typo is invisible at runtime and
18
+ * indistinguishable from the partial-catalogue behaviour every adopter relies
19
+ * on. Nothing on the render path can tell them apart, `theia nls-extract`
20
+ * reports what the SOURCE declares rather than whether a catalogue matches it,
21
+ * and the framework's own gates see only the framework's own files.
22
+ *
23
+ * Shipped as test support rather than as a runtime check on purpose: an
24
+ * orphaned key is an authoring mistake, and failing a server boot over one would
25
+ * take a running product down for a cosmetic defect.
26
+ */
27
+
28
+ /**
29
+ * Flatten a nested catalogue into the `/`-joined keys a message code is spelled
30
+ * with, dropping `_`-prefixed keys as notes to a human reader.
31
+ *
32
+ * Nesting is a HOST convention, not the framework's: Theia flattens a nested
33
+ * catalogue by joining keys with `/`, which is the separator a code already
34
+ * uses, so an adopter on that host writes the file nested and one handed
35
+ * straight to a `DefaultMessageRenderer` writes it flat. Both end up here.
36
+ *
37
+ * `_`-prefixed keys are dropped by PREFIX rather than by matching one literal
38
+ * name, so a second note added to a file cannot silently become a catalogue
39
+ * entry. A code is three `/`-separated segments, so no real entry can begin
40
+ * with `_`.
41
+ */
42
+ export function flattenCatalogue(catalogue: Record<string, unknown>, prefix = ''): Record<string, string> {
43
+ const flat: Record<string, string> = {};
44
+ for (const [key, value] of Object.entries(catalogue)) {
45
+ if (key.startsWith('_')) {
46
+ continue;
47
+ }
48
+ const joined = prefix ? `${prefix}/${key}` : key;
49
+ if (typeof value === 'string') {
50
+ flat[joined] = value;
51
+ } else if (typeof value === 'object' && value !== null) {
52
+ Object.assign(flat, flattenCatalogue(value as Record<string, unknown>, joined));
53
+ }
54
+ }
55
+ return flat;
56
+ }
57
+
58
+ /** Options for {@link findUndeclaredCodes}. */
59
+ export interface CatalogueAuditOptions {
60
+ /**
61
+ * Key prefixes to skip, for entries whose codes are NOT declared through a
62
+ * `defineMessage` barrel.
63
+ *
64
+ * The real case is a host's own mechanism: Theia's `nls.localize` takes its
65
+ * key as an inline literal at the call site, so those keys exist only in
66
+ * source text and no barrel can enumerate them. Keep this as narrow as the
67
+ * host layer actually is — exempting a namespace is exempting every typo in
68
+ * it, which is what this function exists to find.
69
+ */
70
+ readonly exemptPrefixes?: readonly string[];
71
+ }
72
+
73
+ /**
74
+ * Every catalogue key that names no code any of `barrels` declares.
75
+ *
76
+ * Barrels are taken as opaque objects and read with {@link collectMessages},
77
+ * which is what lets a caller pass a `import * as messages` namespace directly:
78
+ * a barrel's value type is a union of its declarations AND its functions, and
79
+ * filtering that union will not narrow to a `MessageDefinition`.
80
+ *
81
+ * Returns the offending keys rather than a boolean, so a failing assertion names
82
+ * WHICH key is wrong — a count says only that something is.
83
+ */
84
+ export function findUndeclaredCodes(
85
+ catalogueKeys: readonly string[],
86
+ barrels: readonly object[],
87
+ options: CatalogueAuditOptions = {}
88
+ ): string[] {
89
+ const declared = new Set(barrels.flatMap(barrel => collectMessages(barrel).map(message => message.code)));
90
+ const exempt = options.exemptPrefixes ?? [];
91
+ return catalogueKeys.filter(key => !exempt.some(prefix => key.startsWith(prefix)) && !declared.has(key));
92
+ }
93
+
94
+ /**
95
+ * Keys present in more than one catalogue — the shape a split catalogue rots
96
+ * into.
97
+ *
98
+ * Exactly one side renders a given message, so two catalogues holding one code
99
+ * are two authorities over one sentence and they diverge on the first reword.
100
+ * Nothing at runtime notices: both sides render, and whichever ran last wins on
101
+ * its own surface.
102
+ *
103
+ * Takes the key sets rather than a boolean answer for the same reason as
104
+ * {@link findUndeclaredCodes}, and reports NOTHING when a set is empty — an
105
+ * empty catalogue shares no key with anything, so a caller must assert
106
+ * non-emptiness separately or a failed read passes this vacuously.
107
+ */
108
+ export function findSharedCodes(first: readonly string[], second: readonly string[]): string[] {
109
+ const other = new Set(second);
110
+ return first.filter(key => other.has(key));
111
+ }