@hydranium/protocol 1.0.0-next.13 → 1.0.0-next.132

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 (172) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-connection.d.ts +145 -0
  3. package/lib/client/data-connection.d.ts.map +1 -0
  4. package/lib/client/data-connection.js +205 -0
  5. package/lib/client/data-connection.js.map +1 -0
  6. package/lib/client/data-events.d.ts +13 -1
  7. package/lib/client/data-events.d.ts.map +1 -1
  8. package/lib/client/data-events.js +21 -0
  9. package/lib/client/data-events.js.map +1 -1
  10. package/lib/client/data-port.d.ts +17 -22
  11. package/lib/client/data-port.d.ts.map +1 -1
  12. package/lib/client/data-session.d.ts +301 -80
  13. package/lib/client/data-session.d.ts.map +1 -1
  14. package/lib/client/data-session.js +425 -107
  15. package/lib/client/data-session.js.map +1 -1
  16. package/lib/client/index.d.ts +13 -8
  17. package/lib/client/index.d.ts.map +1 -1
  18. package/lib/client/index.js +13 -8
  19. package/lib/client/index.js.map +1 -1
  20. package/lib/client/message-relay.d.ts +9 -3
  21. package/lib/client/message-relay.d.ts.map +1 -1
  22. package/lib/client/message-relay.js +11 -5
  23. package/lib/client/message-relay.js.map +1 -1
  24. package/lib/client/post-message-transport.d.ts +64 -3
  25. package/lib/client/post-message-transport.d.ts.map +1 -1
  26. package/lib/client/post-message-transport.js +175 -1
  27. package/lib/client/post-message-transport.js.map +1 -1
  28. package/lib/client/rpc-connection.d.ts +149 -0
  29. package/lib/client/rpc-connection.d.ts.map +1 -0
  30. package/lib/client/rpc-connection.js +179 -0
  31. package/lib/client/rpc-connection.js.map +1 -0
  32. package/lib/client-ids.d.ts +41 -0
  33. package/lib/client-ids.d.ts.map +1 -0
  34. package/lib/client-ids.js +44 -0
  35. package/lib/client-ids.js.map +1 -0
  36. package/lib/clock.d.ts +38 -0
  37. package/lib/clock.d.ts.map +1 -1
  38. package/lib/clock.js +36 -1
  39. package/lib/clock.js.map +1 -1
  40. package/lib/data/data-protocol-methods.d.ts +4 -4
  41. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  42. package/lib/data/data-protocol-methods.js +11 -1
  43. package/lib/data/data-protocol-methods.js.map +1 -1
  44. package/lib/data/data-server-protocol.d.ts +110 -31
  45. package/lib/data/data-server-protocol.d.ts.map +1 -1
  46. package/lib/data/events.d.ts +84 -3
  47. package/lib/data/events.d.ts.map +1 -1
  48. package/lib/data/requests.d.ts +67 -11
  49. package/lib/data/requests.d.ts.map +1 -1
  50. package/lib/errors.d.ts +102 -12
  51. package/lib/errors.d.ts.map +1 -1
  52. package/lib/errors.js +136 -18
  53. package/lib/errors.js.map +1 -1
  54. package/lib/glsp-save-model-actions.d.ts +50 -0
  55. package/lib/glsp-save-model-actions.d.ts.map +1 -0
  56. package/lib/glsp-save-model-actions.js +28 -0
  57. package/lib/glsp-save-model-actions.js.map +1 -0
  58. package/lib/index.d.ts +3 -0
  59. package/lib/index.d.ts.map +1 -1
  60. package/lib/index.js +6 -0
  61. package/lib/index.js.map +1 -1
  62. package/lib/latency-collector.d.ts +8 -4
  63. package/lib/latency-collector.d.ts.map +1 -1
  64. package/lib/latency-collector.js.map +1 -1
  65. package/lib/messages/index.d.ts +29 -0
  66. package/lib/messages/index.d.ts.map +1 -0
  67. package/lib/messages/index.js +56 -0
  68. package/lib/messages/index.js.map +1 -0
  69. package/lib/messages/primitives.d.ts +188 -0
  70. package/lib/messages/primitives.d.ts.map +1 -0
  71. package/lib/messages/primitives.js +161 -0
  72. package/lib/messages/primitives.js.map +1 -0
  73. package/lib/model-server.d.ts +44 -13
  74. package/lib/model-server.d.ts.map +1 -1
  75. package/lib/model-server.js +4 -2
  76. package/lib/model-server.js.map +1 -1
  77. package/lib/model-service/based-on.d.ts +57 -0
  78. package/lib/model-service/based-on.d.ts.map +1 -0
  79. package/lib/model-service/based-on.js +37 -0
  80. package/lib/model-service/based-on.js.map +1 -0
  81. package/lib/model-service/index.d.ts +1 -1
  82. package/lib/model-service/index.d.ts.map +1 -1
  83. package/lib/model-service/index.js +4 -5
  84. package/lib/model-service/index.js.map +1 -1
  85. package/lib/patch-merge.d.ts +28 -27
  86. package/lib/patch-merge.d.ts.map +1 -1
  87. package/lib/patch-merge.js +66 -22
  88. package/lib/patch-merge.js.map +1 -1
  89. package/lib/profile-session.d.ts +8 -4
  90. package/lib/profile-session.d.ts.map +1 -1
  91. package/lib/profile-session.js.map +1 -1
  92. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  93. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  94. package/lib/rpc/bind-rpc-methods.js +22 -3
  95. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  96. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  97. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  98. package/lib/rpc/create-rpc-proxy.js +6 -1
  99. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  100. package/lib/testing/catalogue-audit.d.ts +80 -0
  101. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  102. package/lib/testing/catalogue-audit.js +94 -0
  103. package/lib/testing/catalogue-audit.js.map +1 -0
  104. package/lib/testing/data-doubles.d.ts +13 -12
  105. package/lib/testing/data-doubles.d.ts.map +1 -1
  106. package/lib/testing/data-doubles.js +19 -5
  107. package/lib/testing/data-doubles.js.map +1 -1
  108. package/lib/testing/fake-clock.d.ts +9 -1
  109. package/lib/testing/fake-clock.d.ts.map +1 -1
  110. package/lib/testing/fake-clock.js +54 -45
  111. package/lib/testing/fake-clock.js.map +1 -1
  112. package/lib/testing/index.d.ts +1 -0
  113. package/lib/testing/index.d.ts.map +1 -1
  114. package/lib/testing/index.js +4 -1
  115. package/lib/testing/index.js.map +1 -1
  116. package/lib/testing/node/index.d.ts +1 -0
  117. package/lib/testing/node/index.d.ts.map +1 -1
  118. package/lib/testing/node/index.js +2 -2
  119. package/lib/testing/node/index.js.map +1 -1
  120. package/lib/testing/node/message-port-pair.d.ts +25 -0
  121. package/lib/testing/node/message-port-pair.d.ts.map +1 -0
  122. package/lib/testing/node/message-port-pair.js +26 -0
  123. package/lib/testing/node/message-port-pair.js.map +1 -0
  124. package/lib/transfer-diagnostic.d.ts +33 -0
  125. package/lib/transfer-diagnostic.d.ts.map +1 -1
  126. package/lib/transfer-diagnostic.js +23 -0
  127. package/lib/transfer-diagnostic.js.map +1 -1
  128. package/lib/transfer-document.d.ts +22 -5
  129. package/lib/transfer-document.d.ts.map +1 -1
  130. package/lib/transfer-document.js +14 -1
  131. package/lib/transfer-document.js.map +1 -1
  132. package/package.json +11 -2
  133. package/src/client/data-connection.ts +282 -0
  134. package/src/client/data-events.ts +33 -1
  135. package/src/client/data-port.ts +17 -23
  136. package/src/client/data-session.ts +549 -126
  137. package/src/client/index.ts +13 -8
  138. package/src/client/message-relay.ts +29 -7
  139. package/src/client/post-message-transport.ts +219 -4
  140. package/src/client/rpc-connection.ts +244 -0
  141. package/src/client-ids.ts +45 -0
  142. package/src/clock.ts +56 -0
  143. package/src/data/data-protocol-methods.ts +11 -3
  144. package/src/data/data-server-protocol.ts +131 -31
  145. package/src/data/events.ts +90 -3
  146. package/src/data/requests.ts +71 -11
  147. package/src/errors.ts +154 -20
  148. package/src/glsp-save-model-actions.ts +59 -0
  149. package/src/index.ts +6 -0
  150. package/src/latency-collector.ts +8 -3
  151. package/src/messages/index.ts +36 -0
  152. package/src/messages/primitives.ts +271 -0
  153. package/src/model-server.ts +47 -18
  154. package/src/model-service/based-on.ts +63 -0
  155. package/src/model-service/index.ts +4 -5
  156. package/src/patch-merge.ts +90 -37
  157. package/src/profile-session.ts +9 -4
  158. package/src/rpc/bind-rpc-methods.ts +49 -4
  159. package/src/rpc/create-rpc-proxy.ts +14 -1
  160. package/src/testing/catalogue-audit.ts +111 -0
  161. package/src/testing/data-doubles.ts +42 -17
  162. package/src/testing/fake-clock.ts +62 -47
  163. package/src/testing/index.ts +4 -1
  164. package/src/testing/node/index.ts +2 -2
  165. package/src/testing/node/message-port-pair.ts +40 -0
  166. package/src/transfer-diagnostic.ts +40 -0
  167. package/src/transfer-document.ts +29 -6
  168. package/lib/model-service/args.d.ts +0 -64
  169. package/lib/model-service/args.d.ts.map +0 -1
  170. package/lib/model-service/args.js +0 -11
  171. package/lib/model-service/args.js.map +0 -1
  172. package/src/model-service/args.ts +0 -67
