@hydranium/core 1.0.0-next.30 → 1.0.0-next.32

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 (107) hide show
  1. package/lib/documents/hydranium-text-documents.d.ts.map +1 -1
  2. package/lib/documents/hydranium-text-documents.js +12 -1
  3. package/lib/documents/hydranium-text-documents.js.map +1 -1
  4. package/lib/index.d.ts +1 -0
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +1 -0
  7. package/lib/index.js.map +1 -1
  8. package/lib/langium/ast-extension/ast-node-builder.d.ts +32 -9
  9. package/lib/langium/ast-extension/ast-node-builder.d.ts.map +1 -1
  10. package/lib/langium/ast-extension/ast-node-builder.js +60 -22
  11. package/lib/langium/ast-extension/ast-node-builder.js.map +1 -1
  12. package/lib/langium/bootstrap.d.ts.map +1 -1
  13. package/lib/langium/bootstrap.js +8 -1
  14. package/lib/langium/bootstrap.js.map +1 -1
  15. package/lib/langium/document-builder/document-builder.d.ts +33 -1
  16. package/lib/langium/document-builder/document-builder.d.ts.map +1 -1
  17. package/lib/langium/document-builder/document-builder.js +68 -2
  18. package/lib/langium/document-builder/document-builder.js.map +1 -1
  19. package/lib/langium/model-service/model-service.d.ts +26 -0
  20. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  21. package/lib/langium/model-service/model-service.js +31 -3
  22. package/lib/langium/model-service/model-service.js.map +1 -1
  23. package/lib/langium/module.d.ts +20 -0
  24. package/lib/langium/module.d.ts.map +1 -1
  25. package/lib/langium/module.js +4 -0
  26. package/lib/langium/module.js.map +1 -1
  27. package/lib/langium/naming/name-provider.d.ts +10 -0
  28. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  29. package/lib/langium/naming/name-provider.js.map +1 -1
  30. package/lib/langium/naming/name-separator-validation.d.ts +23 -1
  31. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  32. package/lib/langium/naming/name-separator-validation.js +22 -0
  33. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  34. package/lib/langium/scope/hydranium-scope-provider.d.ts +10 -6
  35. package/lib/langium/scope/hydranium-scope-provider.d.ts.map +1 -1
  36. package/lib/langium/scope/hydranium-scope-provider.js +15 -11
  37. package/lib/langium/scope/hydranium-scope-provider.js.map +1 -1
  38. package/lib/langium/shared-services.d.ts +13 -2
  39. package/lib/langium/shared-services.d.ts.map +1 -1
  40. package/lib/langium/shared-services.js.map +1 -1
  41. package/lib/langium/validation/document-validator.d.ts +66 -1
  42. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  43. package/lib/langium/validation/document-validator.js +101 -1
  44. package/lib/langium/validation/document-validator.js.map +1 -1
  45. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +11 -1
  46. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  47. package/lib/langium/workspace/hydranium-workspace-manager.js +15 -0
  48. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  49. package/lib/langium/workspace/initialize-workspace.d.ts +22 -2
  50. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  51. package/lib/langium/workspace/initialize-workspace.js +13 -5
  52. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  53. package/lib/locale/index.d.ts +10 -0
  54. package/lib/locale/index.d.ts.map +1 -0
  55. package/lib/locale/index.js +10 -0
  56. package/lib/locale/index.js.map +1 -0
  57. package/lib/locale/server-locale.d.ts +49 -0
  58. package/lib/locale/server-locale.d.ts.map +1 -0
  59. package/lib/locale/server-locale.js +51 -0
  60. package/lib/locale/server-locale.js.map +1 -0
  61. package/lib/messages/carriers.d.ts +7 -6
  62. package/lib/messages/carriers.d.ts.map +1 -1
  63. package/lib/messages/carriers.js +8 -7
  64. package/lib/messages/carriers.js.map +1 -1
  65. package/lib/messages/index.d.ts +3 -0
  66. package/lib/messages/index.d.ts.map +1 -1
  67. package/lib/messages/index.js +3 -0
  68. package/lib/messages/index.js.map +1 -1
  69. package/lib/messages/renderer.d.ts +117 -0
  70. package/lib/messages/renderer.d.ts.map +1 -0
  71. package/lib/messages/renderer.js +159 -0
  72. package/lib/messages/renderer.js.map +1 -0
  73. package/lib/testing/fake-document.d.ts +14 -3
  74. package/lib/testing/fake-document.d.ts.map +1 -1
  75. package/lib/testing/fake-document.js +18 -3
  76. package/lib/testing/fake-document.js.map +1 -1
  77. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  78. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  79. package/lib/testing/make-noop-shared-services.js +28 -2
  80. package/lib/testing/make-noop-shared-services.js.map +1 -1
  81. package/lib/testing/make-test-services.d.ts +27 -0
  82. package/lib/testing/make-test-services.d.ts.map +1 -1
  83. package/lib/testing/make-test-services.js +17 -1
  84. package/lib/testing/make-test-services.js.map +1 -1
  85. package/package.json +5 -5
  86. package/src/documents/hydranium-text-documents.ts +12 -1
  87. package/src/index.ts +1 -0
  88. package/src/langium/ast-extension/ast-node-builder.ts +66 -22
  89. package/src/langium/bootstrap.ts +8 -1
  90. package/src/langium/document-builder/document-builder.ts +70 -2
  91. package/src/langium/model-service/model-service.ts +33 -2
  92. package/src/langium/module.ts +22 -0
  93. package/src/langium/naming/name-provider.ts +10 -0
  94. package/src/langium/naming/name-separator-validation.ts +25 -3
  95. package/src/langium/scope/hydranium-scope-provider.ts +15 -11
  96. package/src/langium/shared-services.ts +13 -2
  97. package/src/langium/validation/document-validator.ts +117 -1
  98. package/src/langium/workspace/hydranium-workspace-manager.ts +18 -1
  99. package/src/langium/workspace/initialize-workspace.ts +34 -5
  100. package/src/locale/index.ts +10 -0
  101. package/src/locale/server-locale.ts +61 -0
  102. package/src/messages/carriers.ts +8 -8
  103. package/src/messages/index.ts +3 -0
  104. package/src/messages/renderer.ts +184 -0
  105. package/src/testing/fake-document.ts +22 -4
  106. package/src/testing/make-noop-shared-services.ts +50 -2
  107. package/src/testing/make-test-services.ts +43 -1
