@hydranium/protocol 1.0.0-next.4 → 1.0.0-next.40

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 (84) hide show
  1. package/README.md +35 -1
  2. package/lib/client/data-events.d.ts +9 -1
  3. package/lib/client/data-events.d.ts.map +1 -1
  4. package/lib/client/data-events.js +14 -0
  5. package/lib/client/data-events.js.map +1 -1
  6. package/lib/client/data-port.d.ts +10 -3
  7. package/lib/client/data-port.d.ts.map +1 -1
  8. package/lib/client/data-session.d.ts +8 -0
  9. package/lib/client/data-session.d.ts.map +1 -1
  10. package/lib/client/data-session.js +12 -3
  11. package/lib/client/data-session.js.map +1 -1
  12. package/lib/client/message-relay.d.ts +8 -2
  13. package/lib/client/message-relay.d.ts.map +1 -1
  14. package/lib/client/message-relay.js +10 -4
  15. package/lib/client/message-relay.js.map +1 -1
  16. package/lib/data/data-protocol-methods.d.ts +2 -2
  17. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  18. package/lib/data/data-protocol-methods.js +6 -1
  19. package/lib/data/data-protocol-methods.js.map +1 -1
  20. package/lib/data/data-server-protocol.d.ts +21 -1
  21. package/lib/data/data-server-protocol.d.ts.map +1 -1
  22. package/lib/data/events.d.ts +70 -3
  23. package/lib/data/events.d.ts.map +1 -1
  24. package/lib/errors.d.ts +25 -6
  25. package/lib/errors.d.ts.map +1 -1
  26. package/lib/errors.js +32 -12
  27. package/lib/errors.js.map +1 -1
  28. package/lib/index.d.ts +1 -0
  29. package/lib/index.d.ts.map +1 -1
  30. package/lib/index.js +4 -0
  31. package/lib/index.js.map +1 -1
  32. package/lib/messages/index.d.ts +28 -0
  33. package/lib/messages/index.d.ts.map +1 -0
  34. package/lib/messages/index.js +52 -0
  35. package/lib/messages/index.js.map +1 -0
  36. package/lib/messages/primitives.d.ts +141 -0
  37. package/lib/messages/primitives.d.ts.map +1 -0
  38. package/lib/messages/primitives.js +138 -0
  39. package/lib/messages/primitives.js.map +1 -0
  40. package/lib/model-server.d.ts +2 -2
  41. package/lib/model-server.d.ts.map +1 -1
  42. package/lib/rpc/bind-rpc-methods.d.ts +29 -3
  43. package/lib/rpc/bind-rpc-methods.d.ts.map +1 -1
  44. package/lib/rpc/bind-rpc-methods.js +22 -3
  45. package/lib/rpc/bind-rpc-methods.js.map +1 -1
  46. package/lib/rpc/create-rpc-proxy.d.ts +7 -0
  47. package/lib/rpc/create-rpc-proxy.d.ts.map +1 -1
  48. package/lib/rpc/create-rpc-proxy.js +6 -1
  49. package/lib/rpc/create-rpc-proxy.js.map +1 -1
  50. package/lib/testing/catalogue-audit.d.ts +80 -0
  51. package/lib/testing/catalogue-audit.d.ts.map +1 -0
  52. package/lib/testing/catalogue-audit.js +94 -0
  53. package/lib/testing/catalogue-audit.js.map +1 -0
  54. package/lib/testing/data-doubles.d.ts +11 -5
  55. package/lib/testing/data-doubles.d.ts.map +1 -1
  56. package/lib/testing/data-doubles.js +14 -4
  57. package/lib/testing/data-doubles.js.map +1 -1
  58. package/lib/testing/index.d.ts +1 -0
  59. package/lib/testing/index.d.ts.map +1 -1
  60. package/lib/testing/index.js +4 -1
  61. package/lib/testing/index.js.map +1 -1
  62. package/lib/transfer-diagnostic.d.ts +33 -0
  63. package/lib/transfer-diagnostic.d.ts.map +1 -1
  64. package/lib/transfer-diagnostic.js +23 -0
  65. package/lib/transfer-diagnostic.js.map +1 -1
  66. package/package.json +11 -2
  67. package/src/client/data-events.ts +24 -1
  68. package/src/client/data-port.ts +10 -3
  69. package/src/client/data-session.ts +21 -2
  70. package/src/client/message-relay.ts +28 -6
  71. package/src/data/data-protocol-methods.ts +6 -3
  72. package/src/data/data-server-protocol.ts +29 -1
  73. package/src/data/events.ts +74 -3
  74. package/src/errors.ts +38 -14
  75. package/src/index.ts +4 -0
  76. package/src/messages/index.ts +35 -0
  77. package/src/messages/primitives.ts +215 -0
  78. package/src/model-server.ts +2 -2
  79. package/src/rpc/bind-rpc-methods.ts +49 -4
  80. package/src/rpc/create-rpc-proxy.ts +14 -1
  81. package/src/testing/catalogue-audit.ts +111 -0
  82. package/src/testing/data-doubles.ts +33 -9
  83. package/src/testing/index.ts +4 -1
  84. package/src/transfer-diagnostic.ts +40 -0