@@ -14,17 +14,19 @@
14
14
  * over `TRoot`.
15
15
  */
16
16
 
17
- import type { TransferClientArgs } from './model-service/args';
18
17
  import type { ReferenceCandidate } from './model-service/reference-candidate';
19
18
 
20
19
  // ---------------------------------------------------------------------------
21
20
  // Client / server arguments
22
21
  // ---------------------------------------------------------------------------
23
22
 
24
- // `TransferClientArgs` / `TransferUpdateArgs` / `TransferSaveArgs` live in
25
- // `./model-service/args.ts` and are re-exported by the main barrel via
26
- // `./model-service`. The legacy LSP-style protocol (Open / Close / events)
27
- // defined here only consumes them as a supertype.
23
+ /** Identifies a client-document binding. */
24
+ export interface TransferClientArgs {
25
+ /** Document URI. */
26
+ uri: string;
27
+ /** Stable identifier for the client invoking the operation. */
28
+ clientId: string;
29
+ }
28
30
 
29
31
  /** Open a document on behalf of a client. */
30
32
  export interface OpenModelArgs extends TransferClientArgs {
@@ -47,10 +49,18 @@ export interface OpenModelArgs extends TransferClientArgs {
47
49
  * means read from the filesystem, which is the normal case.
48
50
  *
49
51
  * Honoured only on the first open of a URI: opening an already-open document
50
- * is a no-op, so passing `text` for one silently changes nothing. Write
51
- * through the update path instead.
52
+ * attaches the caller to the existing shared entry and does not replace its
53
+ * content with this seed. Write through the update path instead. The open
54
+ * response reads the current shared content after registration; a textual
55
+ * `didOpen` attach may separately refresh the build.
52
56
  */
53
57
  text?: string;
58
+ /**
59
+ * Kept on the server for this client's open until it closes, for the
60
+ * server's own open path to read. Only a client session's open keeps them,
61
+ * and a repeat open keeps the first open's.
62
+ */
63
+ options?: object;
54
64
  }
55
65
 
56
66
  /** Close a previously-opened document for the client. */
@@ -64,8 +74,8 @@ export interface CloseModelArgs extends TransferClientArgs {}
64
74
  export interface TransferUpdatedEvent<TDocument> {
65
75
  document: TDocument;
66
76
  sourceClientId: string;
67
- /** See `ModelDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
68
- reason: 'changed' | 'deleted' | 'rebuilt' | 'saved';
77
+ /** See `TransferDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
78
+ reason: 'changed' | 'rebuilt' | 'saved';
69
79
  }
70
80
 
71
81
  export interface TransferSavedEvent<TDocument> {
@@ -147,10 +157,10 @@ export function isElementSource(object: unknown): object is ElementSource {
147
157
  /** An element of a document that does not yet exist on disk — used during element creation flows. */
148
158
  export interface SyntheticSource {
149
159
  /**
150
- * The document the element would belong to. That document must already be
151
- * LOADED — the default resolution takes its parse root as the synthetic
152
- * node's container and answers `undefined` when it is not, so a URI for a
153
- * file that exists on disk but was never opened resolves to nothing.
160
+ * The document the element would belong to. It need not be loaded, or
161
+ * exist — an unloaded URI materialises a transient empty document, so a
162
+ * folder is a valid anchor. A URI that IS loaded contributes that
163
+ * document's parse root as the container, putting its contents in scope.
154
164
  */
155
165
  uri: string;
156
166
  /**
@@ -159,6 +169,16 @@ export interface SyntheticSource {
159
169
  * it is what scoping filters candidates against.
160
170
  */
161
171
  type: string;
172
+ /**
173
+ * The grammar the element will belong to, as a language id.
174
+ *
175
+ * Optional because `uri` and `type` each answer on their own when
176
+ * unambiguous. Set it when neither is: a URI naming no file carries no
177
+ * extension to route on, and a `type` two grammars can produce identifies
178
+ * neither. Unset, such a source reaches the server's own policy, which
179
+ * answers the same way for every caller.
180
+ */
181
+ language?: string;
162
182
  }
163
183
 
164
184
  export function isSyntheticSource(object: unknown): object is SyntheticSource {
@@ -183,8 +203,10 @@ export namespace ReferenceSource {
183
203
  export function element(name: string, type?: string): ElementSource {
184
204
  return { name, type };
185
205
  }
186
- export function synthetic(uri: string, type: string): SyntheticSource {
187
- return { uri, type };
206
+ export function synthetic(uri: string, type: string, language?: string): SyntheticSource {
207
+ // The key is omitted rather than set to `undefined`, so a source built
208
+ // without a language stays deep-equal to the two-argument form.
209
+ return language === undefined ? { uri, type } : { uri, type, language };
188
210
  }
189
211
  }
190
212
 
@@ -457,9 +479,10 @@ export interface FindNextNameArgs {
457
479
  */
458
480
  uri: string;
459
481
  /**
460
- * The AST `$type` of the element being named. Collisions are only looked for
461
- * among elements of that same type, so the returned name may still be taken
462
- * by an element of another type.
482
+ * The AST `$type` of the element being named. Collisions are looked for
483
+ * among elements of that type and of any subtype of it, so a supertype
484
+ * names a uniqueness scope its concrete types share; the returned name may
485
+ * still be taken by an element outside that hierarchy.
463
486
  */
464
487
  type: string;
465
488
  /**
@@ -476,4 +499,10 @@ export interface FindNextNameArgs {
476
499
  * See {@link NameTier} for what each tier covers.
477
500
  */
478
501
  tier?: NameTier;
502
+ /**
503
+ * The grammar to name under, routed as {@link SyntheticSource.language} —
504
+ * this call builds one. A caller that sets it there must set it here, or
505
+ * candidates and the name it proposes come from different grammars.
506
+ */
507
+ language?: string;
479
508
  }
@@ -0,0 +1,63 @@
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
+ declare const snapshotMarker: unique symbol;
11
+
12
+ /**
13
+ * A text-document version that came out of a SNAPSHOT read: a document
14
+ * envelope's `version`, which cannot move once the envelope exists.
15
+ *
16
+ * A plain number at runtime, usable anywhere a number is, and it travels the
17
+ * wire as one. The marker exists only so the compiler can tell it apart from a
18
+ * version read off a LIVE document, which is the same number type and is the
19
+ * defect the conflict gate exists to prevent: read at write time it is whatever
20
+ * the server is at now, which is the number the gate is about to compare it
21
+ * against, so the gate passes unconditionally and a concurrent edit is
22
+ * overwritten with nothing logged.
23
+ */
24
+ export type SnapshotVersion = number & { readonly [snapshotMarker]: true };
25
+
26
+ /**
27
+ * What a write declares it was based on: a version from a snapshot read, or
28
+ * `'anything'`.
29
+ *
30
+ * `'anything'` is a precondition that always holds — the write accepts whatever
31
+ * the server currently has, and therefore overwrites it. It is the honest
32
+ * answer wherever the write was authored against no particular server version,
33
+ * and a lie anywhere a reader handed the writer a document. The field carrying
34
+ * it is required, so an ungated write is a word someone chose rather than a
35
+ * field someone forgot.
36
+ */
37
+ export type BasedOn = SnapshotVersion | 'anything';
38
+
39
+ /**
40
+ * Whether `basedOn` names a version, and so arms the gate.
41
+ *
42
+ * Branch on this rather than on `basedOn !== 'anything'`, which reads as "not
43
+ * based on anything" — the opposite of what the branch tests.
44
+ */
45
+ export function isSnapshotVersion(basedOn: BasedOn): basedOn is SnapshotVersion {
46
+ return typeof basedOn === 'number';
47
+ }
48
+
49
+ /**
50
+ * Mark a version as having come from a snapshot read.
51
+ *
52
+ * **For the envelope constructors, not for callers.** Every door that builds a
53
+ * document envelope applies it on the way in, so anything a read returns
54
+ * already carries it and a writer never needs this. A caller reaching for it is
55
+ * asserting a provenance the compiler was about to deny — the read-late defect
56
+ * written out where a reviewer can see it.
57
+ */
58
+ export function asSnapshotVersion(version: number): SnapshotVersion {
59
+ return version as SnapshotVersion;
60
+ }
61
+
62
+ /** A snapshot version no write can match, so a write based on it conflicts. */
63
+ export const NO_MATCHING_VERSION: SnapshotVersion = asSnapshotVersion(-1);
@@ -7,10 +7,9 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- // Subpath barrel for the in-process `ModelService` facade contract. The
11
- // implementation lives in `@hydranium/core`; this package owns the
12
- // argument types so both the framework facade and the data-server wire
13
- // protocol can structurally agree on the lifecycle shape.
10
+ // Generic payload types the data protocol shares with core: the based-on
11
+ // version, which the server's model service checks writes against, and the
12
+ // reference candidates, which core's scope and completion code produce.
14
13
 
15
- export * from './args';
14
+ export * from './based-on';
16
15
  export * from './reference-candidate';
@@ -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,38 @@ 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`, and
56
+ * decides its own fallback (e.g. force-retry) on `no-op` / `unavailable`.
48
57
  */
49
58
  export type ReconcileOutcome<T> =
50
59
  | {
51
60
  /** The replay succeeded: the foreign writer touched no path the user did. */
52
61
  status: 'merged';
53
62
  /**
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.
63
+ * A new root built on theirs, carrying both intents. It is NOT the
64
+ * caller's `ours` root — take this value as the new base, or the next
65
+ * write diffs against state the server never had.
58
66
  */
59
67
  merged: T;
60
68
  }
61
69
  | {
62
70
  /**
63
- * The user's root already equalled the baseline, so the version gate
71
+ * The user's root already equalled the base, so the version gate
64
72
  * fired on drift that changed nothing. No refetch was performed and
65
73
  * there is nothing to persist — retrying the same write reproduces it.
66
74
  */
67
75
  status: 'no-op';
68
76
  }
69
77
  | {
70
- /** A guarded `test` op tripped: user and foreign writer touched one path. */
78
+ /** User and foreign writer changed one path, or both added the same element or key. */
71
79
  status: 'conflict';
72
80
  /**
73
81
  * The server's current root, refetched and unmodified — the user's
74
82
  * intent was NOT applied to it. Surface it and drop the write; treating
75
83
  * it as a merge result silently discards what the user typed.
76
84
  */
77
- fresh: T;
85
+ theirs: T;
78
86
  }
79
87
  | {
80
88
  /**
@@ -87,39 +95,84 @@ export type ReconcileOutcome<T> =
87
95
 
88
96
  /**
89
97
  * Shared three-way reconcile for a `ConflictError`: diff the user's intent
90
- * (`baseline → attempted`), refetch the server's current root, and replay the
98
+ * (`base → ours`), refetch the server's current root (theirs), and replay the
91
99
  * intent on top under strict, {@link augmentWithTestOps}-guarded `applyPatch`.
92
100
  *
93
- * - `no-op` — the user's root equals the baseline, so the gate fired on a
101
+ * - `no-op` — the user's root equals the base, so the gate fired on a
94
102
  * benign version drift; nothing to replay (refetch is skipped).
95
103
  * - `unavailable` — the refetch produced nothing; caller falls back.
96
104
  * - `merged` — the foreign writer touched only paths the user did not; the
97
105
  * merged root carries both intents.
98
- * - `conflict` — a same-path divergence tripped a `test` op; caller drops the
99
- * write and surfaces `fresh`.
106
+ * - `conflict` — a same-path divergence tripped a `test` op, or an `add`
107
+ * collides with one the foreign writer made; caller drops the write and
108
+ * surfaces `theirs`.
100
109
  *
101
110
  * 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
111
+ * `merged` result (update vs save, new base, UI refresh) stays at the call
103
112
  * site so form and GLSP paths keep their own persistence semantics.
104
113
  */
105
114
  export async function reconcileByPatchReplay<T extends object>(
106
- baseline: T,
107
- attempted: T,
115
+ base: T,
116
+ ours: T,
108
117
  refetch: () => Promise<T | undefined>
109
118
  ): Promise<ReconcileOutcome<T>> {
110
- const userPatch = compare(baseline, attempted);
119
+ const userPatch = compare(base, ours);
111
120
  if (userPatch.length === 0) {
112
121
  return { status: 'no-op' };
113
122
  }
114
- const fresh = await refetch();
115
- if (!fresh) {
123
+ const theirs = await refetch();
124
+ if (!theirs) {
116
125
  return { status: 'unavailable' };
117
126
  }
127
+ if (addsCollide(base, theirs, userPatch)) {
128
+ return { status: 'conflict', theirs };
129
+ }
118
130
  try {
119
- const merged = applyPatch(deepClone(fresh), augmentWithTestOps(baseline, userPatch), true).newDocument;
131
+ const merged = applyPatch(deepClone(theirs), augmentWithTestOps(base, userPatch), true).newDocument;
120
132
  return { status: 'merged', merged };
121
133
  } catch {
122
- return { status: 'conflict', fresh };
134
+ return { status: 'conflict', theirs };
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Whether an `add` of `userPatch` collides with one the foreign writer made:
140
+ * it inserts a value into an array that `theirs` holds more often than
141
+ * `base` did, or it adds an object key that `theirs` already holds.
142
+ *
143
+ * Replayed, the first inserts the value a second time and the second replaces
144
+ * the foreign value. Identical values conflict rather than being skipped:
145
+ * skipping drops one of two additions that merely happen to be equal.
146
+ */
147
+ function addsCollide(base: object, theirs: object, userPatch: readonly JsonPatchOperation[]): boolean {
148
+ // Through JSON, as `compare` clones the add values: an undefined-valued key
149
+ // in `theirs` would otherwise make an equal element count as another.
150
+ const comparable = JSON.parse(JSON.stringify(theirs)) as object;
151
+ return userPatch.some(op => {
152
+ if (op.op !== 'add') {
153
+ return false;
154
+ }
155
+ const cut = op.path.lastIndexOf('/');
156
+ const before = valueAt(base, op.path.slice(0, cut));
157
+ const now = valueAt(comparable, op.path.slice(0, cut));
158
+ if (Array.isArray(before)) {
159
+ return Array.isArray(now) && occurrences(now, op.value) > occurrences(before, op.value);
160
+ }
161
+ return typeof now === 'object' && now !== null && Object.hasOwn(now, unescapePathComponent(op.path.slice(cut + 1)));
162
+ });
163
+ }
164
+
165
+ /** How many elements of `array` deeply equal `value`, whatever their key order. */
166
+ function occurrences(array: readonly unknown[], value: unknown): number {
167
+ return array.filter(element => _areEquals(element, value)).length;
168
+ }
169
+
170
+ /** The value at `pointer`, or `undefined` when a step of it is missing. */
171
+ function valueAt(document: object, pointer: string): unknown {
172
+ try {
173
+ return getValueByPointer(document, pointer);
174
+ } catch {
175
+ return undefined;
123
176
  }
124
177
  }
125
178
 
@@ -132,12 +185,12 @@ export async function reconcileByPatchReplay<T extends object>(
132
185
  */
133
186
  export interface ConflictResolver {
134
187
  /**
135
- * Reconcile the user's `baseline → attempted` intent against the current
136
- * server state (`refetch`), returning a {@link ReconcileOutcome} the caller
188
+ * Reconcile the user's `base → ours` intent against the current
189
+ * server state (theirs, from `refetch`), returning a {@link ReconcileOutcome} the caller
137
190
  * acts on (persist `merged`, drop on `conflict`, fall back on `no-op` /
138
191
  * `unavailable`).
139
192
  */
140
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
193
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
141
194
  }
142
195
 
143
196
  /**
@@ -147,19 +200,19 @@ export interface ConflictResolver {
147
200
  * clobbered.
148
201
  */
149
202
  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);
203
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
204
+ return reconcileByPatchReplay(base, ours, refetch);
152
205
  }
153
206
  }
154
207
 
155
208
  /**
156
- * Last-writer-wins {@link ConflictResolver}: always reports the `attempted`
209
+ * Last-writer-wins {@link ConflictResolver}: always reports the `ours`
157
210
  * state as merged, without refetching or guarding. Suitable for single-client
158
211
  * tools or always-regenerated artifacts where a concurrent foreign edit may be
159
212
  * overwritten. A foreign edit to any field is clobbered.
160
213
  */
161
214
  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 };
215
+ async resolve<T extends object>(_base: T, ours: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
216
+ return { status: 'merged', merged: ours };
164
217
  }
165
218
  }
@@ -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];
@@ -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
  };
@@ -136,6 +136,14 @@ export interface CreateRpcProxyOptions<TLocal extends object = never> {
136
136
  * `bindRpcMethods` call) still capture per-method latency. Absent by default.
137
137
  */
138
138
  readonly latency?: BindRpcMethodsOptions['latency'];
139
+
140
+ /**
141
+ * Forwarded to the inbound {@link localTarget} binding: renders the message
142
+ * an outgoing rejection carries. Only the inbound direction has rejections
143
+ * to render — the outbound proxy is this side making requests, and a
144
+ * rejection it receives was rendered by whoever answered.
145
+ */
146
+ readonly renderErrorMessage?: BindRpcMethodsOptions['renderErrorMessage'];
139
147
  }
140
148
 
141
149
  /**
@@ -225,7 +233,12 @@ export function createRpcProxy<T extends object, TLocal extends object = never>(
225
233
  // connection; see `localTarget` for why no `Disposable` is surfaced.
226
234
  const { localTarget, localMethods } = options;
227
235
  if (localTarget && localMethods && localMethods.length > 0) {
228
- const binding = bindRpcMethods(connection, localTarget, localMethods, { methodNamespace, isNotification, latency: options.latency });
236
+ const binding = bindRpcMethods(connection, localTarget, localMethods, {
237
+ methodNamespace,
238
+ isNotification,
239
+ latency: options.latency,
240
+ renderErrorMessage: options.renderErrorMessage
241
+ });
229
242
  resolvedConnection.then(conn => conn.onClose(() => binding.dispose())).catch(() => undefined);
230
243
  }
231
244