@@ -7,10 +7,20 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { type LogThreshold, type MaybeObservableValue, ObservableValue, type Tracer, TransferDiagnostic } from '@hydranium/protocol';
10
+ import {
11
+ defineMessage,
12
+ describeError,
13
+ messageData,
14
+ type LogThreshold,
15
+ type MaybeObservableValue,
16
+ ObservableValue,
17
+ type Tracer,
18
+ TransferDiagnostic
19
+ } from '@hydranium/protocol';
11
20
  import {
12
21
  type AstNode,
13
22
  type AstNodeLocator,
23
+ type AstReflection,
14
24
  DefaultDocumentValidator,
15
25
  type DiagnosticInfo,
16
26
  type LangiumDocument,
@@ -48,6 +58,26 @@ export interface TransferLspDiagnostic extends Diagnostic {
48
58
  property?: string;
49
59
  }
50
60
 
61
+ /**
62
+ * A reference resolved to nothing.
63
+ *
64
+ * **The English is byte-identical to Langium's `DefaultLinker.createLinkingError`
65
+ * sentence, and must stay so.** The identity is attached to a diagnostic Langium
66
+ * already worded, so a divergence here would silently change the text every
67
+ * adopter without a catalogue sees. {@link HydraniumDocumentValidator.processLinkingErrors}
68
+ * attaches it only when the two match exactly, which is also what keeps an
69
+ * adopter's own reworded linking error from being mislabelled as this one.
70
+ *
71
+ * It exists because this is the most-seen validation error in any language built
72
+ * on the framework, and Langium puts its own code in `data.code` rather than on
73
+ * `Diagnostic.code` — so without a framework identity every adopter wanting to
74
+ * render it has to special-case Langium's shape.
75
+ */
76
+ export const UNRESOLVED_REFERENCE = defineMessage(
77
+ 'hydranium/core/unresolved-reference',
78
+ "Could not resolve reference to {referenceType} named '{refText}'."
79
+ );
80
+
51
81
  export interface DocumentValidatorOptions extends LogNameOptions {
52
82
  /**
53
83
  * Level at which the `validateDocument` timing line is emitted, or `'off'`
@@ -94,6 +124,7 @@ export interface DocumentValidatorOptions extends LogNameOptions {
94
124
  export class HydraniumDocumentValidator extends DefaultDocumentValidator {
95
125
  protected readonly tracer: Tracer;
96
126
  protected readonly astNodeLocator: AstNodeLocator;
127
+ protected readonly reflection: AstReflection;
97
128
  protected readonly logLevel: ObservableValue<LogThreshold>;
98
129
  protected readonly logAfterMs: ObservableValue<number>;
99
130
  protected readonly validateVirtualDocuments: ObservableValue<boolean>;
@@ -103,6 +134,7 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
103
134
  super(services);
104
135
  this.tracer = services.shared.Tracer.for(options.logName ?? 'DocumentValidator').trace('instantiated');
105
136
  this.astNodeLocator = services.workspace.AstNodeLocator;
137
+ this.reflection = services.shared.AstReflection;
106
138
  this.logLevel = ObservableValue.from(options.logLevel ?? 'debug');
107
139
  this.logAfterMs = ObservableValue.from(options.logAfterMs ?? 20);
108
140
  this.validateVirtualDocuments = ObservableValue.from(options.validateVirtualDocuments ?? false);
@@ -157,6 +189,90 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
157
189
  return !this.validateSyntheticNodes.value && isSyntheticNode(node);
158
190
  }
159
191
 
192
+ /**
193
+ * Langium's linking-error pass, plus the framework identity on each
194
+ * diagnostic it produced.
195
+ *
196
+ * Langium puts its own `linking-error` marker in `data.code` and leaves
197
+ * `Diagnostic.code` unset, so nothing identifies the message on a surface
198
+ * that drops `data` — which is every editor surface. This adds the framework
199
+ * identity to both `code` and `data.hydranium` while LEAVING `data.code` in
200
+ * place: `stopAfterLinkingErrors` and Langium's code-action dispatch both
201
+ * read it.
202
+ *
203
+ * **The identity is attached only when the message is the one
204
+ * {@link UNRESOLVED_REFERENCE} renders.** Two other sentences reach this
205
+ * list: the linker's exception form, raised when resolution itself throws,
206
+ * and whatever an adopter overriding `createLinkingError` chose. Labelling
207
+ * either would make a catalogue render the wrong sentence — and for the
208
+ * exception form it would discard the underlying cause. Comparing against
209
+ * the locally rendered English is what discriminates; there is no structural
210
+ * field that does.
211
+ */
212
+ protected override processLinkingErrors(document: LangiumDocument, diagnostics: Diagnostic[], options: ValidationOptions): void {
213
+ const from = diagnostics.length;
214
+ super.processLinkingErrors(document, diagnostics, options);
215
+ for (let index = from; index < diagnostics.length; index++) {
216
+ diagnostics[index] = this.identifyLinkingError(diagnostics[index]);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Add the {@link UNRESOLVED_REFERENCE} identity to one linking diagnostic,
222
+ * or return it untouched when its message is not the sentence that identity
223
+ * renders.
224
+ *
225
+ * `refText` comes from the `data` Langium populated; `referenceType` is not
226
+ * in it, so it is recovered the same way `createLinkingError` produced it —
227
+ * through the reflection, from the container type and property.
228
+ */
229
+ protected identifyLinkingError(diagnostic: Diagnostic): Diagnostic {
230
+ const data = diagnostic.data as { code?: unknown; refText?: unknown; containerType?: unknown; property?: unknown } | undefined;
231
+ if (typeof data?.refText !== 'string' || typeof data.containerType !== 'string' || typeof data.property !== 'string') {
232
+ return diagnostic;
233
+ }
234
+ const referenceType = this.referenceTypeOf(data.containerType, data.property, data.refText);
235
+ if (referenceType === undefined) {
236
+ return diagnostic;
237
+ }
238
+ const params = { referenceType, refText: data.refText };
239
+ if (diagnostic.message !== UNRESOLVED_REFERENCE.format(params)) {
240
+ return diagnostic;
241
+ }
242
+ // Merged OVER Langium's data rather than replacing it, so `data.code`
243
+ // survives for the readers that switch on it.
244
+ return { ...diagnostic, code: UNRESOLVED_REFERENCE.code, data: { ...data, ...messageData(UNRESOLVED_REFERENCE, params) } };
245
+ }
246
+
247
+ /**
248
+ * The declared target type of the reference this diagnostic came from, or
249
+ * `undefined` when the reflection cannot name one.
250
+ *
251
+ * **The lookup can throw, and that is the reason this is a method rather
252
+ * than an inline call.** `AbstractAstReflection.getReferenceType` raises on
253
+ * an unknown container `$type` and on a property that is not a reference —
254
+ * and the linking error whose type it cannot name is the one most likely to
255
+ * reach here, because `DefaultLinker` catches its OWN failed lookup and
256
+ * turns it into the exception-form message. Rethrowing would take
257
+ * `validateDocument` with it, since Langium wraps `processLinkingErrors` in
258
+ * no try: a diagnostic Langium degraded gracefully would become a failed
259
+ * build. Declining is also the right answer on the merits — a reference
260
+ * whose type cannot be named is not the message
261
+ * {@link UNRESOLVED_REFERENCE} claims.
262
+ */
263
+ protected referenceTypeOf(containerType: string, property: string, refText: string): string | undefined {
264
+ try {
265
+ return this.reflection.getReferenceType({
266
+ container: { $type: containerType } as AstNode,
267
+ property,
268
+ reference: { $refText: refText }
269
+ } as Parameters<AstReflection['getReferenceType']>[0]);
270
+ } catch (err: unknown) {
271
+ this.tracer.debug(`cannot name the reference type for ${containerType}.${property}: ${describeError(err)}`);
272
+ return undefined;
273
+ }
274
+ }
275
+
160
276
  protected override toDiagnostic<N extends AstNode>(
161
277
  severity: ValidationSeverity,
162
278
  message: string,
@@ -9,9 +9,10 @@
9
9
 
10
10
  import { Deferred, type Logger, type Tracer } from '@hydranium/protocol';
11
11
  import { DefaultWorkspaceManager, DocumentState, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
12
- import { type CancellationToken } from 'vscode-languageserver';
12
+ import { type CancellationToken, type InitializeParams } from 'vscode-languageserver';
13
13
  import type { WorkspaceFolder } from 'vscode-languageserver-types';
14
14
  import { type LogNameOptions, resolveLogFilePlaceholder, toLogFileWorkspaceToken } from '../diagnostics/logger.js';
15
+ import type { ServerLocale } from '../../locale/server-locale.js';
15
16
  import type { ProjectChangeEvent } from '../project/project-change-event.js';
16
17
  import type { ProjectManager } from '../project/project-manager.js';
17
18
  import type { ServerSharedServicesMinimal } from '../shared-services.js';
@@ -156,6 +157,8 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
156
157
  readonly workspaceInitialized: Promise<unknown> = this.workspaceInitializedDeferred.promise;
157
158
 
158
159
  protected readonly uriPolicy: DocumentUriPolicy;
160
+ /** Handed the client's locale at init; read by whoever renders in it. */
161
+ protected readonly serverLocale: ServerLocale;
159
162
  protected readonly writableFileSystemProvider: WritableFileSystemProvider;
160
163
  protected readonly additionalDocuments: Record<string, AdditionalDocumentContribution>;
161
164
  /** Registry consulted by {@link warnIfUnroutable} to check a seeded document routes. */
@@ -166,6 +169,7 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
166
169
  this.projectManager = services.workspace.ProjectManager;
167
170
  this.projectManager.onProjectsChanged(event => this.onProjectsChanged(event));
168
171
  this.uriPolicy = services.workspace.DocumentUriPolicy;
172
+ this.serverLocale = services.ServerLocale;
169
173
  this.writableFileSystemProvider = services.workspace.FileSystemProvider;
170
174
  this.additionalDocuments = services.additionalDocuments;
171
175
  this.languageRegistry = services.ServiceRegistry;
@@ -360,6 +364,19 @@ export class HydraniumWorkspaceManager extends DefaultWorkspaceManager {
360
364
  }
361
365
  }
362
366
 
367
+ /**
368
+ * Forward the locale the client declared, then Langium's own read of the
369
+ * params. `DefaultWorkspaceManager.initialize` reads `workspaceFolders`
370
+ * alone, so `params.locale` would otherwise be discarded — and this is the
371
+ * only place it arrives, which the headless init seams route through too.
372
+ */
373
+ override initialize(params: InitializeParams): void {
374
+ if (params.locale) {
375
+ this.serverLocale.accept(params.locale);
376
+ }
377
+ super.initialize(params);
378
+ }
379
+
363
380
  /**
364
381
  * Override of Langium's workspace setup to resolve / reject
365
382
  * {@link workspaceInitializedDeferred} once setup completes. Adopters with
@@ -18,6 +18,25 @@ import type { ServerSharedServicesMinimal } from '../shared-services.js';
18
18
  /** A workspace folder root accepted by the headless init seams: a filesystem path or a {@link URI}. */
19
19
  export type WorkspaceFolderInput = string | URI;
20
20
 
21
+ /**
22
+ * Options for the headless init seams.
23
+ *
24
+ * **Optional, and the parameter is optional too**, so that no existing caller
25
+ * has to change to gain a field it does not set.
26
+ */
27
+ export interface ProgrammaticInitOptions {
28
+ /**
29
+ * The locale to render user-facing server messages in — the headless
30
+ * equivalent of LSP `initialize`'s `locale`, for a head with no LSP
31
+ * connection (`startStdioServer`, the CLI subcommands, a test harness).
32
+ *
33
+ * Omitted means no locale, which the default renderer resolves as the
34
+ * framework's English. That is the correct answer for a headless tool: it
35
+ * has no reading user to have a language.
36
+ */
37
+ readonly locale?: string;
38
+ }
39
+
21
40
  /**
22
41
  * Normalize the seam's flexible folder argument to LSP {@link WorkspaceFolder}s.
23
42
  * A `string` is resolved to an absolute filesystem path and wrapped as a
@@ -58,17 +77,25 @@ function toWorkspaceFolders(folders: WorkspaceFolderInput | ReadonlyArray<Worksp
58
77
  *
59
78
  * @param services the shared services tree the workspace manager lives on
60
79
  * @param folders one or more workspace roots (filesystem paths or URIs)
80
+ * @param options the message locale, when the caller has one
61
81
  */
62
82
  export async function initializeWorkspaceProgrammatically(
63
83
  services: ServerSharedServicesMinimal,
64
- folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>
84
+ folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>,
85
+ options: ProgrammaticInitOptions = {}
65
86
  ): Promise<void> {
66
87
  const workspaceFolders = toWorkspaceFolders(folders);
67
88
  const manager = services.workspace.WorkspaceManager;
68
- // `initialize` records the folders (DefaultWorkspaceManager reads only this
89
+ // `locale` goes through the synthesized params rather than a direct
90
+ // `acceptLocale` call, so this seam and a real LSP `initialize` reach the
91
+ // slot by the SAME path — an adopter overriding the capture in
92
+ // `HydraniumWorkspaceManager.initialize` is honoured headlessly too, which a
93
+ // second write site here would silently bypass.
94
+ //
95
+ // `initialize` records the folders (DefaultWorkspaceManager reads only that
69
96
  // field); `initialized` runs `mutex.write(initializeWorkspace)` and resolves
70
97
  // once discovery + the init build settle, so awaiting it is the ready gate.
71
- manager.initialize({ workspaceFolders } as InitializeParams);
98
+ manager.initialize({ workspaceFolders, locale: options.locale } as InitializeParams);
72
99
  await manager.initialized({} as InitializedParams);
73
100
  }
74
101
 
@@ -91,12 +118,14 @@ export async function initializeWorkspaceProgrammatically(
91
118
  *
92
119
  * @param services the shared services tree the workspace manager lives on
93
120
  * @param folders one or more workspace roots (filesystem paths or URIs)
121
+ * @param options the message locale, when the caller has one
94
122
  */
95
123
  export async function buildWorkspaceProgrammatically(
96
124
  services: ServerSharedServicesMinimal,
97
- folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>
125
+ folders: WorkspaceFolderInput | ReadonlyArray<WorkspaceFolderInput>,
126
+ options: ProgrammaticInitOptions = {}
98
127
  ): Promise<void> {
99
- await initializeWorkspaceProgrammatically(services, folders);
128
+ await initializeWorkspaceProgrammatically(services, folders, options);
100
129
  const documents = services.workspace.LangiumDocuments.all.toArray();
101
130
  await services.workspace.DocumentBuilder.build(documents, { validation: true });
102
131
  }
@@ -0,0 +1,10 @@
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
+ export * from './server-locale.js';
@@ -0,0 +1,61 @@
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 { Tracer } from '@hydranium/protocol';
11
+ import { type LogNameOptions } from '../langium/diagnostics/logger.js';
12
+ import type { ServerSharedServicesMinimal } from '../langium/shared-services.js';
13
+
14
+ /** Construction options for {@link ServerLocale}. */
15
+ export type ServerLocaleOptions = LogNameOptions;
16
+
17
+ /**
18
+ * The locale the server was handed at init, for whoever needs to render in the
19
+ * reading user's language. Held apart from the message renderer that reads it,
20
+ * so replacing the renderer cannot drop locale handling.
21
+ *
22
+ * A plain string in and out. A consumer that must react to a change rather than
23
+ * read the current value wraps this itself — nothing does today, and both real
24
+ * hosts respawn the server on a display-language switch.
25
+ */
26
+ export class ServerLocale {
27
+ protected readonly tracer: Tracer;
28
+ protected current: string | undefined;
29
+
30
+ constructor(services: ServerSharedServicesMinimal, options: ServerLocaleOptions = {}) {
31
+ this.tracer = services.Tracer.for(options.logName ?? 'ServerLocale').trace('instantiated');
32
+ }
33
+
34
+ /** The locale, or `undefined` when no init supplied one — which means the framework's English. */
35
+ get value(): string | undefined {
36
+ return this.current;
37
+ }
38
+
39
+ /**
40
+ * Take the locale an init declared.
41
+ *
42
+ * **One locale per process, and the reason the OTHER heads need none of
43
+ * their own.** The data and GLSP heads publish a port over the LSP
44
+ * connection and are reached by forwarding a socket to it, so they are the
45
+ * same process as the LSP head that was handed this locale — there is no
46
+ * topology in which one of them serves a second frontend. The Theia backend
47
+ * is the case that would break it, and it holds no locale precisely because
48
+ * it serves every frontend at once; nothing there writes here.
49
+ *
50
+ * The framework accepts a locale and never sources one, and neither
51
+ * validates nor normalises the tag: rejecting an unfamiliar one would be
52
+ * selecting a locale.
53
+ *
54
+ * Override to ignore the argument, which is how a host pins a locale it
55
+ * already knows but has no LSP client to declare.
56
+ */
57
+ accept(locale: string): void {
58
+ this.current = locale;
59
+ this.tracer.debug(`locale set to '${locale}'`);
60
+ }
61
+ }
@@ -16,7 +16,7 @@ import {
16
16
  type ResolvedMessage
17
17
  } from '@hydranium/protocol';
18
18
  import type { AstNode, DiagnosticData, DiagnosticInfo, Properties, ValidationAcceptor } from '@hydranium/langium';
19
- import type { Diagnostic } from 'vscode-languageserver-protocol';
19
+ import { Diagnostic } from 'vscode-languageserver-protocol';
20
20
 
21
21
  /**
22
22
  * Raise a validation diagnostic from a declaration, so the call site never
@@ -52,17 +52,17 @@ export function acceptMessage<S extends string, N extends AstNode, P extends Pro
52
52
  }
53
53
 
54
54
  /**
55
- * Recover the identity from a published diagnostic, for a surface that renders
56
- * diagnostics itself.
55
+ * Recover the identity from a published diagnostic, for a surface that
56
+ * identifies or renders diagnostics itself.
57
57
  *
58
- * The `MarkupContent` narrowing is not padding: `Diagnostic.message` is
59
- * `string | MarkupContent` in LSP 3.17+ and this does not compile without it.
60
- * Only the string form is a resolved English sentence.
58
+ * `Diagnostic.message` is `string | MarkupContent` in LSP 3.17+, so the text
59
+ * comes from upstream's own `Diagnostic.getMessageString` rather than a
60
+ * hand-rolled narrowing — consuming the library in its style, and one fewer
61
+ * place restating the union.
61
62
  */
62
63
  export function resolvedFromDiagnostic(diagnostic: Diagnostic): ResolvedMessage | undefined {
63
64
  if (!hasMessageIdentity(diagnostic.data)) {
64
65
  return undefined;
65
66
  }
66
- const text = typeof diagnostic.message === 'string' ? diagnostic.message : diagnostic.message.value;
67
- return { ...diagnostic.data.hydranium, text };
67
+ return { ...diagnostic.data.hydranium, text: Diagnostic.getMessageString(diagnostic) };
68
68
  }
@@ -18,7 +18,10 @@
18
18
  */
19
19
 
20
20
  export * from './carriers.js';
21
+ export * from './renderer.js';
21
22
 
23
+ export { MODEL_UPDATE_EDIT } from '../langium/model-service/model-service.js';
22
24
  export { SEPARATOR_IN_NAME } from '../langium/naming/name-separator-validation.js';
25
+ export { UNRESOLVED_REFERENCE } from '../langium/validation/document-validator.js';
23
26
  export { NO_LOADABLE_CONTENT } from '../langium/workspace/langium-documents.js';
24
27
  export { NO_SUCH_FILE, NO_SUCH_PATH } from '../langium/workspace/in-memory-file-system-provider.js';
@@ -0,0 +1,184 @@
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 {
11
+ describeError,
12
+ renderFrameworkMessage,
13
+ resolve,
14
+ resolvedFromResponseError,
15
+ type MessageDefinition,
16
+ type ParamsArg,
17
+ type ResolvedMessage,
18
+ type Tracer
19
+ } from '@hydranium/protocol';
20
+ import { SimpleCache } from '@hydranium/langium';
21
+ import type { ResponseError } from 'vscode-jsonrpc';
22
+ import { Diagnostic } from 'vscode-languageserver-protocol';
23
+ import { type LogNameOptions } from '../langium/diagnostics/logger.js';
24
+ import type { ServerSharedServicesMinimal } from '../langium/shared-services.js';
25
+ import type { ServerLocale } from '../locale/server-locale.js';
26
+ import { resolvedFromDiagnostic } from './carriers.js';
27
+
28
+ /** Construction options for {@link ServerMessageRenderer}. */
29
+ export type ServerMessageRendererOptions = LogNameOptions;
30
+
31
+ /**
32
+ * Renders every user-facing message the server sends, in the locale the server
33
+ * was handed at init. The framework ships no catalogue, so its own behaviour is
34
+ * a pass-through.
35
+ *
36
+ * Adopters override {@link translationsFor}: the public render methods carry
37
+ * the no-throw contract, and the catalogue lookup they wrap is what can fail.
38
+ *
39
+ * Two render methods rather than one, because what is useful to an adopter is
40
+ * the carrier's structured fields and the two carriers have different ones. A
41
+ * single `render(text)` would force an adopter to match English prose, which
42
+ * breaks on the first Langium reword.
43
+ */
44
+ export class ServerMessageRenderer {
45
+ protected readonly tracer: Tracer;
46
+ protected readonly serverLocale: ServerLocale;
47
+ /**
48
+ * {@link translationsFor}'s answer per locale, `undefined` answers included —
49
+ * a `SimpleCache` distinguishes "absent" from "cached as none", which matters
50
+ * because shipping no catalogue is the framework's own hot path.
51
+ *
52
+ * `SimpleCache` rather than Langium's `WorkspaceCache`: the eviction axis
53
+ * there is document change, and a catalogue does not depend on documents, so
54
+ * it would evict on every build AND put a `DocumentBuilder` dependency on a
55
+ * service the shared tier declares free of one. Nothing evicts this: the
56
+ * locale arrives once per process. A subclass whose catalogue can change
57
+ * clears it.
58
+ */
59
+ protected readonly catalogues = new SimpleCache<string | undefined, Record<string, string> | undefined>();
60
+
61
+ constructor(services: ServerSharedServicesMinimal, options: ServerMessageRendererOptions = {}) {
62
+ this.serverLocale = services.ServerLocale;
63
+ this.tracer = services.Tracer.for(options.logName ?? 'MessageRenderer').trace('instantiated');
64
+ }
65
+
66
+ /**
67
+ * The sentence to publish for `diagnostic`, replacing its current `message`.
68
+ * Sees lexer and parser errors too, which Langium pushes onto the document
69
+ * without routing them through `toDiagnostic`.
70
+ *
71
+ * **Must not throw**, which is why the guard is here and not at the call
72
+ * site: this runs inside the `Validated` phase, and Langium's
73
+ * `notifyDocumentPhase` rethrows anything that is not a cancellation — so an
74
+ * escaping error leaves the document AT `Validated` with the phase's
75
+ * listeners never run, and the client receives no diagnostics for that file.
76
+ * A subclass overriding this method takes that contract on itself.
77
+ */
78
+ renderDiagnostic(diagnostic: Diagnostic): string {
79
+ try {
80
+ const resolved = resolvedFromDiagnostic(diagnostic);
81
+ return resolved ? this.render(resolved) : Diagnostic.getMessageString(diagnostic);
82
+ } catch (err: unknown) {
83
+ this.reportFailure(err, 'a diagnostic');
84
+ return Diagnostic.getMessageString(diagnostic);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * The sentence to send for `error`, replacing its current `message`. Same
90
+ * no-throw contract as {@link renderDiagnostic}: an escaping error replaces a
91
+ * typed rejection the caller can handle with one it cannot.
92
+ */
93
+ renderError(error: ResponseError<unknown>): string {
94
+ try {
95
+ const resolved = resolvedFromResponseError(error);
96
+ return resolved ? this.render(resolved) : error.message;
97
+ } catch (err: unknown) {
98
+ this.reportFailure(err, 'an RPC error');
99
+ return error.message;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * The sentence for a declaration the caller holds directly, for a carrier
105
+ * with no slot to put an identity in.
106
+ *
107
+ * GLSP's action protocol is the case: every member of its message, status
108
+ * and reject actions is prose or an enum, so a code cannot travel and the
109
+ * raise site is the last place that still knows which message this is.
110
+ * Prefer {@link renderDiagnostic} / {@link renderError} wherever a carrier
111
+ * does hold the identity — they keep the render off the raise site, so an
112
+ * adopter's own messages ride the same one binding.
113
+ *
114
+ * Same no-throw contract as the carrier methods.
115
+ */
116
+ renderMessage<S extends string>(message: MessageDefinition<S>, ...params: ParamsArg<S>): string {
117
+ // `resolve` is inside the guard with the render, not before it: it calls
118
+ // the declaration's own `format`, which for an adopter declaration is
119
+ // arbitrary code, and a throw there would escape a method whose contract
120
+ // says it cannot.
121
+ let resolved: ResolvedMessage | undefined;
122
+ try {
123
+ resolved = resolve(message, ...params);
124
+ return this.render(resolved);
125
+ } catch (err: unknown) {
126
+ this.reportFailure(err, `the message '${message.code}'`);
127
+ // Unset only when `format` ITSELF threw, which leaves the
128
+ // uninterpolated template as the only text there is. A failed render
129
+ // still has the resolved English.
130
+ return resolved?.text ?? message.text;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * The catalogue for the current locale, or `undefined` for none — the
136
+ * framework's answer, shipping none. Overriding this leaves every identity
137
+ * decision, every pass-through and the no-throw guard in place.
138
+ *
139
+ * **Called once per locale, not once per message**, so an override may load
140
+ * a file or build a map without that cost landing per diagnostic. The
141
+ * corollary is that a catalogue mutated in place afterwards is not seen;
142
+ * clear {@link catalogues} to invalidate.
143
+ *
144
+ * An adopter wanting Langium's own uncoded sentences instead matches
145
+ * `Diagnostic.data.code` from an overridden {@link renderDiagnostic}, never
146
+ * the sentence.
147
+ */
148
+ protected translationsFor(_locale: string | undefined): Record<string, string> | undefined {
149
+ return undefined;
150
+ }
151
+
152
+ /**
153
+ * Resolve one identity against the current locale's catalogue.
154
+ *
155
+ * Reads the locale per call. Copying it into a field at construction pins
156
+ * whatever was there before init ran, which is always `undefined` — services
157
+ * compose first.
158
+ *
159
+ * The catalogue behind it is memoized, because a workspace-wide validation
160
+ * renders once per diagnostic and the naive override — parse a JSON file,
161
+ * build a map — then pays that per diagnostic rather than per locale.
162
+ */
163
+ protected render(message: ResolvedMessage): string {
164
+ const locale = this.serverLocale.value;
165
+ return renderFrameworkMessage(
166
+ message,
167
+ this.catalogues.get(locale, () => this.translationsFor(locale))
168
+ );
169
+ }
170
+
171
+ /**
172
+ * Emit a failed render. Logged rather than swallowed: the fallback output is
173
+ * byte-identical to a correctly-configured default, so a throwing catalogue
174
+ * is otherwise invisible.
175
+ */
176
+ protected reportFailure(err: unknown, carrier: string): void {
177
+ this.tracer.error(this.formatRenderFailure(err, carrier));
178
+ }
179
+
180
+ /** Format the failed-render line. Override to name the adopter's catalogue entry. */
181
+ protected formatRenderFailure(err: unknown, carrier: string): string {
182
+ return `rendering ${carrier} failed; falling back to the server's own text. ${describeError(err)}`;
183
+ }
184
+ }
@@ -7,7 +7,8 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { DocumentState, type AstNode, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
10
+ import { DocumentState, type AstNode, type AstReflection, type LangiumDocument, UriUtils, type URI } from '@hydranium/langium';
11
+ import { buildAstNode } from '../langium/ast-extension/ast-node-builder.js';
11
12
 
12
13
  /**
13
14
  * Build a typed AST-node fixture for unit tests.
@@ -23,12 +24,29 @@ import { DocumentState, type AstNode, type LangiumDocument, UriUtils, type URI }
23
24
  * framework synthetic node, and marking it would change scope/index behaviour.
24
25
  * A test that wants a genuine synthetic node calls `markSynthetic` explicitly.
25
26
  *
27
+ * **Without a `reflection`, the fixture carries only what the test spells out**,
28
+ * which is a shape production never produces: a parsed or built node always has
29
+ * its grammar-declared containment arrays, so a fixture that omits one lets a
30
+ * test pass against an impossible node, and lets code that walks a list crash
31
+ * only under test. Pass the grammar's reflection whenever the type is a real
32
+ * one and the code under test reads a collection off it. Fixtures typed against
33
+ * ad-hoc names have no reflection to pass and keep the plain form.
34
+ *
26
35
  * @param node the node shape — `$type` is required; every other property is a
27
36
  * value the test cares about (`$container`, cross-reference values, internal
28
- * `_id` fields, …). The object is returned by reference, not copied.
37
+ * `_id` fields, …).
38
+ * @param reflection when given, pre-fills the grammar's declared defaults the
39
+ * same way {@link buildAstNode} does, and the result is a fresh object rather
40
+ * than `node` itself. Omitted, `node` is returned by reference.
29
41
  */
30
- export function makeFakeAstNode<TAst extends AstNode = AstNode>(node: { $type: string } & Record<string, unknown>): TAst {
31
- return node as unknown as TAst;
42
+ export function makeFakeAstNode<TAst extends AstNode = AstNode>(
43
+ node: { $type: string } & Record<string, unknown>,
44
+ reflection?: AstReflection
45
+ ): TAst {
46
+ if (!reflection) {
47
+ return node as unknown as TAst;
48
+ }
49
+ return buildAstNode<TAst>(reflection, node.$type, node);
32
50
  }
33
51
 
34
52
  /**