@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,34 +7,43 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { applyPatch, compare, deepClone, getValueByPointer, type Operation as JsonPatchOperation } from 'fast-json-patch';
10
+ import {
11
+ _areEquals,
12
+ applyPatch,
13
+ compare,
14
+ deepClone,
15
+ getValueByPointer,
16
+ type Operation as JsonPatchOperation,
17
+ unescapePathComponent
18
+ } from 'fast-json-patch';
11
19
 
12
20
  /**
13
- * Augment a user-intent JSON patch (computed `baseline → attempted`) with
21
+ * Augment a user-intent JSON patch (computed `base → ours`) with
14
22
  * `test` ops so a strict `applyPatch` against freshly-fetched server state
15
23
  * fails loudly when a foreign writer changed a path the user also changed.
16
24
  *
17
25
  * `fast-json-patch`'s `validateOperation: true` validates op structure and
18
26
  * path resolvability but NOT the pre-existing value — a plain `replace` /
19
27
  * `remove` silently overwrites whatever the foreign writer put there. For each
20
- * `replace` / `remove` op we prepend a `test` op carrying the baseline value at
28
+ * `replace` / `remove` op we prepend a `test` op carrying the base value at
21
29
  * that path, so a same-path divergence becomes a `TEST_OPERATION_FAILED` throw.
22
30
  * The caller treats that as a real field-level conflict (drop + refetch) rather
23
31
  * than silently clobbering the foreign edit.
24
32
  *
25
- * `add` ops are left unguarded: the path is new, so there is no baseline value
26
- * to test against, and add-vs-add overlaps are out of scope for this floor.
33
+ * `add` ops get no `test` op: the path is new, so there is no base value
34
+ * to test. {@link reconcileByPatchReplay} checks them against theirs
35
+ * instead; a caller applying this patch itself does not get that check.
27
36
  *
28
37
  * Used behind the framework's `ConflictError` contract by every reconcile
29
38
  * path — the GLSP recording command's undo/redo and forward-write, via
30
39
  * {@link ReconcilingConflictResolver}, and an adopter's form-widget save — so
31
40
  * they share one collision-detection rule.
32
41
  */
33
- export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
42
+ export function augmentWithTestOps(base: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
34
43
  const augmented: JsonPatchOperation[] = [];
35
44
  for (const op of userPatch) {
36
45
  if (op.op === 'replace' || op.op === 'remove') {
37
- augmented.push({ op: 'test', path: op.path, value: getValueByPointer(baseline, op.path) });
46
+ augmented.push({ op: 'test', path: op.path, value: getValueByPointer(base, op.path) });
38
47
  }
39
48
  augmented.push(op);
40
49
  }
@@ -42,39 +51,40 @@ export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<Js
42
51
  }
43
52
 
44
53
  /**
45
- * Outcome of {@link reconcileByPatchReplay}. The caller persists / re-baselines
46
- * on `merged`, drops + surfaces the `fresh` root on `conflict`, and decides its
47
- * own fallback (e.g. force-retry) on `no-op` / `unavailable`.
54
+ * Outcome of {@link reconcileByPatchReplay}. The caller persists `merged` and
55
+ * takes it as the new base, drops + surfaces the `theirs` root on `conflict`,
56
+ * catches up with the server on `no-op`, and decides its own fallback (e.g.
57
+ * force-retry) on `unavailable`.
48
58
  */
49
59
  export type ReconcileOutcome<T> =
50
60
  | {
51
61
  /** The replay succeeded: the foreign writer touched no path the user did. */
52
62
  status: 'merged';
53
63
  /**
54
- * A fresh root built on the refetched server state, carrying both
55
- * intents. It is NOT the caller's `attempted` root — re-baseline on
56
- * this value, or the next write diffs against state the server never
57
- * had.
64
+ * A new root built on theirs, carrying both intents. It is NOT the
65
+ * caller's `ours` root — take this value as the new base, or the next
66
+ * write diffs against state the server never had.
58
67
  */
59
68
  merged: T;
60
69
  }
61
70
  | {
62
71
  /**
63
- * The user's root already equalled the baseline, so the version gate
64
- * fired on drift that changed nothing. No refetch was performed and
65
- * there is nothing to persist — retrying the same write reproduces it.
72
+ * The user's root equalled the base, so the gate fired on another writer's
73
+ * change and the caller is behind the server (`ConflictError.actualVersion`).
74
+ * Nothing was refetched. Catch up from the update at that version or a later
75
+ * one, or refetch; forcing the write overwrites the other writer's change.
66
76
  */
67
77
  status: 'no-op';
68
78
  }
