@dialexjs/language-server 0.0.0-stage → 0.7.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Halil Aydın
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @dialexjs/language-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) server for
4
+ [Dialex](https://github.com/awaiden/dialex) translations. Editors that speak LSP (Zed, Neovim,
5
+ Helix, Sublime and others) get Dialex's diagnostics and hover without a dedicated plugin.
6
+
7
+ > **Status: early.** Everything below works, tested against an LSP client and in Zed.
8
+
9
+ ## Run it
10
+
11
+ ```bash
12
+ npx @dialexjs/language-server --stdio
13
+ ```
14
+
15
+ ## What it does today
16
+
17
+ - **Diagnostics**: missing keys and locales in `.content.ts` dictionaries, `getDictionary("x")` and
18
+ `t("x.y")` calls that point at nothing, invalid ICU messages, `[TODO]` placeholders, and
19
+ translations whose source text changed since they were translated.
20
+ - **Hover**: hover a `t("home.title")` key, a dictionary name, or a member of a variable that holds
21
+ a dictionary (`s.nav.features` after `const s = useDictionary("showcase")`) to see the text in
22
+ every locale.
23
+ - **Go to definition**: jump from a key, or from `s.nav.features`, to where the dictionary writes it.
24
+ - **Completion**: dictionary names and key paths inside `t("…")`, `getDictionary("…")` and
25
+ `useDictionary("…")`, triggered by `"`, `'`, `` ` `` and `.`.
26
+ - **Quick fixes**: copy a missing key into a locale (marked `[TODO]`), add every missing key in a
27
+ file, or create a key that code refers to.
28
+
29
+ - **Generated files**: when a dictionary or config file is added, changed or removed, in a project
30
+ that already has a `dialex.generated.ts`, the server regenerates it and `dialex-env.d.ts`. It
31
+ uses the editor's file events when the client sends them and watches the disk itself otherwise.
32
+ It never creates a generated file in a project that has none; run `dx generate` once for that.
33
+
34
+ It reads configs and dictionaries from the syntax tree and **never runs your project's code**.
35
+
36
+ ## Settings
37
+
38
+ Sent under the `dialex` section (`workspace/configuration`):
39
+
40
+ | Setting | Default | Description |
41
+ | ------------ | ------- | ----------------------------------------------------------------------- |
42
+ | `enable` | `true` | Turn all features off |
43
+ | `unusedKeys` | `false` | Fade out keys and dictionaries that no source file seems to use |
44
+ | `configPath` | — | Config file relative to each project root; empty uses `dialex.config.*` |
45
+
46
+ ## Library use
47
+
48
+ The editor-independent building blocks (project model, reference lookup, hover text, completion
49
+ entries, quick-fix edits, project discovery) are exported from `@dialexjs/language-server/features`.
50
+ The VS Code extension uses them too.
@@ -0,0 +1,130 @@
1
+ import { AnalysisResult, AnalyzedDictionary, Reference, SourceRange } from "@dialexjs/cli/api";
2
+ //#region src/features/model.d.ts
3
+ /** What the editor features know about one Dialex project (a folder with its own config). */
4
+ export interface ProjectModel {
5
+ root: string;
6
+ defaultLocale: string;
7
+ dictionaries: Map<string, AnalyzedDictionary>;
8
+ }
9
+ export declare function buildModel(root: string, defaultLocale: string, result: Pick<AnalysisResult, "dictionaries">): ProjectModel;
10
+ /** The model whose root contains `file`, preferring the deepest (nested projects). */
11
+ export declare function modelForFile(models: Iterable<ProjectModel>, file: string): ProjectModel | undefined;
12
+ /** Locales with the default locale first. */
13
+ export declare function orderedLocales(model: ProjectModel, dictionary: AnalyzedDictionary): string[];
14
+ //#endregion
15
+ //#region src/features/bindings.d.ts
16
+ /** Variable name -> dictionary name, for `const s = useDictionary("showcase")`. */
17
+ export type Bindings = ReadonlyMap<string, string>;
18
+ /**
19
+ * Finds the variables in a file that hold a dictionary, so `s.nav.features` can be resolved to
20
+ * `showcase.nav.features`. It is a text match: a variable that is reassigned or shadowed in another
21
+ * scope may resolve to the wrong dictionary, which only affects editor hints.
22
+ */
23
+ export declare function findBindings(text: string): Bindings;
24
+ //#endregion
25
+ //#region src/features/references.d.ts
26
+ /**
27
+ * The Dialex reference under the cursor on one line of code: a dictionary name, a `t("a.b.c")`
28
+ * path, a member of `getDictionary("a")` such as `.title`, or, with `bindings`, a member of a
29
+ * variable that holds a dictionary (`s.nav.features` after `const s = useDictionary("showcase")`).
30
+ * Offsets are into `lineText`.
31
+ */
32
+ export declare function findReferenceAt(lineText: string, character: number, bindings?: Bindings): Reference | undefined;
33
+ export interface ResolvedReference {
34
+ dictionary: AnalyzedDictionary;
35
+ /** Empty for a reference to the dictionary itself. */
36
+ keyPath: string[];
37
+ }
38
+ export declare function resolveReference(model: ProjectModel, ref: Reference): ResolvedReference | undefined;
39
+ /** Whether `keyPath` is a leaf, a group of leaves, or nothing in this dictionary. */
40
+ export declare function classifyPath(dictionary: AnalyzedDictionary, keyPath: string[]): "leaf" | "group" | "missing";
41
+ //#endregion
42
+ //#region src/features/hover.d.ts
43
+ /** Escapes Markdown so translation text cannot change the hover's formatting. */
44
+ export declare function escapeMarkdown(text: string): string;
45
+ /**
46
+ * Markdown for a hover over a Dialex reference: every locale's text for a key, or a summary of a
47
+ * dictionary. Returns `undefined` for unknown references (diagnostics already flag those).
48
+ */
49
+ export declare function buildHover(model: ProjectModel, ref: Reference): string | undefined;
50
+ //#endregion
51
+ //#region src/features/definition.d.ts
52
+ export interface DefinitionTarget {
53
+ file: string;
54
+ range: SourceRange;
55
+ }
56
+ /**
57
+ * Where a reference is defined: the key in the default locale if it has one, otherwise in the
58
+ * first locale that does. A dictionary reference points at the dictionary object.
59
+ */
60
+ export declare function definitionFor(model: ProjectModel, ref: Reference): DefinitionTarget | undefined;
61
+ //#endregion
62
+ //#region src/features/completion.d.ts
63
+ export type CompletionContext = {
64
+ kind: "dictionary";
65
+ call: string;
66
+ typed: string;
67
+ length: number;
68
+ } | {
69
+ kind: "path";
70
+ dictionary: string;
71
+ parent: string[];
72
+ typed: string;
73
+ length: number;
74
+ };
75
+ /**
76
+ * Whether the cursor is inside the string argument of a Dialex call, and what is being typed.
77
+ * `textBeforeCursor` is the line up to the cursor. `length` is how many characters before the
78
+ * cursor a completion replaces.
79
+ */
80
+ export declare function completionContextAt(textBeforeCursor: string, bindings?: Bindings): CompletionContext | undefined;
81
+ export interface CompletionEntry {
82
+ label: string;
83
+ kind: "dictionary" | "group" | "leaf";
84
+ detail: string;
85
+ /** Text to insert in place of what was typed. */
86
+ insertText: string;
87
+ /** Re-open the suggestion list after inserting (after `home.` or `nav.`). */
88
+ retrigger: boolean;
89
+ documentation?: string;
90
+ }
91
+ /** Suggestions for the string being typed, filtered by what is already there. */
92
+ export declare function completionEntries(model: ProjectModel, context: CompletionContext): CompletionEntry[];
93
+ //#endregion
94
+ //#region src/features/quickfix.d.ts
95
+ export interface MissingKey {
96
+ locale: string;
97
+ path: string[];
98
+ /** A locale that has the key, to copy its value from. */
99
+ sourceLocale?: string;
100
+ }
101
+ /**
102
+ * New text for a dictionary file with `missing` keys added to their locales, copied from the
103
+ * source locale (strings get the `[TODO] ` marker, like `dialex check --fix`). Returns
104
+ * `undefined` if nothing could be added.
105
+ */
106
+ export declare function addMissingKeys(file: string, text: string, missing: MissingKey[]): string | undefined;
107
+ /**
108
+ * New text for a dictionary file with a key that code refers to but the dictionary lacks, added
109
+ * to every locale as a `[TODO]` placeholder named after the key.
110
+ */
111
+ export declare function addUnknownKey(file: string, text: string, keyPath: string[]): string | undefined;
112
+ //#endregion
113
+ //#region src/features/projects.d.ts
114
+ export interface ProjectRoot {
115
+ root: string;
116
+ /** Globs (relative to `root`) for nested projects that belong to someone else. */
117
+ ignore: string[];
118
+ }
119
+ /**
120
+ * Finds the Dialex projects inside a workspace folder.
121
+ *
122
+ * - Every directory with a `dialex.config.*` or `i18n.config.*` is a project.
123
+ * - A `*.content.ts` file that no such project contains belongs to the nearest folder with a
124
+ * `package.json` (or the workspace folder), which then uses the default settings. This covers
125
+ * monorepos where only some packages have a config file.
126
+ * - A project excludes the projects nested inside it, so one dictionary is never reported twice.
127
+ */
128
+ export declare function discoverProjects(folder: string): ProjectRoot[];
129
+ //#endregion
130
+ //# sourceMappingURL=features.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"features.d.mts","names":[],"sources":["../src/features/model.ts","../src/features/bindings.ts","../src/features/references.ts","../src/features/hover.ts","../src/features/definition.ts","../src/features/completion.ts","../src/features/quickfix.ts","../src/features/projects.ts"],"mappings":";;;iBAKiB;EACf;EACA;EACA,cAAc,YAAY;;wBAGZ,WACd,cACA,uBACA,QAAQ,KAAK,kCACZ;;wBASa,aACd,QAAQ,SAAS,eACjB,eACC;;wBAWa,eAAe,OAAO,cAAc,YAAY;;;;YCrCpD,WAAW;;;;;;wBAcP,aAAa,eAAe;;;;;;;;;wBCE5B,gBACd,kBACA,mBACA,WAAW,WACV;iBA8Cc;EACf,YAAY;;EAEZ;;wBAGc,iBACd,OAAO,cACP,KAAK,YACJ;;wBAWa,aACd,YAAY,oBACZ;;;;wBCjFc,eAAe;;;;;wBAwBf,WAAW,OAAO,cAAc,KAAK;;;iBC1BpC;EACf;EACA,OAAO;;;;;;wBASO,cAAc,OAAO,cAAc,KAAK,YAAY;;;YCZxD;EACN;EAAoB;EAAc;EAAe;;EACjD;EAAc;EAAoB;EAAkB;EAAe;;;;;;;wBASzD,oBACd,0BACA,WAAW,WACV;iBAiCc;EACf;EACA;EACA;;EAEA;;EAEA;EACA;;;wBA+Dc,kBACd,OAAO,cACP,SAAS,oBACR;;;iBCpHc;EACf;EACA;;EAEA;;;;;;;wBAQc,eACd,cACA,cACA,SAAS;;;;;wBAkBK,cAAc,cAAc,cAAc;;;iBCtCzC;EACf;;EAEA;;;;;;;;;;;wBAwBc,iBAAiB,iBAAiB"}
@@ -0,0 +1,361 @@
1
+ import fs from "node:fs";
2
+ import { TODO_PREFIX, copyLeaf, dictionaryLocation, getLeafSource, hasPath, listLocales, locationOf, parseDictionaryText, renderDictionaryFile, scanFiles, scanReferences, setString } from "@dialexjs/cli/api";
3
+ import path from "node:path";
4
+ //#region src/features/model.ts
5
+ function buildModel(root, defaultLocale, result) {
6
+ return {
7
+ root,
8
+ defaultLocale,
9
+ dictionaries: new Map(result.dictionaries.map((d) => [d.name, d]))
10
+ };
11
+ }
12
+ /** The model whose root contains `file`, preferring the deepest (nested projects). */
13
+ function modelForFile(models, file) {
14
+ let best;
15
+ for (const model of models) {
16
+ const rel = path.relative(model.root, file);
17
+ if (rel.startsWith("..") || path.isAbsolute(rel)) continue;
18
+ if (!best || model.root.length > best.root.length) best = model;
19
+ }
20
+ return best;
21
+ }
22
+ /** Locales with the default locale first. */
23
+ function orderedLocales(model, dictionary) {
24
+ return [...dictionary.locales.filter((l) => l === model.defaultLocale), ...dictionary.locales.filter((l) => l !== model.defaultLocale)];
25
+ }
26
+ //#endregion
27
+ //#region src/features/bindings.ts
28
+ /**
29
+ * `const s = useDictionary("showcase")`, `const home = await getDictionary("home", locale)`,
30
+ * `let t: Home = injectDictionary<Home>("home")`: a variable that holds a dictionary.
31
+ */
32
+ const DECLARATION = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*(?:await\s+)?(?:[A-Za-z_$][\w$]*\.)*(?:getDictionary|useDictionary|injectDictionary)\s*(?:<[^()]*?>)?\(\s*(["'`])([^"'`$\n]+)\2/g;
33
+ /**
34
+ * Finds the variables in a file that hold a dictionary, so `s.nav.features` can be resolved to
35
+ * `showcase.nav.features`. It is a text match: a variable that is reassigned or shadowed in another
36
+ * scope may resolve to the wrong dictionary, which only affects editor hints.
37
+ */
38
+ function findBindings(text) {
39
+ const bindings = /* @__PURE__ */ new Map();
40
+ for (const match of text.matchAll(DECLARATION)) bindings.set(match[1], match[3]);
41
+ return bindings;
42
+ }
43
+ //#endregion
44
+ //#region src/features/references.ts
45
+ /** `getDictionary("home").nav.about` -> the `.nav.about` member chain after the call. */
46
+ const MEMBER_CHAIN = /(?:getDictionary|useDictionary)\(\s*(["'`])([^"'`$\n]+)\1[^()\n]*\)((?:\??\.[A-Za-z_$][\w$]*)+)/dg;
47
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
+ /**
49
+ * The Dialex reference under the cursor on one line of code: a dictionary name, a `t("a.b.c")`
50
+ * path, a member of `getDictionary("a")` such as `.title`, or, with `bindings`, a member of a
51
+ * variable that holds a dictionary (`s.nav.features` after `const s = useDictionary("showcase")`).
52
+ * Offsets are into `lineText`.
53
+ */
54
+ function findReferenceAt(lineText, character, bindings) {
55
+ const direct = scanReferences(lineText).find((r) => character >= r.start && character <= r.end);
56
+ if (direct) return direct;
57
+ for (const match of lineText.matchAll(MEMBER_CHAIN)) {
58
+ const dictionary = match[2];
59
+ const [chainStart] = match.indices[3];
60
+ const members = /\??\.([A-Za-z_$][\w$]*)/g;
61
+ const keys = [];
62
+ for (const member of match[3].matchAll(members)) {
63
+ const start = chainStart + member.index + member[0].length - member[1].length;
64
+ const end = start + member[1].length;
65
+ keys.push(member[1]);
66
+ if (character >= start && character <= end) return {
67
+ kind: "path",
68
+ value: [dictionary, ...keys].join("."),
69
+ start,
70
+ end
71
+ };
72
+ }
73
+ }
74
+ for (const [name, dictionary] of bindings ?? []) {
75
+ const chain = new RegExp(`(?<![\\w$.])${escapeRegExp(name)}(?![\\w$])((?:\\??\\.[A-Za-z_$][\\w$]*)*)`, "dg");
76
+ for (const match of lineText.matchAll(chain)) {
77
+ const nameStart = match.index;
78
+ const nameEnd = nameStart + name.length;
79
+ if (character >= nameStart && character <= nameEnd) return {
80
+ kind: "dictionary",
81
+ value: dictionary,
82
+ start: nameStart,
83
+ end: nameEnd
84
+ };
85
+ const [chainStart] = match.indices[1];
86
+ const keys = [];
87
+ for (const member of match[1].matchAll(/\??\.([A-Za-z_$][\w$]*)/g)) {
88
+ const start = chainStart + member.index + member[0].length - member[1].length;
89
+ const end = start + member[1].length;
90
+ keys.push(member[1]);
91
+ if (character >= start && character <= end) return {
92
+ kind: "path",
93
+ value: [dictionary, ...keys].join("."),
94
+ start,
95
+ end
96
+ };
97
+ }
98
+ }
99
+ }
100
+ }
101
+ function resolveReference(model, ref) {
102
+ if (ref.kind === "dictionary") {
103
+ const dictionary = model.dictionaries.get(ref.value);
104
+ return dictionary ? {
105
+ dictionary,
106
+ keyPath: []
107
+ } : void 0;
108
+ }
109
+ const [name, ...keyPath] = ref.value.split(".");
110
+ const dictionary = model.dictionaries.get(name);
111
+ return dictionary ? {
112
+ dictionary,
113
+ keyPath
114
+ } : void 0;
115
+ }
116
+ /** Whether `keyPath` is a leaf, a group of leaves, or nothing in this dictionary. */
117
+ function classifyPath(dictionary, keyPath) {
118
+ const joined = keyPath.join(".");
119
+ if (dictionary.paths.includes(joined)) return "leaf";
120
+ return dictionary.paths.some((p) => p.startsWith(`${joined}.`)) ? "group" : "missing";
121
+ }
122
+ //#endregion
123
+ //#region src/features/hover.ts
124
+ /** Escapes Markdown so translation text cannot change the hover's formatting. */
125
+ function escapeMarkdown(text) {
126
+ return text.replace(/[\\`*_{}[\]()#+!|<>~]/g, "\\$&").replace(/\r?\n/g, "<br>").slice(0, 400);
127
+ }
128
+ function cell(dictionary, locale, keyPath) {
129
+ const leaf = dictionary.leaves.get(locale)?.get(keyPath.join("."));
130
+ if (!leaf) return "_missing_";
131
+ if (leaf.kind === "string") return escapeMarkdown(leaf.value ?? "");
132
+ if (leaf.kind === "function") {
133
+ const source = dictionary.df ? getLeafSource(dictionary.df, locale, keyPath) : void 0;
134
+ return source ? `\`${source.replace(/`/g, "'").replace(/\s+/g, " ").slice(0, 160)}\`` : "_function_";
135
+ }
136
+ return "_value_";
137
+ }
138
+ /**
139
+ * Markdown for a hover over a Dialex reference: every locale's text for a key, or a summary of a
140
+ * dictionary. Returns `undefined` for unknown references (diagnostics already flag those).
141
+ */
142
+ function buildHover(model, ref) {
143
+ const resolved = resolveReference(model, ref);
144
+ if (!resolved) return void 0;
145
+ const { dictionary, keyPath } = resolved;
146
+ const file = path.basename(dictionary.file);
147
+ if (keyPath.length === 0) return [
148
+ `**${dictionary.name}** · ${file}`,
149
+ "",
150
+ `${dictionary.paths.length} key${dictionary.paths.length === 1 ? "" : "s"} · locales: ${dictionary.locales.join(", ")}`
151
+ ].join("\n");
152
+ const kind = classifyPath(dictionary, keyPath);
153
+ const title = `**${dictionary.name}.${keyPath.join(".")}** · ${file}`;
154
+ if (kind === "missing") return void 0;
155
+ if (kind === "group") {
156
+ const prefix = `${keyPath.join(".")}.`;
157
+ const children = new Set(dictionary.paths.filter((p) => p.startsWith(prefix)).map((p) => p.slice(prefix.length).split(".")[0]));
158
+ return `${title}\n\n${children.size} key${children.size === 1 ? "" : "s"}: ${[...children].map((c) => `\`${c}\``).join(", ")}`;
159
+ }
160
+ return [
161
+ title,
162
+ "",
163
+ "| Locale | Text |",
164
+ "| --- | --- |",
165
+ ...orderedLocales(model, dictionary).map((locale) => `| ${locale} | ${cell(dictionary, locale, keyPath)} |`)
166
+ ].join("\n");
167
+ }
168
+ //#endregion
169
+ //#region src/features/definition.ts
170
+ const START = {
171
+ start: {
172
+ line: 0,
173
+ column: 0
174
+ },
175
+ end: {
176
+ line: 0,
177
+ column: 0
178
+ }
179
+ };
180
+ /**
181
+ * Where a reference is defined: the key in the default locale if it has one, otherwise in the
182
+ * first locale that does. A dictionary reference points at the dictionary object.
183
+ */
184
+ function definitionFor(model, ref) {
185
+ const resolved = resolveReference(model, ref);
186
+ if (!resolved) return void 0;
187
+ const { dictionary, keyPath } = resolved;
188
+ const { df } = dictionary;
189
+ if (!df) return {
190
+ file: dictionary.file,
191
+ range: START
192
+ };
193
+ if (keyPath.length === 0) return {
194
+ file: dictionary.file,
195
+ range: dictionaryLocation(df) ?? START
196
+ };
197
+ for (const locale of orderedLocales(model, dictionary)) {
198
+ const range = locationOf(df, locale, keyPath);
199
+ if (range) return {
200
+ file: dictionary.file,
201
+ range
202
+ };
203
+ }
204
+ }
205
+ //#endregion
206
+ //#region src/features/completion.ts
207
+ const CALL = /(?<![\w$.])(t|getDictionary|useDictionary|DialexDictionary)\(\s*(["'`])([^"'`\n]*)$/;
208
+ /**
209
+ * Whether the cursor is inside the string argument of a Dialex call, and what is being typed.
210
+ * `textBeforeCursor` is the line up to the cursor. `length` is how many characters before the
211
+ * cursor a completion replaces.
212
+ */
213
+ function completionContextAt(textBeforeCursor, bindings) {
214
+ const match = CALL.exec(textBeforeCursor);
215
+ if (!match) return bindings ? memberContextAt(textBeforeCursor, bindings) : void 0;
216
+ const [, call, , value] = match;
217
+ if (call === "t" && value.includes(".")) {
218
+ const segments = value.split(".");
219
+ const typed = segments.pop();
220
+ const [dictionary, ...parent] = segments;
221
+ return {
222
+ kind: "path",
223
+ dictionary,
224
+ parent,
225
+ typed,
226
+ length: typed.length
227
+ };
228
+ }
229
+ return {
230
+ kind: "dictionary",
231
+ call,
232
+ typed: value,
233
+ length: value.length
234
+ };
235
+ }
236
+ /** `s.nav.fe|` where `s` holds a dictionary: the keys under `nav` that start with `fe`. */
237
+ function memberContextAt(textBeforeCursor, bindings) {
238
+ for (const [name, dictionary] of bindings) {
239
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
240
+ const match = new RegExp(`(?<![\\w$.])${escaped}((?:\\??\\.[A-Za-z_$][\\w$]*)*)\\??\\.([A-Za-z_$][\\w$]*)?$`).exec(textBeforeCursor);
241
+ if (!match) continue;
242
+ const parent = [...match[1].matchAll(/\??\.([A-Za-z_$][\w$]*)/g)].map((m) => m[1]);
243
+ const typed = match[2] ?? "";
244
+ return {
245
+ kind: "path",
246
+ dictionary,
247
+ parent,
248
+ typed,
249
+ length: typed.length
250
+ };
251
+ }
252
+ }
253
+ const preview = (text) => text === void 0 ? void 0 : text.length > 60 ? `${text.slice(0, 57)}...` : text;
254
+ function dictionaryEntries(model, context) {
255
+ return [...model.dictionaries.values()].filter((d) => d.name.startsWith(context.typed)).map((d) => {
256
+ const continues = context.call === "t";
257
+ return {
258
+ label: d.name,
259
+ kind: "dictionary",
260
+ detail: `${d.paths.length} keys · ${d.locales.join(", ")}`,
261
+ insertText: continues ? `${d.name}.` : d.name,
262
+ retrigger: continues
263
+ };
264
+ });
265
+ }
266
+ function pathEntries(model, dictionary, context) {
267
+ const prefix = context.parent.length > 0 ? `${context.parent.join(".")}.` : "";
268
+ const children = /* @__PURE__ */ new Map();
269
+ for (const keyPath of dictionary.paths) {
270
+ if (!keyPath.startsWith(prefix)) continue;
271
+ const rest = keyPath.slice(prefix.length).split(".");
272
+ const name = rest[0];
273
+ if (!name.startsWith(context.typed)) continue;
274
+ const entry = children.get(name) ?? { leaf: true };
275
+ if (rest.length > 1) entry.leaf = false;
276
+ children.set(name, entry);
277
+ }
278
+ return [...children].map(([name, { leaf }]) => {
279
+ const full = `${prefix}${name}`;
280
+ const holder = [model.defaultLocale, ...dictionary.locales].find((l) => dictionary.leaves.get(l)?.has(full));
281
+ const text = holder ? dictionary.leaves.get(holder).get(full) : void 0;
282
+ return {
283
+ label: name,
284
+ kind: leaf ? "leaf" : "group",
285
+ detail: leaf ? preview(text?.kind === "string" ? text.value : text ? `(${text.kind})` : void 0) ?? "" : "keys…",
286
+ insertText: leaf ? name : `${name}.`,
287
+ retrigger: !leaf
288
+ };
289
+ });
290
+ }
291
+ /** Suggestions for the string being typed, filtered by what is already there. */
292
+ function completionEntries(model, context) {
293
+ if (context.kind === "dictionary") return dictionaryEntries(model, context);
294
+ const dictionary = model.dictionaries.get(context.dictionary);
295
+ return dictionary ? pathEntries(model, dictionary, context) : [];
296
+ }
297
+ //#endregion
298
+ //#region src/features/quickfix.ts
299
+ /**
300
+ * New text for a dictionary file with `missing` keys added to their locales, copied from the
301
+ * source locale (strings get the `[TODO] ` marker, like `dialex check --fix`). Returns
302
+ * `undefined` if nothing could be added.
303
+ */
304
+ function addMissingKeys(file, text, missing) {
305
+ const df = parseDictionaryText(file, text);
306
+ if (!df) return void 0;
307
+ let changed = false;
308
+ for (const { locale, path, sourceLocale } of missing) {
309
+ if (!sourceLocale) continue;
310
+ if (copyLeaf(df, sourceLocale, locale, path, (value) => `${TODO_PREFIX}${value}`)) changed = true;
311
+ }
312
+ return changed ? renderDictionaryFile(df) : void 0;
313
+ }
314
+ /**
315
+ * New text for a dictionary file with a key that code refers to but the dictionary lacks, added
316
+ * to every locale as a `[TODO]` placeholder named after the key.
317
+ */
318
+ function addUnknownKey(file, text, keyPath) {
319
+ const df = parseDictionaryText(file, text);
320
+ if (!df) return void 0;
321
+ const placeholder = `${TODO_PREFIX}${keyPath[keyPath.length - 1]}`;
322
+ let changed = false;
323
+ for (const locale of listLocales(df)) if (!hasPath(df, locale, keyPath) && setString(df, locale, keyPath, placeholder) !== "skipped") changed = true;
324
+ return changed ? renderDictionaryFile(df) : void 0;
325
+ }
326
+ //#endregion
327
+ //#region src/features/projects.ts
328
+ const IGNORE = ["**/.git/**", "**/.nuxt/**"];
329
+ /** The nearest folder at or above `dir` (but inside `folder`) that has a package.json. */
330
+ function packageRoot(folder, dir) {
331
+ for (let current = dir; current.startsWith(folder); current = path.dirname(current)) {
332
+ if (fs.existsSync(path.join(current, "package.json"))) return current;
333
+ if (current === folder) break;
334
+ }
335
+ return folder;
336
+ }
337
+ /**
338
+ * Finds the Dialex projects inside a workspace folder.
339
+ *
340
+ * - Every directory with a `dialex.config.*` or `i18n.config.*` is a project.
341
+ * - A `*.content.ts` file that no such project contains belongs to the nearest folder with a
342
+ * `package.json` (or the workspace folder), which then uses the default settings. This covers
343
+ * monorepos where only some packages have a config file.
344
+ * - A project excludes the projects nested inside it, so one dictionary is never reported twice.
345
+ */
346
+ function discoverProjects(folder) {
347
+ const configs = scanFiles(folder, ["**/dialex.config.*", "**/i18n.config.*"], { ignore: IGNORE });
348
+ const configured = [...new Set(configs.map((f) => path.dirname(f)))];
349
+ const roots = new Set(configured);
350
+ const dictionaries = scanFiles(folder, "**/*.content.ts", { ignore: IGNORE });
351
+ for (const file of dictionaries) if (!configured.some((root) => file.startsWith(root + path.sep))) roots.add(packageRoot(folder, path.dirname(file)));
352
+ const all = [...roots].sort((a, b) => a.length - b.length);
353
+ return all.map((root) => ({
354
+ root,
355
+ ignore: all.filter((other) => other !== root && other.startsWith(root + path.sep)).map((other) => `${path.relative(root, other).split(path.sep).join("/")}/**`)
356
+ }));
357
+ }
358
+ //#endregion
359
+ export { addMissingKeys, addUnknownKey, buildHover, buildModel, classifyPath, completionContextAt, completionEntries, definitionFor, discoverProjects, escapeMarkdown, findBindings, findReferenceAt, modelForFile, orderedLocales, resolveReference };
360
+
361
+ //# sourceMappingURL=features.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"features.mjs","names":[],"sources":["../src/features/model.ts","../src/features/bindings.ts","../src/features/references.ts","../src/features/hover.ts","../src/features/definition.ts","../src/features/completion.ts","../src/features/quickfix.ts","../src/features/projects.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport type { AnalysisResult, AnalyzedDictionary } from \"@dialexjs/cli/api\";\n\n/** What the editor features know about one Dialex project (a folder with its own config). */\nexport interface ProjectModel {\n root: string;\n defaultLocale: string;\n dictionaries: Map<string, AnalyzedDictionary>;\n}\n\nexport function buildModel(\n root: string,\n defaultLocale: string,\n result: Pick<AnalysisResult, \"dictionaries\">,\n): ProjectModel {\n return {\n root,\n defaultLocale,\n dictionaries: new Map(result.dictionaries.map((d) => [d.name, d])),\n };\n}\n\n/** The model whose root contains `file`, preferring the deepest (nested projects). */\nexport function modelForFile(\n models: Iterable<ProjectModel>,\n file: string,\n): ProjectModel | undefined {\n let best: ProjectModel | undefined;\n for (const model of models) {\n const rel = path.relative(model.root, file);\n if (rel.startsWith(\"..\") || path.isAbsolute(rel)) continue;\n if (!best || model.root.length > best.root.length) best = model;\n }\n return best;\n}\n\n/** Locales with the default locale first. */\nexport function orderedLocales(model: ProjectModel, dictionary: AnalyzedDictionary): string[] {\n return [\n ...dictionary.locales.filter((l) => l === model.defaultLocale),\n ...dictionary.locales.filter((l) => l !== model.defaultLocale),\n ];\n}\n","/** Variable name -> dictionary name, for `const s = useDictionary(\"showcase\")`. */\nexport type Bindings = ReadonlyMap<string, string>;\n\n/**\n * `const s = useDictionary(\"showcase\")`, `const home = await getDictionary(\"home\", locale)`,\n * `let t: Home = injectDictionary<Home>(\"home\")`: a variable that holds a dictionary.\n */\nconst DECLARATION =\n /\\b(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*(?::[^=\\n]+)?=\\s*(?:await\\s+)?(?:[A-Za-z_$][\\w$]*\\.)*(?:getDictionary|useDictionary|injectDictionary)\\s*(?:<[^()]*?>)?\\(\\s*([\"'`])([^\"'`$\\n]+)\\2/g;\n\n/**\n * Finds the variables in a file that hold a dictionary, so `s.nav.features` can be resolved to\n * `showcase.nav.features`. It is a text match: a variable that is reassigned or shadowed in another\n * scope may resolve to the wrong dictionary, which only affects editor hints.\n */\nexport function findBindings(text: string): Bindings {\n const bindings = new Map<string, string>();\n for (const match of text.matchAll(DECLARATION)) {\n bindings.set(match[1], match[3]);\n }\n return bindings;\n}\n","import { scanReferences, type AnalyzedDictionary, type Reference } from \"@dialexjs/cli/api\";\n\nimport type { Bindings } from \"./bindings.js\";\nimport type { ProjectModel } from \"./model.js\";\n\n/** `getDictionary(\"home\").nav.about` -> the `.nav.about` member chain after the call. */\nconst MEMBER_CHAIN =\n /(?:getDictionary|useDictionary)\\(\\s*([\"'`])([^\"'`$\\n]+)\\1[^()\\n]*\\)((?:\\??\\.[A-Za-z_$][\\w$]*)+)/dg;\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * The Dialex reference under the cursor on one line of code: a dictionary name, a `t(\"a.b.c\")`\n * path, a member of `getDictionary(\"a\")` such as `.title`, or, with `bindings`, a member of a\n * variable that holds a dictionary (`s.nav.features` after `const s = useDictionary(\"showcase\")`).\n * Offsets are into `lineText`.\n */\nexport function findReferenceAt(\n lineText: string,\n character: number,\n bindings?: Bindings,\n): Reference | undefined {\n const direct = scanReferences(lineText).find((r) => character >= r.start && character <= r.end);\n if (direct) return direct;\n\n for (const match of lineText.matchAll(MEMBER_CHAIN)) {\n const dictionary = match[2];\n const [chainStart] = match.indices![3] as [number, number];\n const members = /\\??\\.([A-Za-z_$][\\w$]*)/g;\n const keys: string[] = [];\n for (const member of match[3].matchAll(members)) {\n const start = chainStart + member.index! + member[0].length - member[1].length;\n const end = start + member[1].length;\n keys.push(member[1]);\n if (character >= start && character <= end) {\n return { kind: \"path\", value: [dictionary, ...keys].join(\".\"), start, end };\n }\n }\n }\n\n for (const [name, dictionary] of bindings ?? []) {\n const chain = new RegExp(\n `(?<![\\\\w$.])${escapeRegExp(name)}(?![\\\\w$])((?:\\\\??\\\\.[A-Za-z_$][\\\\w$]*)*)`,\n \"dg\",\n );\n for (const match of lineText.matchAll(chain)) {\n const nameStart = match.index!;\n const nameEnd = nameStart + name.length;\n if (character >= nameStart && character <= nameEnd) {\n return { kind: \"dictionary\", value: dictionary, start: nameStart, end: nameEnd };\n }\n\n const [chainStart] = match.indices![1] as [number, number];\n const keys: string[] = [];\n for (const member of match[1].matchAll(/\\??\\.([A-Za-z_$][\\w$]*)/g)) {\n const start = chainStart + member.index! + member[0].length - member[1].length;\n const end = start + member[1].length;\n keys.push(member[1]);\n if (character >= start && character <= end) {\n return { kind: \"path\", value: [dictionary, ...keys].join(\".\"), start, end };\n }\n }\n }\n }\n return undefined;\n}\n\nexport interface ResolvedReference {\n dictionary: AnalyzedDictionary;\n /** Empty for a reference to the dictionary itself. */\n keyPath: string[];\n}\n\nexport function resolveReference(\n model: ProjectModel,\n ref: Reference,\n): ResolvedReference | undefined {\n if (ref.kind === \"dictionary\") {\n const dictionary = model.dictionaries.get(ref.value);\n return dictionary ? { dictionary, keyPath: [] } : undefined;\n }\n const [name, ...keyPath] = ref.value.split(\".\");\n const dictionary = model.dictionaries.get(name);\n return dictionary ? { dictionary, keyPath } : undefined;\n}\n\n/** Whether `keyPath` is a leaf, a group of leaves, or nothing in this dictionary. */\nexport function classifyPath(\n dictionary: AnalyzedDictionary,\n keyPath: string[],\n): \"leaf\" | \"group\" | \"missing\" {\n const joined = keyPath.join(\".\");\n if (dictionary.paths.includes(joined)) return \"leaf\";\n return dictionary.paths.some((p) => p.startsWith(`${joined}.`)) ? \"group\" : \"missing\";\n}\n","import path from \"node:path\";\n\nimport { getLeafSource, type AnalyzedDictionary, type Reference } from \"@dialexjs/cli/api\";\n\nimport { orderedLocales, type ProjectModel } from \"./model.js\";\nimport { classifyPath, resolveReference } from \"./references.js\";\n\n/** Escapes Markdown so translation text cannot change the hover's formatting. */\nexport function escapeMarkdown(text: string): string {\n return text\n .replace(/[\\\\`*_{}[\\]()#+!|<>~]/g, \"\\\\$&\")\n .replace(/\\r?\\n/g, \"<br>\")\n .slice(0, 400);\n}\n\nfunction cell(dictionary: AnalyzedDictionary, locale: string, keyPath: string[]): string {\n const leaf = dictionary.leaves.get(locale)?.get(keyPath.join(\".\"));\n if (!leaf) return \"_missing_\";\n if (leaf.kind === \"string\") return escapeMarkdown(leaf.value ?? \"\");\n if (leaf.kind === \"function\") {\n const source = dictionary.df ? getLeafSource(dictionary.df, locale, keyPath) : undefined;\n return source\n ? `\\`${source.replace(/`/g, \"'\").replace(/\\s+/g, \" \").slice(0, 160)}\\``\n : \"_function_\";\n }\n return \"_value_\";\n}\n\n/**\n * Markdown for a hover over a Dialex reference: every locale's text for a key, or a summary of a\n * dictionary. Returns `undefined` for unknown references (diagnostics already flag those).\n */\nexport function buildHover(model: ProjectModel, ref: Reference): string | undefined {\n const resolved = resolveReference(model, ref);\n if (!resolved) return undefined;\n const { dictionary, keyPath } = resolved;\n const file = path.basename(dictionary.file);\n\n if (keyPath.length === 0) {\n return [\n `**${dictionary.name}** · ${file}`,\n \"\",\n `${dictionary.paths.length} key${dictionary.paths.length === 1 ? \"\" : \"s\"} · locales: ${dictionary.locales.join(\", \")}`,\n ].join(\"\\n\");\n }\n\n const kind = classifyPath(dictionary, keyPath);\n const title = `**${dictionary.name}.${keyPath.join(\".\")}** · ${file}`;\n\n if (kind === \"missing\") return undefined;\n\n if (kind === \"group\") {\n const prefix = `${keyPath.join(\".\")}.`;\n const children = new Set(\n dictionary.paths\n .filter((p) => p.startsWith(prefix))\n .map((p) => p.slice(prefix.length).split(\".\")[0]),\n );\n return `${title}\\n\\n${children.size} key${children.size === 1 ? \"\" : \"s\"}: ${[...children].map((c) => `\\`${c}\\``).join(\", \")}`;\n }\n\n const rows = orderedLocales(model, dictionary).map(\n (locale) => `| ${locale} | ${cell(dictionary, locale, keyPath)} |`,\n );\n return [title, \"\", \"| Locale | Text |\", \"| --- | --- |\", ...rows].join(\"\\n\");\n}\n","import { dictionaryLocation, locationOf, type SourceRange } from \"@dialexjs/cli/api\";\nimport type { Reference } from \"@dialexjs/cli/api\";\n\nimport { orderedLocales, type ProjectModel } from \"./model.js\";\nimport { resolveReference } from \"./references.js\";\n\nexport interface DefinitionTarget {\n file: string;\n range: SourceRange;\n}\n\nconst START: SourceRange = { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } };\n\n/**\n * Where a reference is defined: the key in the default locale if it has one, otherwise in the\n * first locale that does. A dictionary reference points at the dictionary object.\n */\nexport function definitionFor(model: ProjectModel, ref: Reference): DefinitionTarget | undefined {\n const resolved = resolveReference(model, ref);\n if (!resolved) return undefined;\n const { dictionary, keyPath } = resolved;\n const { df } = dictionary;\n if (!df) return { file: dictionary.file, range: START };\n\n if (keyPath.length === 0) {\n return { file: dictionary.file, range: dictionaryLocation(df) ?? START };\n }\n\n for (const locale of orderedLocales(model, dictionary)) {\n const range = locationOf(df, locale, keyPath);\n if (range) return { file: dictionary.file, range };\n }\n return undefined;\n}\n","import type { AnalyzedDictionary } from \"@dialexjs/cli/api\";\n\nimport type { Bindings } from \"./bindings.js\";\nimport type { ProjectModel } from \"./model.js\";\n\nexport type CompletionContext =\n | { kind: \"dictionary\"; call: string; typed: string; length: number }\n | { kind: \"path\"; dictionary: string; parent: string[]; typed: string; length: number };\n\nconst CALL = /(?<![\\w$.])(t|getDictionary|useDictionary|DialexDictionary)\\(\\s*([\"'`])([^\"'`\\n]*)$/;\n\n/**\n * Whether the cursor is inside the string argument of a Dialex call, and what is being typed.\n * `textBeforeCursor` is the line up to the cursor. `length` is how many characters before the\n * cursor a completion replaces.\n */\nexport function completionContextAt(\n textBeforeCursor: string,\n bindings?: Bindings,\n): CompletionContext | undefined {\n const match = CALL.exec(textBeforeCursor);\n if (!match) return bindings ? memberContextAt(textBeforeCursor, bindings) : undefined;\n const [, call, , value] = match;\n\n if (call === \"t\" && value.includes(\".\")) {\n const segments = value.split(\".\");\n const typed = segments.pop()!;\n const [dictionary, ...parent] = segments;\n return { kind: \"path\", dictionary, parent, typed, length: typed.length };\n }\n return { kind: \"dictionary\", call, typed: value, length: value.length };\n}\n\n/** `s.nav.fe|` where `s` holds a dictionary: the keys under `nav` that start with `fe`. */\nfunction memberContextAt(\n textBeforeCursor: string,\n bindings: Bindings,\n): CompletionContext | undefined {\n for (const [name, dictionary] of bindings) {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = new RegExp(\n `(?<![\\\\w$.])${escaped}((?:\\\\??\\\\.[A-Za-z_$][\\\\w$]*)*)\\\\??\\\\.([A-Za-z_$][\\\\w$]*)?$`,\n ).exec(textBeforeCursor);\n if (!match) continue;\n\n const parent = [...match[1].matchAll(/\\??\\.([A-Za-z_$][\\w$]*)/g)].map((m) => m[1]);\n const typed = match[2] ?? \"\";\n return { kind: \"path\", dictionary, parent, typed, length: typed.length };\n }\n return undefined;\n}\n\nexport interface CompletionEntry {\n label: string;\n kind: \"dictionary\" | \"group\" | \"leaf\";\n detail: string;\n /** Text to insert in place of what was typed. */\n insertText: string;\n /** Re-open the suggestion list after inserting (after `home.` or `nav.`). */\n retrigger: boolean;\n documentation?: string;\n}\n\nconst preview = (text: string | undefined) =>\n text === undefined ? undefined : text.length > 60 ? `${text.slice(0, 57)}...` : text;\n\nfunction dictionaryEntries(\n model: ProjectModel,\n context: Extract<CompletionContext, { kind: \"dictionary\" }>,\n) {\n return [...model.dictionaries.values()]\n .filter((d) => d.name.startsWith(context.typed))\n .map<CompletionEntry>((d) => {\n // t(\"home.title\") continues with a dot; getDictionary(\"home\") is complete as is\n const continues = context.call === \"t\";\n return {\n label: d.name,\n kind: \"dictionary\",\n detail: `${d.paths.length} keys · ${d.locales.join(\", \")}`,\n insertText: continues ? `${d.name}.` : d.name,\n retrigger: continues,\n };\n });\n}\n\nfunction pathEntries(\n model: ProjectModel,\n dictionary: AnalyzedDictionary,\n context: Extract<CompletionContext, { kind: \"path\" }>,\n) {\n const prefix = context.parent.length > 0 ? `${context.parent.join(\".\")}.` : \"\";\n const children = new Map<string, { leaf: boolean }>();\n\n for (const keyPath of dictionary.paths) {\n if (!keyPath.startsWith(prefix)) continue;\n const rest = keyPath.slice(prefix.length).split(\".\");\n const name = rest[0];\n if (!name.startsWith(context.typed)) continue;\n const entry = children.get(name) ?? { leaf: true };\n if (rest.length > 1) entry.leaf = false;\n children.set(name, entry);\n }\n\n return [...children].map<CompletionEntry>(([name, { leaf }]) => {\n const full = `${prefix}${name}`;\n const holder = [model.defaultLocale, ...dictionary.locales].find((l) =>\n dictionary.leaves.get(l)?.has(full),\n );\n const text = holder ? dictionary.leaves.get(holder)!.get(full)! : undefined;\n return {\n label: name,\n kind: leaf ? \"leaf\" : \"group\",\n detail: leaf\n ? (preview(text?.kind === \"string\" ? text.value : text ? `(${text.kind})` : undefined) ??\n \"\")\n : \"keys…\",\n insertText: leaf ? name : `${name}.`,\n retrigger: !leaf,\n };\n });\n}\n\n/** Suggestions for the string being typed, filtered by what is already there. */\nexport function completionEntries(\n model: ProjectModel,\n context: CompletionContext,\n): CompletionEntry[] {\n if (context.kind === \"dictionary\") return dictionaryEntries(model, context);\n const dictionary = model.dictionaries.get(context.dictionary);\n return dictionary ? pathEntries(model, dictionary, context) : [];\n}\n","import {\n TODO_PREFIX,\n copyLeaf,\n hasPath,\n listLocales,\n parseDictionaryText,\n renderDictionaryFile,\n setString,\n} from \"@dialexjs/cli/api\";\n\nexport interface MissingKey {\n locale: string;\n path: string[];\n /** A locale that has the key, to copy its value from. */\n sourceLocale?: string;\n}\n\n/**\n * New text for a dictionary file with `missing` keys added to their locales, copied from the\n * source locale (strings get the `[TODO] ` marker, like `dialex check --fix`). Returns\n * `undefined` if nothing could be added.\n */\nexport function addMissingKeys(\n file: string,\n text: string,\n missing: MissingKey[],\n): string | undefined {\n const df = parseDictionaryText(file, text);\n if (!df) return undefined;\n\n let changed = false;\n for (const { locale, path, sourceLocale } of missing) {\n if (!sourceLocale) continue;\n if (copyLeaf(df, sourceLocale, locale, path, (value) => `${TODO_PREFIX}${value}`))\n changed = true;\n }\n return changed ? renderDictionaryFile(df) : undefined;\n}\n\n/**\n * New text for a dictionary file with a key that code refers to but the dictionary lacks, added\n * to every locale as a `[TODO]` placeholder named after the key.\n */\nexport function addUnknownKey(file: string, text: string, keyPath: string[]): string | undefined {\n const df = parseDictionaryText(file, text);\n if (!df) return undefined;\n\n const placeholder = `${TODO_PREFIX}${keyPath[keyPath.length - 1]}`;\n let changed = false;\n for (const locale of listLocales(df)) {\n if (\n !hasPath(df, locale, keyPath) &&\n setString(df, locale, keyPath, placeholder) !== \"skipped\"\n ) {\n changed = true;\n }\n }\n return changed ? renderDictionaryFile(df) : undefined;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { scanFiles } from \"@dialexjs/cli/api\";\n\nexport interface ProjectRoot {\n root: string;\n /** Globs (relative to `root`) for nested projects that belong to someone else. */\n ignore: string[];\n}\n\n// On top of the CLI's built-in list and the project's `.gitignore` files.\nconst IGNORE = [\"**/.git/**\", \"**/.nuxt/**\"];\n\n/** The nearest folder at or above `dir` (but inside `folder`) that has a package.json. */\nfunction packageRoot(folder: string, dir: string): string {\n for (let current = dir; current.startsWith(folder); current = path.dirname(current)) {\n if (fs.existsSync(path.join(current, \"package.json\"))) return current;\n if (current === folder) break;\n }\n return folder;\n}\n\n/**\n * Finds the Dialex projects inside a workspace folder.\n *\n * - Every directory with a `dialex.config.*` or `i18n.config.*` is a project.\n * - A `*.content.ts` file that no such project contains belongs to the nearest folder with a\n * `package.json` (or the workspace folder), which then uses the default settings. This covers\n * monorepos where only some packages have a config file.\n * - A project excludes the projects nested inside it, so one dictionary is never reported twice.\n */\nexport function discoverProjects(folder: string): ProjectRoot[] {\n const configs = scanFiles(folder, [\"**/dialex.config.*\", \"**/i18n.config.*\"], {\n ignore: IGNORE,\n });\n const configured = [...new Set(configs.map((f) => path.dirname(f)))];\n const roots = new Set(configured);\n\n // Judge coverage against the configured projects only; a fallback root must not hide others.\n const dictionaries = scanFiles(folder, \"**/*.content.ts\", { ignore: IGNORE });\n for (const file of dictionaries) {\n if (!configured.some((root) => file.startsWith(root + path.sep))) {\n roots.add(packageRoot(folder, path.dirname(file)));\n }\n }\n\n const all = [...roots].sort((a, b) => a.length - b.length);\n return all.map((root) => ({\n root,\n ignore: all\n .filter((other) => other !== root && other.startsWith(root + path.sep))\n .map((other) => `${path.relative(root, other).split(path.sep).join(\"/\")}/**`),\n }));\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 #!/usr/bin/env node
2
+ import { createServer } from "./server.mjs";
3
+ import { ProposedFeatures, createConnection } from "vscode-languageserver/node.js";
4
+ //#region src/index.ts
5
+ console.log = (...args) => console.error(...args);
6
+ const connection = createConnection(ProposedFeatures.all);
7
+ createServer(connection);
8
+ connection.listen();
9
+ //#endregion
10
+ export {};
11
+
12
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { createConnection, ProposedFeatures } from \"vscode-languageserver/node.js\";\n\nimport { createServer } from \"./server.js\";\n\n// stdout carries the protocol; anything that logs there would corrupt it.\nconsole.log = (...args: unknown[]) => console.error(...args);\n\n// `--stdio` (what editors pass), `--node-ipc` and `--socket=<port>` are handled by the library.\nconst connection = createConnection(ProposedFeatures.all);\ncreateServer(connection);\nconnection.listen();\n"],"mappings":";;;;AAMA,QAAQ,OAAO,GAAG,SAAoB,QAAQ,MAAM,GAAG,IAAI;AAG3D,MAAM,aAAa,iBAAiB,iBAAiB,GAAG;AACxD,aAAa,UAAU;AACvB,WAAW,OAAO"}
@@ -0,0 +1,31 @@
1
+ import { Connection } from "vscode-languageserver/node.js";
2
+ //#region src/server.d.ts
3
+ /** What the client can configure under the `dialex` section. */
4
+ export interface Settings {
5
+ /** Turn diagnostics, hover and the other features off. */
6
+ enable: boolean;
7
+ /** Fade out keys and dictionaries that no source file seems to use. */
8
+ unusedKeys: boolean;
9
+ /**
10
+ * Regenerate `dialex.generated.ts` and `dialex-env.d.ts` when a dictionary or config file
11
+ * changes, in projects that already have a generated file.
12
+ */
13
+ autoGenerate: boolean;
14
+ /** Path to the Dialex config file, relative to each project root. */
15
+ configPath?: string;
16
+ }
17
+ export interface DialexServer {
18
+ /** Re-analyze every project now and publish diagnostics. */
19
+ refresh(): Promise<void>;
20
+ /** Regenerate the generated files of every project that has them, now. */
21
+ regenerate(): Promise<void>;
22
+ /** Stop file watchers and timers. */
23
+ dispose(): Promise<void>;
24
+ }
25
+ /**
26
+ * Wires Dialex's editor features to an LSP connection. Nothing in the project is executed:
27
+ * dictionaries and configs are read from the syntax tree (`runtime: false`).
28
+ */
29
+ export declare function createServer(connection: Connection): DialexServer;
30
+ //#endregion
31
+ //# sourceMappingURL=server.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;iBAqDiB;;EAEf;;EAEA;;;;;EAKA;;EAEA;;iBAkBe;;EAEf,WAAW;;EAEX,cAAc;;EAEd,WAAW;;;;;;wBA0EG,aAAa,YAAY,aAAa"}
@@ -0,0 +1,450 @@
1
+ import { addMissingKeys, addUnknownKey, buildHover, buildModel, completionContextAt, completionEntries, definitionFor, discoverProjects, findBindings, findReferenceAt, modelForFile } from "./features.mjs";
2
+ import { CodeActionKind, CompletionItemKind, DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesNotification, FileChangeType, TextDocumentSyncKind, TextDocuments } from "vscode-languageserver/node.js";
3
+ import fs from "node:fs";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { analyzeProject, clearGitignore, createAnalysisCache, generateDictionaries, readStaticConfig, renderGenerated, startGenerateWatcher } from "@dialexjs/cli/api";
6
+ import { TextDocument } from "vscode-languageserver-textdocument";
7
+ //#region src/server.ts
8
+ const DEFAULT_SETTINGS = {
9
+ enable: true,
10
+ unusedKeys: false,
11
+ autoGenerate: true
12
+ };
13
+ /** Files whose creation or removal can change the set of Dialex projects or what is scanned. */
14
+ const WATCHED_GLOBS = [
15
+ "**/*.content.ts",
16
+ "**/dialex.config.*",
17
+ "**/i18n.config.*",
18
+ "**/.gitignore"
19
+ ];
20
+ function severityOf(issue) {
21
+ if (issue.code === "unused-key" || issue.code === "unused-dictionary") return DiagnosticSeverity.Hint;
22
+ switch (issue.level) {
23
+ case "error": return DiagnosticSeverity.Error;
24
+ case "warning": return DiagnosticSeverity.Warning;
25
+ default: return DiagnosticSeverity.Information;
26
+ }
27
+ }
28
+ const COMPLETION_KINDS = {
29
+ dictionary: CompletionItemKind.Module,
30
+ group: CompletionItemKind.Folder,
31
+ leaf: CompletionItemKind.Text
32
+ };
33
+ /** An edit that replaces a whole document, which is how dictionary files are rewritten. */
34
+ function replaceAll(text, newText) {
35
+ const lines = text.split("\n");
36
+ return {
37
+ range: {
38
+ start: {
39
+ line: 0,
40
+ character: 0
41
+ },
42
+ end: {
43
+ line: lines.length - 1,
44
+ character: lines[lines.length - 1].length
45
+ }
46
+ },
47
+ newText
48
+ };
49
+ }
50
+ function toDiagnostic(issue) {
51
+ const severity = severityOf(issue);
52
+ return {
53
+ range: issue.range ? {
54
+ start: {
55
+ line: issue.range.start.line,
56
+ character: issue.range.start.column
57
+ },
58
+ end: {
59
+ line: issue.range.end.line,
60
+ character: issue.range.end.column
61
+ }
62
+ } : {
63
+ start: {
64
+ line: 0,
65
+ character: 0
66
+ },
67
+ end: {
68
+ line: 0,
69
+ character: 0
70
+ }
71
+ },
72
+ message: issue.message,
73
+ severity,
74
+ source: "dialex",
75
+ code: issue.code,
76
+ tags: severity === DiagnosticSeverity.Hint ? [DiagnosticTag.Unnecessary] : void 0,
77
+ data: {
78
+ code: issue.code,
79
+ path: issue.path,
80
+ locale: issue.locale,
81
+ sourceLocale: issue.sourceLocale,
82
+ dictionary: issue.dictionary
83
+ }
84
+ };
85
+ }
86
+ const uriToPath = (uri) => uri.startsWith("file:") ? fileURLToPath(uri) : void 0;
87
+ /**
88
+ * Wires Dialex's editor features to an LSP connection. Nothing in the project is executed:
89
+ * dictionaries and configs are read from the syntax tree (`runtime: false`).
90
+ */
91
+ function createServer(connection) {
92
+ const documents = new TextDocuments(TextDocument);
93
+ const cache = createAnalysisCache();
94
+ const states = /* @__PURE__ */ new Map();
95
+ const projectCache = /* @__PURE__ */ new Map();
96
+ let folders = [];
97
+ let canConfigure = false;
98
+ let settings = { ...DEFAULT_SETTINGS };
99
+ let published = /* @__PURE__ */ new Set();
100
+ let timer;
101
+ let generateTimer;
102
+ /** True when the client sends file events itself; otherwise the server watches the disk. */
103
+ let clientWatches = false;
104
+ const watchers = /* @__PURE__ */ new Map();
105
+ const projectsIn = (folder) => {
106
+ let projects = projectCache.get(folder);
107
+ if (!projects) {
108
+ projects = discoverProjects(folder);
109
+ projectCache.set(folder, projects);
110
+ }
111
+ return projects;
112
+ };
113
+ const forgetLayout = () => {
114
+ projectCache.clear();
115
+ clearGitignore(cache);
116
+ };
117
+ async function loadSettings() {
118
+ settings = { ...DEFAULT_SETTINGS };
119
+ if (!canConfigure) return;
120
+ try {
121
+ const value = await connection.workspace.getConfiguration("dialex");
122
+ if (value && typeof value === "object") {
123
+ if (typeof value.enable === "boolean") settings.enable = value.enable;
124
+ if (typeof value.unusedKeys === "boolean") settings.unusedKeys = value.unusedKeys;
125
+ if (typeof value.autoGenerate === "boolean") settings.autoGenerate = value.autoGenerate;
126
+ if (typeof value.configPath === "string" && value.configPath) settings.configPath = value.configPath;
127
+ }
128
+ } catch {}
129
+ }
130
+ function publish() {
131
+ const byFile = /* @__PURE__ */ new Map();
132
+ for (const { issues } of states.values()) for (const issue of issues) {
133
+ const list = byFile.get(issue.file) ?? [];
134
+ list.push(toDiagnostic(issue));
135
+ byFile.set(issue.file, list);
136
+ }
137
+ const next = /* @__PURE__ */ new Set();
138
+ for (const [file, diagnostics] of byFile) {
139
+ const uri = pathToFileURL(file).href;
140
+ next.add(uri);
141
+ connection.sendDiagnostics({
142
+ uri,
143
+ diagnostics
144
+ });
145
+ }
146
+ for (const uri of published) if (!next.has(uri)) connection.sendDiagnostics({
147
+ uri,
148
+ diagnostics: []
149
+ });
150
+ published = next;
151
+ }
152
+ /** The projects whose generated file exists; the others do not use one. */
153
+ function generatedProjects() {
154
+ const found = [];
155
+ for (const folder of folders) for (const { root } of projectsIn(folder)) {
156
+ const options = {
157
+ config: settings.configPath,
158
+ static: true
159
+ };
160
+ try {
161
+ if (fs.existsSync(renderGenerated(root, options).outputPath)) found.push({
162
+ root,
163
+ options
164
+ });
165
+ } catch (error) {
166
+ connection.console.error(`[${root}] generate failed: ${error.message}`);
167
+ }
168
+ }
169
+ return found;
170
+ }
171
+ /**
172
+ * Keeps `dialex.generated.ts` and `dialex-env.d.ts` current. The config is read from its syntax
173
+ * tree, so no project code runs.
174
+ */
175
+ async function regenerate() {
176
+ if (!settings.autoGenerate || !settings.enable) return;
177
+ for (const { root, options } of generatedProjects()) try {
178
+ const { outputPath } = renderGenerated(root, options);
179
+ const before = fs.readFileSync(outputPath, "utf-8");
180
+ const { files } = generateDictionaries(root, options);
181
+ if (fs.readFileSync(outputPath, "utf-8") !== before) connection.console.info(`[${root}] regenerated ${outputPath.slice(root.length + 1)} (${files.length} dictionaries)`);
182
+ } catch (error) {
183
+ connection.console.error(`[${root}] generate failed: ${error.message}`);
184
+ }
185
+ }
186
+ /** Without client file events, watch each project that has a generated file ourselves. */
187
+ async function syncWatchers() {
188
+ const wanted = /* @__PURE__ */ new Map();
189
+ if (!clientWatches && settings.autoGenerate && settings.enable) for (const { root, options } of generatedProjects()) wanted.set(root, options);
190
+ for (const [root, watcher] of watchers) if (!wanted.has(root)) {
191
+ watchers.delete(root);
192
+ await watcher.close();
193
+ }
194
+ for (const [root, options] of wanted) {
195
+ if (watchers.has(root)) continue;
196
+ try {
197
+ watchers.set(root, startGenerateWatcher(root, options, () => {
198
+ regenerate().then(() => schedule());
199
+ }, 250, (message) => connection.console.info(`[${root}] ${message}`)));
200
+ } catch (error) {
201
+ connection.console.error(`[${root}] could not watch: ${error.message}`);
202
+ }
203
+ }
204
+ }
205
+ async function refresh() {
206
+ await loadSettings();
207
+ states.clear();
208
+ if (settings.enable) for (const folder of folders) for (const { root, ignore } of projectsIn(folder)) try {
209
+ const { config, notes } = readStaticConfig(root, settings.configPath);
210
+ for (const note of notes) connection.console.info(`[${root}] ${note}`);
211
+ const result = await analyzeProject({
212
+ root,
213
+ config,
214
+ runtime: false,
215
+ ignore,
216
+ unused: settings.unusedKeys,
217
+ cache
218
+ });
219
+ states.set(root, {
220
+ model: buildModel(root, config.defaultLocale, result),
221
+ issues: result.issues
222
+ });
223
+ } catch (error) {
224
+ connection.console.error(`[${root}] analysis failed: ${error.message}`);
225
+ }
226
+ publish();
227
+ await syncWatchers();
228
+ }
229
+ function schedule() {
230
+ if (timer) clearTimeout(timer);
231
+ timer = setTimeout(() => void refresh(), 300);
232
+ }
233
+ function scheduleGenerate() {
234
+ if (generateTimer) clearTimeout(generateTimer);
235
+ generateTimer = setTimeout(() => void regenerate(), 250);
236
+ }
237
+ connection.onInitialize((params) => {
238
+ folders = (params.workspaceFolders ?? []).map((folder) => uriToPath(folder.uri)).filter((path) => path !== void 0);
239
+ if (folders.length === 0 && params.rootUri) {
240
+ const root = uriToPath(params.rootUri);
241
+ if (root) folders = [root];
242
+ }
243
+ canConfigure = params.capabilities.workspace?.configuration === true;
244
+ clientWatches = params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true;
245
+ return {
246
+ capabilities: {
247
+ textDocumentSync: {
248
+ openClose: true,
249
+ change: TextDocumentSyncKind.Incremental,
250
+ save: { includeText: false }
251
+ },
252
+ hoverProvider: true,
253
+ definitionProvider: true,
254
+ completionProvider: { triggerCharacters: [
255
+ "\"",
256
+ "'",
257
+ "`",
258
+ "."
259
+ ] },
260
+ codeActionProvider: { codeActionKinds: [CodeActionKind.QuickFix] }
261
+ },
262
+ serverInfo: { name: "dialex-language-server" }
263
+ };
264
+ });
265
+ connection.onInitialized(async () => {
266
+ if (clientWatches) try {
267
+ await connection.client.register(DidChangeWatchedFilesNotification.type, { watchers: WATCHED_GLOBS.map((globPattern) => ({ globPattern })) });
268
+ } catch {
269
+ clientWatches = false;
270
+ }
271
+ schedule();
272
+ scheduleGenerate();
273
+ });
274
+ connection.onDidChangeConfiguration(() => schedule());
275
+ connection.onDidChangeWatchedFiles(({ changes }) => {
276
+ if (changes.some((change) => change.type !== FileChangeType.Changed)) projectCache.clear();
277
+ if (changes.some((change) => change.uri.endsWith(".gitignore"))) forgetLayout();
278
+ schedule();
279
+ scheduleGenerate();
280
+ });
281
+ documents.onDidSave(() => {
282
+ schedule();
283
+ scheduleGenerate();
284
+ });
285
+ connection.onShutdown(() => dispose());
286
+ /** The project model for a file, unless the features are turned off. */
287
+ const modelFor = (file) => settings.enable ? modelForFile([...states.values()].map((state) => state.model), file) : void 0;
288
+ /** One line of an open document, without its line break. */
289
+ const lineOf = (document, line) => document.getText({
290
+ start: {
291
+ line,
292
+ character: 0
293
+ },
294
+ end: {
295
+ line: line + 1,
296
+ character: 0
297
+ }
298
+ }).replace(/\r?\n$/, "");
299
+ connection.onHover((params) => {
300
+ const document = documents.get(params.textDocument.uri);
301
+ const file = uriToPath(params.textDocument.uri);
302
+ const model = document && file ? modelFor(file) : void 0;
303
+ if (!document || !model) return null;
304
+ const ref = findReferenceAt(lineOf(document, params.position.line), params.position.character, findBindings(document.getText()));
305
+ const markdown = ref ? buildHover(model, ref) : void 0;
306
+ if (!ref || !markdown) return null;
307
+ return {
308
+ contents: {
309
+ kind: "markdown",
310
+ value: markdown
311
+ },
312
+ range: {
313
+ start: {
314
+ line: params.position.line,
315
+ character: ref.start
316
+ },
317
+ end: {
318
+ line: params.position.line,
319
+ character: ref.end
320
+ }
321
+ }
322
+ };
323
+ });
324
+ connection.onDefinition((params) => {
325
+ const document = documents.get(params.textDocument.uri);
326
+ const file = uriToPath(params.textDocument.uri);
327
+ const model = document && file ? modelFor(file) : void 0;
328
+ if (!document || !model) return null;
329
+ const ref = findReferenceAt(lineOf(document, params.position.line), params.position.character, findBindings(document.getText()));
330
+ const target = ref ? definitionFor(model, ref) : void 0;
331
+ if (!target) return null;
332
+ return {
333
+ uri: pathToFileURL(target.file).href,
334
+ range: {
335
+ start: {
336
+ line: target.range.start.line,
337
+ character: target.range.start.column
338
+ },
339
+ end: {
340
+ line: target.range.end.line,
341
+ character: target.range.end.column
342
+ }
343
+ }
344
+ };
345
+ });
346
+ connection.onCompletion((params) => {
347
+ const document = documents.get(params.textDocument.uri);
348
+ const file = uriToPath(params.textDocument.uri);
349
+ const model = document && file ? modelFor(file) : void 0;
350
+ if (!document || !model) return [];
351
+ const before = lineOf(document, params.position.line).slice(0, params.position.character);
352
+ const context = completionContextAt(before, findBindings(document.getText()));
353
+ if (!context) return [];
354
+ const range = {
355
+ start: {
356
+ line: params.position.line,
357
+ character: params.position.character - context.length
358
+ },
359
+ end: params.position
360
+ };
361
+ return completionEntries(model, context).map((entry) => ({
362
+ label: entry.label,
363
+ kind: COMPLETION_KINDS[entry.kind],
364
+ detail: entry.detail,
365
+ documentation: entry.documentation,
366
+ filterText: entry.label,
367
+ textEdit: {
368
+ range,
369
+ newText: entry.insertText
370
+ }
371
+ }));
372
+ });
373
+ connection.onCodeAction((params) => {
374
+ const file = uriToPath(params.textDocument.uri);
375
+ const document = documents.get(params.textDocument.uri);
376
+ if (!file || !document || !settings.enable) return [];
377
+ const actions = [];
378
+ const text = document.getText();
379
+ const model = modelFor(file);
380
+ for (const diagnostic of params.context.diagnostics) {
381
+ const data = diagnostic.data;
382
+ if (diagnostic.source !== "dialex" || !data?.path) continue;
383
+ if (data.code === "missing-key" && data.locale) {
384
+ const updated = addMissingKeys(file, text, [{
385
+ locale: data.locale,
386
+ path: data.path,
387
+ sourceLocale: data.sourceLocale
388
+ }]);
389
+ if (!updated) continue;
390
+ actions.push({
391
+ title: `Add "${data.path.join(".")}" to ${data.locale} (marked [TODO])`,
392
+ kind: CodeActionKind.QuickFix,
393
+ diagnostics: [diagnostic],
394
+ isPreferred: true,
395
+ edit: { changes: { [params.textDocument.uri]: [replaceAll(text, updated)] } }
396
+ });
397
+ }
398
+ if (data.code === "unknown-path" && data.dictionary) {
399
+ const dictionary = model?.dictionaries.get(data.dictionary);
400
+ if (!dictionary) continue;
401
+ const dictionaryUri = pathToFileURL(dictionary.file).href;
402
+ const open = documents.get(dictionaryUri);
403
+ let dictionaryText;
404
+ try {
405
+ dictionaryText = open ? open.getText() : fs.readFileSync(dictionary.file, "utf-8");
406
+ } catch {
407
+ continue;
408
+ }
409
+ const updated = addUnknownKey(dictionary.file, dictionaryText, data.path);
410
+ if (!updated) continue;
411
+ actions.push({
412
+ title: `Add "${data.path.join(".")}" to the "${dictionary.name}" dictionary`,
413
+ kind: CodeActionKind.QuickFix,
414
+ diagnostics: [diagnostic],
415
+ edit: { changes: { [dictionaryUri]: [replaceAll(dictionaryText, updated)] } }
416
+ });
417
+ }
418
+ }
419
+ const missing = [...states.values()].flatMap((state) => state.issues).filter((issue) => issue.file === file && issue.code === "missing-key").filter((issue) => issue.locale && issue.path).map((issue) => ({
420
+ locale: issue.locale,
421
+ path: issue.path,
422
+ sourceLocale: issue.sourceLocale
423
+ }));
424
+ if (missing.length > 1) {
425
+ const updated = addMissingKeys(file, text, missing);
426
+ if (updated) actions.push({
427
+ title: `Add all ${missing.length} missing keys (marked [TODO])`,
428
+ kind: CodeActionKind.QuickFix,
429
+ edit: { changes: { [params.textDocument.uri]: [replaceAll(text, updated)] } }
430
+ });
431
+ }
432
+ return actions;
433
+ });
434
+ documents.listen(connection);
435
+ async function dispose() {
436
+ if (timer) clearTimeout(timer);
437
+ if (generateTimer) clearTimeout(generateTimer);
438
+ await Promise.all([...watchers.values()].map((watcher) => watcher.close()));
439
+ watchers.clear();
440
+ }
441
+ return {
442
+ refresh,
443
+ regenerate,
444
+ dispose
445
+ };
446
+ }
447
+ //#endregion
448
+ export { createServer };
449
+
450
+ //# sourceMappingURL=server.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n analyzeProject,\n clearGitignore,\n createAnalysisCache,\n generateDictionaries,\n readStaticConfig,\n renderGenerated,\n startGenerateWatcher,\n type AnalysisIssue,\n} from \"@dialexjs/cli/api\";\nimport { TextDocument } from \"vscode-languageserver-textdocument\";\nimport {\n CodeActionKind,\n CompletionItemKind,\n DiagnosticSeverity,\n DiagnosticTag,\n DidChangeWatchedFilesNotification,\n FileChangeType,\n TextDocumentSyncKind,\n TextDocuments,\n type CodeAction,\n type CompletionItem,\n type Connection,\n type Diagnostic,\n type Hover,\n type Location,\n type TextEdit,\n type InitializeParams,\n type InitializeResult,\n} from \"vscode-languageserver/node.js\";\n\nimport {\n addMissingKeys,\n addUnknownKey,\n buildHover,\n buildModel,\n completionContextAt,\n completionEntries,\n definitionFor,\n discoverProjects,\n findBindings,\n findReferenceAt,\n modelForFile,\n type CompletionEntry,\n type MissingKey,\n type ProjectModel,\n type ProjectRoot,\n} from \"./features.js\";\n\n/** What the client can configure under the `dialex` section. */\nexport interface Settings {\n /** Turn diagnostics, hover and the other features off. */\n enable: boolean;\n /** Fade out keys and dictionaries that no source file seems to use. */\n unusedKeys: boolean;\n /**\n * Regenerate `dialex.generated.ts` and `dialex-env.d.ts` when a dictionary or config file\n * changes, in projects that already have a generated file.\n */\n autoGenerate: boolean;\n /** Path to the Dialex config file, relative to each project root. */\n configPath?: string;\n}\n\nconst DEFAULT_SETTINGS: Settings = { enable: true, unusedKeys: false, autoGenerate: true };\n\n/** Files whose creation or removal can change the set of Dialex projects or what is scanned. */\nconst WATCHED_GLOBS = [\n \"**/*.content.ts\",\n \"**/dialex.config.*\",\n \"**/i18n.config.*\",\n \"**/.gitignore\",\n];\n\ninterface ProjectState {\n model: ProjectModel;\n issues: AnalysisIssue[];\n}\n\nexport interface DialexServer {\n /** Re-analyze every project now and publish diagnostics. */\n refresh(): Promise<void>;\n /** Regenerate the generated files of every project that has them, now. */\n regenerate(): Promise<void>;\n /** Stop file watchers and timers. */\n dispose(): Promise<void>;\n}\n\nfunction severityOf(issue: AnalysisIssue): DiagnosticSeverity {\n if (issue.code === \"unused-key\" || issue.code === \"unused-dictionary\") {\n return DiagnosticSeverity.Hint;\n }\n switch (issue.level) {\n case \"error\":\n return DiagnosticSeverity.Error;\n case \"warning\":\n return DiagnosticSeverity.Warning;\n default:\n return DiagnosticSeverity.Information;\n }\n}\n\n/** What a quick fix needs from the issue that produced a diagnostic. */\ninterface IssueData {\n code: string;\n path?: string[];\n locale?: string;\n sourceLocale?: string;\n dictionary?: string;\n}\n\nconst COMPLETION_KINDS: Record<CompletionEntry[\"kind\"], CompletionItemKind> = {\n dictionary: CompletionItemKind.Module,\n group: CompletionItemKind.Folder,\n leaf: CompletionItemKind.Text,\n};\n\n/** An edit that replaces a whole document, which is how dictionary files are rewritten. */\nfunction replaceAll(text: string, newText: string): TextEdit {\n const lines = text.split(\"\\n\");\n return {\n range: {\n start: { line: 0, character: 0 },\n end: { line: lines.length - 1, character: lines[lines.length - 1].length },\n },\n newText,\n };\n}\n\nfunction toDiagnostic(issue: AnalysisIssue): Diagnostic {\n const severity = severityOf(issue);\n return {\n range: issue.range\n ? {\n start: { line: issue.range.start.line, character: issue.range.start.column },\n end: { line: issue.range.end.line, character: issue.range.end.column },\n }\n : { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } },\n message: issue.message,\n severity,\n source: \"dialex\",\n code: issue.code,\n tags: severity === DiagnosticSeverity.Hint ? [DiagnosticTag.Unnecessary] : undefined,\n data: {\n code: issue.code,\n path: issue.path,\n locale: issue.locale,\n sourceLocale: issue.sourceLocale,\n dictionary: issue.dictionary,\n } satisfies IssueData,\n };\n}\n\nconst uriToPath = (uri: string) => (uri.startsWith(\"file:\") ? fileURLToPath(uri) : undefined);\n\n/**\n * Wires Dialex's editor features to an LSP connection. Nothing in the project is executed:\n * dictionaries and configs are read from the syntax tree (`runtime: false`).\n */\nexport function createServer(connection: Connection): DialexServer {\n const documents = new TextDocuments(TextDocument);\n const cache = createAnalysisCache();\n const states = new Map<string, ProjectState>();\n const projectCache = new Map<string, ProjectRoot[]>();\n\n let folders: string[] = [];\n let canConfigure = false;\n let settings: Settings = { ...DEFAULT_SETTINGS };\n let published = new Set<string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let generateTimer: ReturnType<typeof setTimeout> | undefined;\n /** True when the client sends file events itself; otherwise the server watches the disk. */\n let clientWatches = false;\n const watchers = new Map<string, { close(): Promise<void> }>();\n\n const projectsIn = (folder: string): ProjectRoot[] => {\n let projects = projectCache.get(folder);\n if (!projects) {\n projects = discoverProjects(folder);\n projectCache.set(folder, projects);\n }\n return projects;\n };\n\n const forgetLayout = () => {\n projectCache.clear();\n clearGitignore(cache);\n };\n\n async function loadSettings(): Promise<void> {\n settings = { ...DEFAULT_SETTINGS };\n if (!canConfigure) return;\n try {\n const value = (await connection.workspace.getConfiguration(\"dialex\")) as\n | Partial<Settings>\n | null\n | undefined;\n if (value && typeof value === \"object\") {\n if (typeof value.enable === \"boolean\") settings.enable = value.enable;\n if (typeof value.unusedKeys === \"boolean\") settings.unusedKeys = value.unusedKeys;\n if (typeof value.autoGenerate === \"boolean\") settings.autoGenerate = value.autoGenerate;\n if (typeof value.configPath === \"string\" && value.configPath) {\n settings.configPath = value.configPath;\n }\n }\n } catch {\n // the client does not answer configuration requests; keep the defaults\n }\n }\n\n function publish(): void {\n const byFile = new Map<string, Diagnostic[]>();\n for (const { issues } of states.values()) {\n for (const issue of issues) {\n const list = byFile.get(issue.file) ?? [];\n list.push(toDiagnostic(issue));\n byFile.set(issue.file, list);\n }\n }\n\n const next = new Set<string>();\n for (const [file, diagnostics] of byFile) {\n const uri = pathToFileURL(file).href;\n next.add(uri);\n void connection.sendDiagnostics({ uri, diagnostics });\n }\n // Files that had problems before and have none now need an explicit empty list.\n for (const uri of published) {\n if (!next.has(uri)) void connection.sendDiagnostics({ uri, diagnostics: [] });\n }\n published = next;\n }\n\n /** The projects whose generated file exists; the others do not use one. */\n function generatedProjects(): { root: string; options: { config?: string; static: true } }[] {\n const found: { root: string; options: { config?: string; static: true } }[] = [];\n for (const folder of folders) {\n for (const { root } of projectsIn(folder)) {\n const options = { config: settings.configPath, static: true as const };\n try {\n if (fs.existsSync(renderGenerated(root, options).outputPath)) {\n found.push({ root, options });\n }\n } catch (error) {\n connection.console.error(`[${root}] generate failed: ${(error as Error).message}`);\n }\n }\n }\n return found;\n }\n\n /**\n * Keeps `dialex.generated.ts` and `dialex-env.d.ts` current. The config is read from its syntax\n * tree, so no project code runs.\n */\n async function regenerate(): Promise<void> {\n if (!settings.autoGenerate || !settings.enable) return;\n for (const { root, options } of generatedProjects()) {\n try {\n const { outputPath } = renderGenerated(root, options);\n const before = fs.readFileSync(outputPath, \"utf-8\");\n const { files } = generateDictionaries(root, options);\n if (fs.readFileSync(outputPath, \"utf-8\") !== before) {\n connection.console.info(\n `[${root}] regenerated ${outputPath.slice(root.length + 1)} (${files.length} dictionaries)`,\n );\n }\n } catch (error) {\n connection.console.error(`[${root}] generate failed: ${(error as Error).message}`);\n }\n }\n }\n\n /** Without client file events, watch each project that has a generated file ourselves. */\n async function syncWatchers(): Promise<void> {\n const wanted = new Map<string, { config?: string; static: true }>();\n if (!clientWatches && settings.autoGenerate && settings.enable) {\n for (const { root, options } of generatedProjects()) wanted.set(root, options);\n }\n\n for (const [root, watcher] of watchers) {\n if (!wanted.has(root)) {\n watchers.delete(root);\n await watcher.close();\n }\n }\n for (const [root, options] of wanted) {\n if (watchers.has(root)) continue;\n try {\n watchers.set(\n root,\n startGenerateWatcher(\n root,\n options,\n () => {\n void regenerate().then(() => schedule());\n },\n 250,\n (message) => connection.console.info(`[${root}] ${message}`),\n ),\n );\n } catch (error) {\n connection.console.error(`[${root}] could not watch: ${(error as Error).message}`);\n }\n }\n }\n\n async function refresh(): Promise<void> {\n await loadSettings();\n states.clear();\n\n if (settings.enable) {\n for (const folder of folders) {\n for (const { root, ignore } of projectsIn(folder)) {\n try {\n const { config, notes } = readStaticConfig(root, settings.configPath);\n for (const note of notes) connection.console.info(`[${root}] ${note}`);\n\n const result = await analyzeProject({\n root,\n config,\n runtime: false,\n ignore,\n unused: settings.unusedKeys,\n cache,\n });\n states.set(root, {\n model: buildModel(root, config.defaultLocale, result),\n issues: result.issues,\n });\n } catch (error) {\n connection.console.error(`[${root}] analysis failed: ${(error as Error).message}`);\n }\n }\n }\n }\n publish();\n await syncWatchers();\n }\n\n function schedule(): void {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 300);\n }\n\n function scheduleGenerate(): void {\n if (generateTimer) clearTimeout(generateTimer);\n generateTimer = setTimeout(() => void regenerate(), 250);\n }\n\n connection.onInitialize((params: InitializeParams): InitializeResult => {\n folders = (params.workspaceFolders ?? [])\n .map((folder) => uriToPath(folder.uri))\n .filter((path): path is string => path !== undefined);\n if (folders.length === 0 && params.rootUri) {\n const root = uriToPath(params.rootUri);\n if (root) folders = [root];\n }\n canConfigure = params.capabilities.workspace?.configuration === true;\n clientWatches =\n params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true;\n\n return {\n capabilities: {\n textDocumentSync: {\n openClose: true,\n change: TextDocumentSyncKind.Incremental,\n save: { includeText: false },\n },\n hoverProvider: true,\n definitionProvider: true,\n completionProvider: { triggerCharacters: ['\"', \"'\", \"`\", \".\"] },\n codeActionProvider: { codeActionKinds: [CodeActionKind.QuickFix] },\n },\n serverInfo: { name: \"dialex-language-server\" },\n };\n });\n\n connection.onInitialized(async () => {\n if (clientWatches) {\n try {\n await connection.client.register(DidChangeWatchedFilesNotification.type, {\n watchers: WATCHED_GLOBS.map((globPattern) => ({ globPattern })),\n });\n } catch {\n // the client refused; the server watches the disk itself\n clientWatches = false;\n }\n }\n schedule();\n scheduleGenerate();\n });\n\n connection.onDidChangeConfiguration(() => schedule());\n\n connection.onDidChangeWatchedFiles(({ changes }) => {\n // An edit cannot change which projects exist; a file appearing or disappearing can.\n if (changes.some((change) => change.type !== FileChangeType.Changed)) projectCache.clear();\n if (changes.some((change) => change.uri.endsWith(\".gitignore\"))) forgetLayout();\n schedule();\n scheduleGenerate();\n });\n\n documents.onDidSave(() => {\n schedule();\n scheduleGenerate();\n });\n\n connection.onShutdown(() => dispose());\n\n /** The project model for a file, unless the features are turned off. */\n const modelFor = (file: string): ProjectModel | undefined =>\n settings.enable\n ? modelForFile(\n [...states.values()].map((state) => state.model),\n file,\n )\n : undefined;\n\n /** One line of an open document, without its line break. */\n const lineOf = (document: TextDocument, line: number): string =>\n document\n .getText({ start: { line, character: 0 }, end: { line: line + 1, character: 0 } })\n .replace(/\\r?\\n$/, \"\");\n\n connection.onHover((params): Hover | null => {\n const document = documents.get(params.textDocument.uri);\n const file = uriToPath(params.textDocument.uri);\n const model = document && file ? modelFor(file) : undefined;\n if (!document || !model) return null;\n\n const ref = findReferenceAt(\n lineOf(document, params.position.line),\n params.position.character,\n findBindings(document.getText()),\n );\n const markdown = ref ? buildHover(model, ref) : undefined;\n if (!ref || !markdown) return null;\n\n return {\n contents: { kind: \"markdown\", value: markdown },\n range: {\n start: { line: params.position.line, character: ref.start },\n end: { line: params.position.line, character: ref.end },\n },\n };\n });\n\n connection.onDefinition((params): Location | null => {\n const document = documents.get(params.textDocument.uri);\n const file = uriToPath(params.textDocument.uri);\n const model = document && file ? modelFor(file) : undefined;\n if (!document || !model) return null;\n\n const ref = findReferenceAt(\n lineOf(document, params.position.line),\n params.position.character,\n findBindings(document.getText()),\n );\n const target = ref ? definitionFor(model, ref) : undefined;\n if (!target) return null;\n\n return {\n uri: pathToFileURL(target.file).href,\n range: {\n start: { line: target.range.start.line, character: target.range.start.column },\n end: { line: target.range.end.line, character: target.range.end.column },\n },\n };\n });\n\n connection.onCompletion((params): CompletionItem[] => {\n const document = documents.get(params.textDocument.uri);\n const file = uriToPath(params.textDocument.uri);\n const model = document && file ? modelFor(file) : undefined;\n if (!document || !model) return [];\n\n const before = lineOf(document, params.position.line).slice(0, params.position.character);\n const context = completionContextAt(before, findBindings(document.getText()));\n if (!context) return [];\n\n const range = {\n start: { line: params.position.line, character: params.position.character - context.length },\n end: params.position,\n };\n return completionEntries(model, context).map((entry) => ({\n label: entry.label,\n kind: COMPLETION_KINDS[entry.kind],\n detail: entry.detail,\n documentation: entry.documentation,\n filterText: entry.label,\n textEdit: { range, newText: entry.insertText },\n }));\n });\n\n connection.onCodeAction((params): CodeAction[] => {\n const file = uriToPath(params.textDocument.uri);\n const document = documents.get(params.textDocument.uri);\n if (!file || !document || !settings.enable) return [];\n\n const actions: CodeAction[] = [];\n const text = document.getText();\n const model = modelFor(file);\n\n for (const diagnostic of params.context.diagnostics) {\n const data = diagnostic.data as IssueData | undefined;\n if (diagnostic.source !== \"dialex\" || !data?.path) continue;\n\n if (data.code === \"missing-key\" && data.locale) {\n const updated = addMissingKeys(file, text, [\n { locale: data.locale, path: data.path, sourceLocale: data.sourceLocale },\n ]);\n if (!updated) continue;\n actions.push({\n title: `Add \"${data.path.join(\".\")}\" to ${data.locale} (marked [TODO])`,\n kind: CodeActionKind.QuickFix,\n diagnostics: [diagnostic],\n isPreferred: true,\n edit: { changes: { [params.textDocument.uri]: [replaceAll(text, updated)] } },\n });\n }\n\n if (data.code === \"unknown-path\" && data.dictionary) {\n const dictionary = model?.dictionaries.get(data.dictionary);\n if (!dictionary) continue;\n\n const dictionaryUri = pathToFileURL(dictionary.file).href;\n const open = documents.get(dictionaryUri);\n let dictionaryText: string;\n try {\n dictionaryText = open ? open.getText() : fs.readFileSync(dictionary.file, \"utf-8\");\n } catch {\n continue;\n }\n const updated = addUnknownKey(dictionary.file, dictionaryText, data.path);\n if (!updated) continue;\n actions.push({\n title: `Add \"${data.path.join(\".\")}\" to the \"${dictionary.name}\" dictionary`,\n kind: CodeActionKind.QuickFix,\n diagnostics: [diagnostic],\n edit: { changes: { [dictionaryUri]: [replaceAll(dictionaryText, updated)] } },\n });\n }\n }\n\n // One action for every missing key in this dictionary file\n const missing: MissingKey[] = [...states.values()]\n .flatMap((state) => state.issues)\n .filter((issue) => issue.file === file && issue.code === \"missing-key\")\n .filter((issue) => issue.locale && issue.path)\n .map((issue) => ({\n locale: issue.locale!,\n path: issue.path!,\n sourceLocale: issue.sourceLocale,\n }));\n if (missing.length > 1) {\n const updated = addMissingKeys(file, text, missing);\n if (updated) {\n actions.push({\n title: `Add all ${missing.length} missing keys (marked [TODO])`,\n kind: CodeActionKind.QuickFix,\n edit: { changes: { [params.textDocument.uri]: [replaceAll(text, updated)] } },\n });\n }\n }\n\n return actions;\n });\n\n documents.listen(connection);\n\n async function dispose(): Promise<void> {\n if (timer) clearTimeout(timer);\n if (generateTimer) clearTimeout(generateTimer);\n await Promise.all([...watchers.values()].map((watcher) => watcher.close()));\n watchers.clear();\n }\n\n return { refresh, regenerate, dispose };\n}\n"],"mappings":";;;;;;;AAmEA,MAAM,mBAA6B;CAAE,QAAQ;CAAM,YAAY;CAAO,cAAc;AAAK;;AAGzF,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;AACF;AAgBA,SAAS,WAAW,OAA0C;CAC5D,IAAI,MAAM,SAAS,gBAAgB,MAAM,SAAS,qBAChD,OAAO,mBAAmB;CAE5B,QAAQ,MAAM,OAAd;EACE,KAAK,SACH,OAAO,mBAAmB;EAC5B,KAAK,WACH,OAAO,mBAAmB;EAC5B,SACE,OAAO,mBAAmB;CAC9B;AACF;AAWA,MAAM,mBAAwE;CAC5E,YAAY,mBAAmB;CAC/B,OAAO,mBAAmB;CAC1B,MAAM,mBAAmB;AAC3B;;AAGA,SAAS,WAAW,MAAc,SAA2B;CAC3D,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7B,OAAO;EACL,OAAO;GACL,OAAO;IAAE,MAAM;IAAG,WAAW;GAAE;GAC/B,KAAK;IAAE,MAAM,MAAM,SAAS;IAAG,WAAW,MAAM,MAAM,SAAS,EAAE,CAAC;GAAO;EAC3E;EACA;CACF;AACF;AAEA,SAAS,aAAa,OAAkC;CACtD,MAAM,WAAW,WAAW,KAAK;CACjC,OAAO;EACL,OAAO,MAAM,QACT;GACE,OAAO;IAAE,MAAM,MAAM,MAAM,MAAM;IAAM,WAAW,MAAM,MAAM,MAAM;GAAO;GAC3E,KAAK;IAAE,MAAM,MAAM,MAAM,IAAI;IAAM,WAAW,MAAM,MAAM,IAAI;GAAO;EACvE,IACA;GAAE,OAAO;IAAE,MAA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O,aAAa,MAAM,CAAC,WAAW,MAAM,OAAO,CAAC,EAAE,EAAE;GAC9E,CAAC;EAEL;EAEA,OAAO;CACT,CAAC;CAED,UAAU,OAAO,UAAU;CAE3B,eAAe,UAAyB;EACtC,IAAI,OAAO,aAAa,KAAK;EAC7B,IAAI,eAAe,aAAa,aAAa;EAC7C,MAAM,QAAQ,IAAI,CAAC,GAAG,SAAS,OAAO,CAAC,CAAC,CAAC,KAAK,YAAY,QAAQ,MAAM,CAAC,CAAC;EAC1E,SAAS,MAAM;CACjB;CAEA,OAAO;EAAE;EAAS;EAAY;CAAQ;AACxC"}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@dialexjs/language-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.2",
4
+ "description": "Language server (LSP) for Dialex translations: diagnostics, hover, go to definition, completion and quick fixes",
5
+ "keywords": [
6
+ "dialex",
7
+ "i18n",
8
+ "language-server",
9
+ "lsp",
10
+ "zed"
11
+ ],
12
+ "homepage": "https://github.com/awaiden/dialex#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/awaiden/dialex/issues"
15
+ },
16
+ "license": "MIT",
17
+ "author": "awaiden",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/awaiden/dialex.git",
21
+ "directory": "packages/language-server"
22
+ },
23
+ "bin": {
24
+ "dialex-language-server": "./dist/index.mjs"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "type": "module",
30
+ "exports": {
31
+ ".": "./dist/index.mjs",
32
+ "./features": "./dist/features.mjs",
33
+ "./server": "./dist/server.mjs",
34
+ "./package.json": "./package.json"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "build": "vp pack",
41
+ "dev": "vp pack --watch",
42
+ "test": "vp test",
43
+ "check": "vp check"
44
+ },
45
+ "dependencies": {
46
+ "@dialexjs/cli": "0.7.2",
47
+ "vscode-languageserver": "^9.0.1",
48
+ "vscode-languageserver-textdocument": "^1.0.12"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^26.1.1",
52
+ "typescript": "^7.0.2",
53
+ "vite-plus": "1.1.0",
54
+ "vscode-jsonrpc": "^8.2.0"
55
+ }
56
+ }