@@ -0,0 +1,215 @@
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 { ResponseError } from 'vscode-jsonrpc';
11
+
12
+ /**
13
+ * The framework externalizes user-facing strings and SELECTS no locale: it
14
+ * relays the one its client declared and renders with whatever templates the
15
+ * adopter installed, defaulting to its English. Every such string carries a
16
+ * stable code beside that English, and exactly one side renders it — the side
17
+ * that knows the reading user's language.
18
+ *
19
+ * Which side that is depends on the message, not on the package. A server
20
+ * message is rendered by the server, at the one seam every carrier passes
21
+ * through, in the locale it was handed at init. A message the client tier raises
22
+ * is rendered there, because those fire when the server is unreachable. Nothing
23
+ * is rendered twice: two renders of one sentence are two authorities over it,
24
+ * and they diverge on the first reword.
25
+ *
26
+ * Codes are `hydranium/<unscoped-package>/<name>`. The package segment locates
27
+ * the declaration, so a message is declared in the package that raises it and a
28
+ * code never names a package it does not live in. `.` and `:` are forbidden in a
29
+ * segment: they are i18next's default key and namespace separators, where either
30
+ * silently becomes a nested lookup that misses.
31
+ */
32
+ export type MessageParams = Readonly<Record<string, string | number>>;
33
+
34
+ type Placeholder<S extends string> = S extends `${string}{${infer Name}}${infer Rest}` ? Name | Placeholder<Rest> : never;
35
+
36
+ export type ParamsOf<S extends string> = [Placeholder<S>] extends [never]
37
+ ? Record<never, never>
38
+ : Readonly<Record<Placeholder<S>, string | number>>;
39
+
40
+ /** Required exactly when the text has placeholders, absent when it does not. */
41
+ export type ParamsArg<S extends string> = [Placeholder<S>] extends [never] ? [] : [params: ParamsOf<S>];
42
+
43
+ /**
44
+ * Rejects a text argument already widened to `string`. Load-bearing rather than
45
+ * defensive: the whole compile-time guarantee is conditional on `S` inferring a
46
+ * literal, and for a concatenated or pre-widened text the placeholder set
47
+ * silently becomes empty, `format()` accepts no arguments, and the missing
48
+ * substitution surfaces only at runtime.
49
+ */
50
+ export type LiteralText<S extends string> = string extends S ? never : S;
51
+
52
+ export interface MessageDefinition<S extends string> {
53
+ readonly code: string;
54
+ readonly text: S;
55
+ format(...args: ParamsArg<S>): string;
56
+ }
57
+
58
+ /**
59
+ * Declare a message. Placeholder names are inferred from `text` rather than
60
+ * declared again in a type argument: a second spelling of every name is the
61
+ * repetition that drifts, since adding a placeholder to the sentence and not to
62
+ * the type compiles.
63
+ */
64
+ export function defineMessage<S extends string>(code: string, text: LiteralText<S>): MessageDefinition<S> {
65
+ const literal = text as S;
66
+ return { code, text: literal, format: (...args) => interpolate(literal, args[0] ?? {}) };
67
+ }
68
+
69
+ const PLACEHOLDER = /\{([^}]+)\}/g;
70
+
71
+ /**
72
+ * Substitute `{name}` tokens, leaving an unfilled token in place.
73
+ *
74
+ * It must not throw. This runs over an adopter's translation as well as our own
75
+ * text, so a typo in a foreign catalogue has to degrade to a slightly wrong
76
+ * sentence rather than raise inside a toast render. Re-scanning the result to
77
+ * detect an unfilled token is what an earlier form did, and it cannot work:
78
+ * `String.replace` does not rescan replacement text, so the check could not tell
79
+ * an unfilled placeholder from user data shaped like one — an element literally
80
+ * named `{separator}` crashed at the authoring site.
81
+ */
82
+ export function interpolate(template: string, params: MessageParams): string {
83
+ // Indexed rather than `key in params`: a hand-built or version-skewed
84
+ // identity can arrive with no params at all, and `in` throws on a non-object
85
+ // where a lookup degrades.
86
+ const lookup = params as Record<string, string | number | undefined> | undefined;
87
+ return template.replace(PLACEHOLDER, (match, key: string) => {
88
+ const value = lookup?.[key];
89
+ return value === undefined ? match : String(value);
90
+ });
91
+ }
92
+
93
+ export interface MessageIdentity {
94
+ readonly code: string;
95
+ readonly params: MessageParams;
96
+ }
97
+
98
+ /**
99
+ * Envelope for a protocol `data` field. Namespaced under one key so it co-exists
100
+ * with a carrier's own `data` conventions rather than occupying `data` itself.
101
+ */
102
+ export interface HydraniumMessageData {
103
+ readonly hydranium: MessageIdentity;
104
+ }
105
+
106
+ /** An identity plus its resolved English — everything a renderer needs, on any carrier. */
107
+ export interface ResolvedMessage extends MessageIdentity {
108
+ readonly text: string;
109
+ }
110
+
111
+ export function messageData<S extends string>(message: MessageDefinition<S>, ...args: ParamsArg<S>): HydraniumMessageData {
112
+ return { hydranium: { code: message.code, params: args[0] ?? {} } };
113
+ }
114
+
115
+ /**
116
+ * Identity plus resolved English, for a hand-off carrying a value rather than a
117
+ * protocol field. The result is structured-clone safe, so it survives a process
118
+ * hop where one intervenes and costs nothing where none does.
119
+ */
120
+ export function resolve<S extends string>(message: MessageDefinition<S>, ...args: ParamsArg<S>): ResolvedMessage {
121
+ return { code: message.code, text: message.format(...args), params: args[0] ?? {} };
122
+ }
123
+
124
+ /**
125
+ * Validates every field {@link MessageIdentity} declares, `params` included.
126
+ * A guard over foreign input that checks only `code` while declaring `params`
127
+ * non-optional hands `undefined` to the renderer, which fails with the worst
128
+ * polarity available: invisible in English, crashing only once a translation is
129
+ * loaded.
130
+ */
131
+ export function hasMessageIdentity(data: unknown): data is HydraniumMessageData {
132
+ if (typeof data !== 'object' || data === null || Array.isArray(data) || !('hydranium' in data)) {
133
+ return false;
134
+ }
135
+ const identity = (data as { hydranium: unknown }).hydranium;
136
+ if (typeof identity !== 'object' || identity === null || Array.isArray(identity)) {
137
+ return false;
138
+ }
139
+ const candidate = identity as Partial<MessageIdentity>;
140
+ return typeof candidate.code === 'string' && typeof candidate.params === 'object' && candidate.params !== null;
141
+ }
142
+
143
+ /**
144
+ * A type alias rather than a subclass. Only `code`, `message` and `data` cross
145
+ * the wire, so a subclass buys nothing there: `instanceof` does not survive
146
+ * reconstruction, and the subclass costs an `Object.setPrototypeOf` in every
147
+ * constructor purely to undo what `ResponseError`'s own constructor does.
148
+ */
149
+ export type HydraniumResponseError = ResponseError<HydraniumMessageData>;
150
+
151
+ /**
152
+ * The numeric `code` and the message's catalogue code are unrelated and both are
153
+ * needed: `ResponseError.code` is an `integer`, so it cannot hold a
154
+ * `hydranium/…` key, and it is what a caller switches on after reconstruction.
155
+ */
156
+ export function messageError<S extends string>(
157
+ code: number,
158
+ message: MessageDefinition<S>,
159
+ ...params: ParamsArg<S>
160
+ ): HydraniumResponseError {
161
+ return new ResponseError(code, message.format(...params), messageData(message, ...params));
162
+ }
163
+
164
+ /**
165
+ * Render on the side that knows the reading user's locale. `translations` is
166
+ * whatever flat `code → template` map the host exposes; omitting it is how an
167
+ * adopter without i18n opts out, and yields the English.
168
+ */
169
+ export function renderFrameworkMessage(message: ResolvedMessage, translations?: Record<string, string>): string {
170
+ const template = translations?.[message.code];
171
+ return template ? interpolate(template, message.params) : message.text;
172
+ }
173
+
174
+ export function resolvedFromResponseError(error: ResponseError<unknown>): ResolvedMessage | undefined {
175
+ return hasMessageIdentity(error.data) ? { ...error.data.hydranium, text: error.message } : undefined;
176
+ }
177
+
178
+ /**
179
+ * The detail half of a `{detail}` placeholder. A technical error string is safe
180
+ * to pass as a parameter for the same reason a number is: it is not itself
181
+ * translatable text, so it needs no code of its own. A PROSE fragment is not,
182
+ * and must become one code per value instead.
183
+ */
184
+ export function describeError(error: unknown): string {
185
+ return error instanceof Error ? error.message : String(error);
186
+ }
187
+
188
+ /**
189
+ * Recognises a declaration among a barrel's exports. The `format` check is what
190
+ * discriminates: a `code` + `text` pair alone admits any object that happens to
191
+ * carry both.
192
+ */
193
+ export function isMessageDeclaration(value: unknown): value is MessageDefinition<string> {
194
+ const candidate = value as { code?: unknown; text?: unknown; format?: unknown } | null;
195
+ return (
196
+ typeof candidate === 'object' &&
197
+ candidate !== null &&
198
+ typeof candidate.code === 'string' &&
199
+ typeof candidate.text === 'string' &&
200
+ typeof candidate.format === 'function'
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Every declaration a `./messages` barrel exports.
206
+ *
207
+ * A caller cannot get there with `Object.values(barrel).filter(isMessageDeclaration)`:
208
+ * a barrel's value type is a union of its declarations AND its functions, and
209
+ * `filter` will not narrow a function type down to a `MessageDefinition`, so the
210
+ * result stays the union and reading `.code` off it does not compile. Taking the
211
+ * barrel as an opaque object is what makes the one-liner work.
212
+ */
213
+ export function collectMessages(barrel: object): MessageDefinition<string>[] {
214
+ return (Object.values(barrel) as unknown[]).filter(isMessageDeclaration);
215
+ }
@@ -64,8 +64,8 @@ export interface CloseModelArgs extends TransferClientArgs {}
64
64
  export interface TransferUpdatedEvent<TDocument> {
65
65
  document: TDocument;
66
66
  sourceClientId: string;
67
- /** See `ModelDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
68
- reason: 'changed' | 'deleted' | 'rebuilt' | 'saved';
67
+ /** See `TransferDocumentUpdateReason` in `./data/events` for the canonical reason set + semantics. */
68
+ reason: 'changed' | 'rebuilt' | 'saved';
69
69
  }
70
70
 
71
71
  export interface TransferSavedEvent<TDocument> {
@@ -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
 
@@ -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
+ }
@@ -34,7 +34,14 @@
34
34
  import { Emitter, type MessageConnection } from 'vscode-jsonrpc';
35
35
  import type { DataPort } from '../client/data-port';
36
36
  import type { DataClientProtocol } from '../data/data-server-protocol';
37
- import type { ProjectsChangedEvent, TransferDocumentSavedEvent, TransferDocumentUpdatedEvent } from '../data/events';
37
+ import type {
38
+ ProjectsChangedEvent,
39
+ TransferDocumentDeletedEvent,
40
+ TransferDocumentSavedEvent,
41
+ TransferDocumentsBuiltEvent,
42
+ TransferDocumentUpdatedEvent
43
+ } from '../data/events';
44
+ import type { ResolvedMessage } from '../messages/primitives';
38
45
  import type { Project } from '../project';
39
46
  import type { TransferDiagnostic } from '../transfer-diagnostic';
40
47
  import type { TransferElement } from '../transfer-element';
@@ -73,10 +80,11 @@ export interface FakeDataPort extends DataPort {
73
80
  /**
74
81
  * Every {@link DataPort.reportError} call, in order. Read from outside: this
75
82
  * is the only place a transport failure surfaces, so a test for the failure
76
- * path asserts on the `context` string here rather than on a rejection that
77
- * the consumer may legitimately swallow.
83
+ * path asserts here rather than on a rejection the consumer may legitimately
84
+ * swallow. Prefer asserting on `message.code`, which is stable, over
85
+ * `message.text`, which is the English default and may be reworded.
78
86
  */
79
- readonly reported: readonly { readonly error: unknown; readonly context: string }[];
87
+ readonly reported: readonly { readonly error: unknown; readonly message: ResolvedMessage }[];
80
88
  /**
81
89
  * Fire {@link DataPort.onDispose} — the host tearing the transport down, a
82
90
  * language-server restart being the case that forces the event to exist.
@@ -96,7 +104,7 @@ export interface FakeDataPort extends DataPort {
96
104
  */
97
105
  export function makeFakeDataPort(options: FakeDataPortOptions): FakeDataPort {
98
106
  const connections: MessageConnection[] = [];
99
- const reported: { error: unknown; context: string }[] = [];
107
+ const reported: { error: unknown; message: ResolvedMessage }[] = [];
100
108
  const disposeEmitter = new Emitter<void>();
101
109
  return {
102
110
  clientId: options.clientId ?? 'fake-data-port',
@@ -108,8 +116,8 @@ export function makeFakeDataPort(options: FakeDataPortOptions): FakeDataPort {
108
116
  connections.push(connection);
109
117
  return connection;
110
118
  },
111
- reportError(error: unknown, context: string): void {
112
- reported.push({ error, context });
119
+ reportError(error: unknown, message: ResolvedMessage): void {
120
+ reported.push({ error, message });
113
121
  },
114
122
  fireDispose(): void {
115
123
  disposeEmitter.fire(undefined);
@@ -132,6 +140,10 @@ export interface CapturingDataClient<
132
140
  readonly updates: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[];
133
141
  /** Every `onDocumentSaved` event, in arrival order. */
134
142
  readonly saves: TransferDocumentSavedEvent<TTransfer, TDiagnostic>[];
143
+ /** Every `onDocumentDeleted` event, in arrival order. */
144
+ readonly deletions: TransferDocumentDeletedEvent[];
145
+ /** Every `onDocumentsBuilt` event, in arrival order. */
146
+ readonly builds: TransferDocumentsBuiltEvent[];
135
147
  /** Every `onProjectsChanged` event, in arrival order. */
136
148
  readonly projectsChanges: ProjectsChangedEvent<TProject>[];
137
149
  }
@@ -139,7 +151,7 @@ export interface CapturingDataClient<
139
151
  /**
140
152
  * A {@link DataClientProtocol} that records every notification it receives.
141
153
  *
142
- * Recording ALL THREE channels even when a suite reads one is deliberate: an
154
+ * Recording EVERY channel even when a suite reads one is deliberate: an
143
155
  * event delivered on the wrong channel is a real defect of the data head, and a
144
156
  * double that drops the other two turns it into silence on the one being
145
157
  * watched.
@@ -156,6 +168,8 @@ export function makeCapturingDataClient<
156
168
  >(overrides: Partial<DataClientProtocol<TTransfer, TDiagnostic, TProject>> = {}): CapturingDataClient<TTransfer, TDiagnostic, TProject> {
157
169
  const updates: TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>[] = [];
158
170
  const saves: TransferDocumentSavedEvent<TTransfer, TDiagnostic>[] = [];
171
+ const deletions: TransferDocumentDeletedEvent[] = [];
172
+ const builds: TransferDocumentsBuiltEvent[] = [];
159
173
  const projectsChanges: ProjectsChangedEvent<TProject>[] = [];
160
174
  const client: DataClientProtocol<TTransfer, TDiagnostic, TProject> = {
161
175
  onDocumentUpdated:
@@ -168,11 +182,21 @@ export function makeCapturingDataClient<
168
182
  (event => {
169
183
  saves.push(event);
170
184
  }),
185
+ onDocumentDeleted:
186
+ overrides.onDocumentDeleted ??
187
+ (event => {
188
+ deletions.push(event);
189
+ }),
190
+ onDocumentsBuilt:
191
+ overrides.onDocumentsBuilt ??
192
+ (event => {
193
+ builds.push(event);
194
+ }),
171
195
  onProjectsChanged:
172
196
  overrides.onProjectsChanged ??
173
197
  (event => {
174
198
  projectsChanges.push(event);
175
199
  })
176
200
  };
177
- return { client, updates, saves, projectsChanges };
201
+ return { client, updates, saves, deletions, builds, projectsChanges };
178
202
  }
@@ -10,7 +10,9 @@
10
10
  // Subpath barrel for `@hydranium/protocol/testing` — the BROWSER-NEUTRAL shared
11
11
  // primitives: `makeFakeClock` (deterministic `Clock` double on one virtual time
12
12
  // axis), `waitFor` / `tick`, the client-side data-head doubles
13
- // (`makeFakeDataPort` / `makeCapturingDataClient`), and the `Harness` marker
13
+ // (`makeFakeDataPort` / `makeCapturingDataClient`), the translation-catalogue
14
+ // audit (`flattenCatalogue` / `findUndeclaredCodes` / `findSharedCodes`), and
15
+ // the `Harness` marker
14
16
  // interface every framework harness extends. Kept out of the main barrel so production bundles don't pull
15
17
  // the test scaffolding in by default; adopters opt in by importing from
16
18
  // `@hydranium/protocol/testing`.
@@ -20,6 +22,7 @@
20
22
  // type, so they cannot be made portable and live at `./testing/node` instead.
21
23
  // The same rule the package surface uses — the portable name is the short one.
22
24
 
25
+ export * from './catalogue-audit';
23
26
  export * from './data-doubles';
24
27
  export * from './fake-clock';
25
28
  export * from './harness';
@@ -7,6 +7,8 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
+ import { type MessageParams, type ResolvedMessage } from './messages/primitives';
11
+
10
12
  /**
11
13
  * Generic, transport-friendly diagnostic shape used by the model-server protocol.
12
14
  *
@@ -56,6 +58,21 @@ export interface TransferDiagnostic {
56
58
  * is not usable as a rule identity on its own.
57
59
  */
58
60
  code?: number | string;
61
+ /**
62
+ * Substitutions for the placeholders in the message this {@link code} names,
63
+ * present only for a diagnostic raised from a framework message declaration.
64
+ *
65
+ * Without them a translated template renders with its `{name}` tokens left
66
+ * standing, because substitution leaves an unmatched token in place rather
67
+ * than raising — so a surface that translates from {@link code} alone is
68
+ * correct for a parameterless sentence and visibly wrong for a parameterised
69
+ * one. This is the field that makes the second case work; the LSP carrier has
70
+ * always moved the params, and no carrier below it did.
71
+ *
72
+ * Prefer {@link TransferDiagnostic.resolved} over reading this: it decides
73
+ * whether an identity is present at all, which a lone `params` cannot.
74
+ */
75
+ params?: MessageParams;
59
76
  }
60
77
 
61
78
  export namespace TransferDiagnostic {
@@ -74,6 +91,29 @@ export namespace TransferDiagnostic {
74
91
  return diagnostic.type === 'parsing-error';
75
92
  }
76
93
 
94
+ /**
95
+ * The diagnostic as a renderable message, for a surface that translates.
96
+ * `undefined` when it carries no framework identity — a syntactic error, an
97
+ * adopter's own check, a linker failure — which is the case a caller must
98
+ * distinguish rather than render.
99
+ *
100
+ * Hand the result to `renderFrameworkMessage` with whatever catalogue the
101
+ * host has loaded. The `text` is the server's English, so a code the
102
+ * catalogue does not carry still yields a complete sentence.
103
+ *
104
+ * `code` alone does not establish an identity: it also holds Langium's
105
+ * internal code and an adopter's own, and either would be looked up against a
106
+ * catalogue that cannot have it. Requiring `params` is what discriminates,
107
+ * and it is why a parameterless framework message still populates the field
108
+ * with an empty object rather than omitting it.
109
+ */
110
+ export function resolved(diagnostic: TransferDiagnostic): ResolvedMessage | undefined {
111
+ if (typeof diagnostic.code !== 'string' || diagnostic.params === undefined) {
112
+ return undefined;
113
+ }
114
+ return { code: diagnostic.code, params: diagnostic.params, text: diagnostic.message };
115
+ }
116
+
77
117
  export function getPath(diagnostic: TransferDiagnostic): string {
78
118
  return diagnostic.property ? `${diagnostic.element}${ELEMENT_PROPERTY_SEPARATOR}${diagnostic.property}` : diagnostic.element;
79
119
  }