69
79
  | {
70
- /** A guarded `test` op tripped: user and foreign writer touched one path. */
80
+ /** User and foreign writer changed one path, or both added the same element or key. */
71
81
  status: 'conflict';
72
82
  /**
73
83
  * The server's current root, refetched and unmodified — the user's
74
84
  * intent was NOT applied to it. Surface it and drop the write; treating
75
85
  * it as a merge result silently discards what the user typed.
76
86
  */
77
- fresh: T;
87
+ theirs: T;
78
88
  }
79
89
  | {
80
90
  /**
@@ -87,39 +97,84 @@ export type ReconcileOutcome<T> =
87
97
 
88
98
  /**
89
99
  * Shared three-way reconcile for a `ConflictError`: diff the user's intent
90
- * (`baseline → attempted`), refetch the server's current root, and replay the
100
+ * (`base → ours`), refetch the server's current root (theirs), and replay the
91
101
  * intent on top under strict, {@link augmentWithTestOps}-guarded `applyPatch`.
92
102
  *
93
- * - `no-op` — the user's root equals the baseline, so the gate fired on a
94
- * benign version drift; nothing to replay (refetch is skipped).
103
+ * - `no-op` — the user's root equals the base: nothing to replay, and no
104
+ * refetch; the caller's document is behind the server's.
95
105
  * - `unavailable` — the refetch produced nothing; caller falls back.
96
106
  * - `merged` — the foreign writer touched only paths the user did not; the
97
107
  * merged root carries both intents.
98
- * - `conflict` — a same-path divergence tripped a `test` op; caller drops the
99
- * write and surfaces `fresh`.
108
+ * - `conflict` — a same-path divergence tripped a `test` op, or an `add`
109
+ * collides with one the foreign writer made; caller drops the write and
110
+ * surfaces `theirs`.
100
111
  *
101
112
  * I/O is the caller's: `refetch` supplies the current root, and applying the
102
- * `merged` result (update vs save, re-baseline, UI refresh) stays at the call
113
+ * `merged` result (update vs save, new base, UI refresh) stays at the call
103
114
  * site so form and GLSP paths keep their own persistence semantics.
104
115
  */
105
116
  export async function reconcileByPatchReplay<T extends object>(
106
- baseline: T,
107
- attempted: T,
117
+ base: T,
118
+ ours: T,
108
119
  refetch: () => Promise<T | undefined>
109
120
  ): Promise<ReconcileOutcome<T>> {
110
- const userPatch = compare(baseline, attempted);
121
+ const userPatch = compare(base, ours);
111
122
  if (userPatch.length === 0) {
112
123
  return { status: 'no-op' };
113
124
  }
114
- const fresh = await refetch();
115
- if (!fresh) {
125
+ const theirs = await refetch();
126
+ if (!theirs) {
116
127
  return { status: 'unavailable' };
117
128
  }
129
+ if (addsCollide(base, theirs, userPatch)) {
130
+ return { status: 'conflict', theirs };
131
+ }
118
132
  try {
119
- const merged = applyPatch(deepClone(fresh), augmentWithTestOps(baseline, userPatch), true).newDocument;
133
+ const merged = applyPatch(deepClone(theirs), augmentWithTestOps(base, userPatch), true).newDocument;
120
134
  return { status: 'merged', merged };
121
135
  } catch {
122
- return { status: 'conflict', fresh };
136
+ return { status: 'conflict', theirs };
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Whether an `add` of `userPatch` collides with one the foreign writer made:
142
+ * it inserts a value into an array that `theirs` holds more often than
143
+ * `base` did, or it adds an object key that `theirs` already holds.
144
+ *
145
+ * Replayed, the first inserts the value a second time and the second replaces
146
+ * the foreign value. Identical values conflict rather than being skipped:
147
+ * skipping drops one of two additions that merely happen to be equal.
148
+ */
149
+ function addsCollide(base: object, theirs: object, userPatch: readonly JsonPatchOperation[]): boolean {
150
+ // Through JSON, as `compare` clones the add values: an undefined-valued key
151
+ // in `theirs` would otherwise make an equal element count as another.
152
+ const comparable = JSON.parse(JSON.stringify(theirs)) as object;
153
+ return userPatch.some(op => {
154
+ if (op.op !== 'add') {
155
+ return false;
156
+ }
157
+ const cut = op.path.lastIndexOf('/');
158
+ const before = valueAt(base, op.path.slice(0, cut));
159
+ const now = valueAt(comparable, op.path.slice(0, cut));
160
+ if (Array.isArray(before)) {
161
+ return Array.isArray(now) && occurrences(now, op.value) > occurrences(before, op.value);
162
+ }
163
+ return typeof now === 'object' && now !== null && Object.hasOwn(now, unescapePathComponent(op.path.slice(cut + 1)));
164
+ });
165
+ }
166
+
167
+ /** How many elements of `array` deeply equal `value`, whatever their key order. */
168
+ function occurrences(array: readonly unknown[], value: unknown): number {
169
+ return array.filter(element => _areEquals(element, value)).length;
170
+ }
171
+
172
+ /** The value at `pointer`, or `undefined` when a step of it is missing. */
173
+ function valueAt(document: object, pointer: string): unknown {
174
+ try {
175
+ return getValueByPointer(document, pointer);
176
+ } catch {
177
+ return undefined;
123
178
  }
124
179
  }
125
180
 
@@ -132,12 +187,12 @@ export async function reconcileByPatchReplay<T extends object>(
132
187
  */
133
188
  export interface ConflictResolver {
134
189
  /**
135
- * Reconcile the user's `baseline → attempted` intent against the current
136
- * server state (`refetch`), returning a {@link ReconcileOutcome} the caller
137
- * acts on (persist `merged`, drop on `conflict`, fall back on `no-op` /
138
- * `unavailable`).
190
+ * Reconcile the user's `base → ours` intent against the current
191
+ * server state (theirs, from `refetch`), returning a {@link ReconcileOutcome} the caller
192
+ * acts on (persist `merged`, drop on `conflict`, catch up on `no-op`, fall
193
+ * back on `unavailable`).
139
194
  */
140
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
195
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
141
196
  }
142
197
 
143
198
  /**
@@ -147,19 +202,19 @@ export interface ConflictResolver {
147
202
  * clobbered.
148
203
  */
149
204
  export class ReconcilingConflictResolver implements ConflictResolver {
150
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
151
- return reconcileByPatchReplay(baseline, attempted, refetch);
205
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
206
+ return reconcileByPatchReplay(base, ours, refetch);
152
207
  }
153
208
  }
154
209
 
155
210
  /**
156
- * Last-writer-wins {@link ConflictResolver}: always reports the `attempted`
211
+ * Last-writer-wins {@link ConflictResolver}: always reports the `ours`
157
212
  * state as merged, without refetching or guarding. Suitable for single-client
158
213
  * tools or always-regenerated artifacts where a concurrent foreign edit may be
159
214
  * overwritten. A foreign edit to any field is clobbered.
160
215
  */
161
216
  export class ForceConflictResolver implements ConflictResolver {
162
- async resolve<T extends object>(_baseline: T, attempted: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
163
- return { status: 'merged', merged: attempted };
217
+ async resolve<T extends object>(_base: T, ours: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
218
+ return { status: 'merged', merged: ours };
164
219
  }
165
220
  }
@@ -62,7 +62,12 @@ export interface ProfileSession {
62
62
  records(): readonly ProfileRecord[];
63
63
  }
64
64
 
65
- interface ScopeFrame {
65
+ /**
66
+ * One in-flight {@link ProfileSession.scope} call. Held on the `protected`
67
+ * {@link DefaultProfileSession.stack} and named by
68
+ * {@link DefaultProfileSession.closeFrame}, so a subclass has to name it too.
69
+ */
70
+ export interface ProfileScopeFrame {
66
71
  readonly id: string;
67
72
  /** Session-stopwatch reading when this scope began. */
68
73
  readonly start: number;
@@ -78,7 +83,7 @@ interface ScopeFrame {
78
83
  export class DefaultProfileSession implements ProfileSession {
79
84
  /** Single monotonic timeline for the whole session; per-scope readings are deltas off it. */
80
85
  protected readonly sessionStopwatch: Stopwatch;
81
- protected readonly stack: ScopeFrame[] = [];
86
+ protected readonly stack: ProfileScopeFrame[] = [];
82
87
  protected readonly entries = new Map<string, number[]>();
83
88
 
84
89
  constructor(
@@ -92,7 +97,7 @@ export class DefaultProfileSession implements ProfileSession {
92
97
  scope<T>(id: string, fn: () => Promise<T>): Promise<T>;
93
98
  scope<T>(id: string, fn: () => T): T;
94
99
  scope<T>(id: string, fn: () => T | Promise<T>): T | Promise<T> {
95
- const frame: ScopeFrame = { id, start: this.sessionStopwatch.elapsedMs, childMs: 0 };
100
+ const frame: ProfileScopeFrame = { id, start: this.sessionStopwatch.elapsedMs, childMs: 0 };
96
101
  this.stack.push(frame);
97
102
  let result: T | Promise<T>;
98
103
  try {
@@ -118,7 +123,7 @@ export class DefaultProfileSession implements ProfileSession {
118
123
  }
119
124
 
120
125
  /** Pop `frame`, charge its full duration to the parent, and record its self-time. */
121
- protected closeFrame(frame: ScopeFrame): void {
126
+ protected closeFrame(frame: ProfileScopeFrame): void {
122
127
  this.stack.pop();
123
128
  const duration = this.sessionStopwatch.elapsedMs - frame.start;
124
129
  const parent = this.stack[this.stack.length - 1];
@@ -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
+ }
@@ -7,7 +7,7 @@
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
11
  import type { LatencyCollector } from '../latency-collector';
12
12
  import { type Disposable, DisposableCollection } from '../util';
13
13
  import { defaultIsNotification } from './create-rpc-proxy';
@@ -70,6 +70,36 @@ export interface BindRpcMethodsOptions {
70
70
  * Requests and notifications are both timed. Absent by default (no overhead).
71
71
  */
72
72
  readonly latency?: LatencyCollector;
73
+
74
+ /**
75
+ * Produce the `message` an outgoing rejection carries, so a user-facing
76
+ * error is rendered by the side that knows the reading user's language.
77
+ * Applied at this one chokepoint, which is what covers a caller's
78
+ * additional methods as well as the framework's own.
79
+ *
80
+ * Only a `ResponseError` is routed through it — a plain `Error` carries no
81
+ * identity to render from, and rewriting its message would relabel a
82
+ * developer-facing failure as a translated one. The rejection is
83
+ * RECONSTRUCTED rather than mutated, because the thrown value may be a
84
+ * shared constant; nothing is lost, since only `code`, `message` and `data`
85
+ * cross the wire and `instanceof` does not survive reconstruction anyway.
86
+ *
87
+ * Notifications are not covered, and "they have no reply channel" is only
88
+ * half the reason — a notification's own PAYLOAD can carry prose. What makes
89
+ * this sound is where that prose comes from: the only user-facing text on
90
+ * the data head's client surface is the diagnostics riding the
91
+ * document-updated and document-saved events, and those are read off
92
+ * `LangiumDocument.diagnostics`, which the document builder has already
93
+ * rendered at `Validated`. So they arrive rendered rather than escaping
94
+ * unrendered. A notification that ever carries prose of its OWN needs its
95
+ * own render at the raise site, as GLSP's actions do.
96
+ */
97
+ readonly renderErrorMessage?: (error: ResponseError<unknown>) => string;
98
+ }
99
+
100
+ /** The rejection to throw in place of `err`, with its message rendered. */
101
+ function renderRejection(err: unknown, render: (error: ResponseError<unknown>) => string): unknown {
102
+ return err instanceof ResponseError ? new ResponseError(err.code, render(err), err.data) : err;
73
103
  }
74
104
 
75
105
  /**
@@ -91,8 +121,10 @@ export interface BindRpcMethodsOptions {
91
121
  *
92
122
  * Errors thrown synchronously from a request handler — or surfaced as a
93
123
  * 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.
124
+ * standard error envelope, with the message rendered when
125
+ * {@link BindRpcMethodsOptions.renderErrorMessage} is supplied. Errors from a
126
+ * notification handler cannot propagate, and are routed to
127
+ * {@link BindRpcMethodsOptions.onNotificationError} instead.
96
128
  *
97
129
  * Accepts either a ready connection or a `Promise<MessageConnection>` —
98
130
  * registrations queue until the connection resolves, then attach. The
@@ -154,7 +186,20 @@ export function bindRpcMethods<T extends object>(
154
186
  })
155
187
  );
156
188
  } else {
157
- disposables.push(resolved.onRequest(wireName, async (params: unknown) => dispatch(params)));
189
+ const render = options.renderErrorMessage;
190
+ disposables.push(
191
+ resolved.onRequest(wireName, async (params: unknown) => {
192
+ if (!render) {
193
+ return dispatch(params);
194
+ }
195
+ try {
196
+ // Awaited inside the try, or a rejected promise escapes it.
197
+ return await dispatch(params);
198
+ } catch (err: unknown) {
199
+ throw renderRejection(err, render);
200
+ }
201
+ })
202
+ );
158
203
  }
159
204
  }
160
205
  };
@@ -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
  }
@@ -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
+ }