-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
server.js
399 lines (326 loc) · 10.3 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
'use strict';
const { TextDocument } = require('vscode-languageserver-textdocument');
const { TextDocuments } = require('vscode-languageserver/node');
const { TextDocumentSyncKind } = require('vscode-languageserver-protocol');
const { getFixes } = require('../utils/documents');
const { displayError } = require('../utils/lsp');
const { deepAssign } = require('../utils/objects');
const { StylelintRunner } = require('../utils/stylelint');
const { StylelintResolver } = require('../utils/packages');
/** @type {LanguageServerOptions} */
const defaultOptions = {
packageManager: 'npm',
validate: ['css', 'less', 'postcss'],
snippet: ['css', 'less', 'postcss'],
};
/**
* Stylelint language server.
*/
class StylelintLanguageServer {
/**
* The language server connection.
* @type {lsp.Connection}
*/
#connection;
/**
* The logger to use, if any.
* @type {winston.Logger | undefined}
*/
#logger;
/**
* The language server options.
* @type {LanguageServerOptions}
*/
#options;
/**
* The resolver used to resolve the Stylelint package.
* @type {StylelintResolver}
*/
#resolver;
/**
* The runner used to run Stylelint.
* @type {StylelintRunner}
*/
#runner;
/**
* The text document manager.
* @type {lsp.TextDocuments<lsp.TextDocument>}
*/
#documents;
/**
* The language server context passed between modules.
* @type {LanguageServerContext}
*/
#context;
/**
* Registered modules.
* @type {Map<string, LanguageServerModule>}
*/
#modules = new Map();
/**
* Creates a new Stylelint language server.
* @param {LanguageServerConstructorParameters} params
*/
constructor({ connection, logger, modules }) {
this.#connection = connection;
this.#logger = logger?.child({ component: 'language-server' });
this.#options = defaultOptions;
this.#resolver = new StylelintResolver(connection, this.#logger);
this.#runner = new StylelintRunner(connection, this.#logger, this.#resolver);
this.#documents = new TextDocuments(TextDocument);
this.#context = {
connection: this.#connection,
documents: this.#documents,
options: this.#options,
runner: this.#runner,
getModule: this.#getModule.bind(this),
getFixes: this.#getFixes.bind(this),
displayError: this.#displayError.bind(this),
lintDocument: this.#lintDocument.bind(this),
resolveStylelint: this.#resolveStylelint.bind(this),
};
const contextReadOnlyProxy = new Proxy(this.#context, {
get(target, name) {
return target[/** @type {keyof typeof target} */ (name)];
},
set() {
throw new Error('Cannot set read-only property');
},
});
if (modules) {
for (const Module of modules) {
this.#logger?.info('Registering module', { module: Module.id });
if (!Module.id) {
throw new Error('Modules must have an ID');
}
if (typeof Module.id !== 'string') {
throw new Error('Module IDs must be strings');
}
const module = new Module({
context: contextReadOnlyProxy,
logger: logger?.child({ component: `language-server:${Module.id}` }),
});
if (this.#modules.has(Module.id)) {
throw new Error(`Module with ID "${Module.id}" already registered`);
}
this.#modules.set(Module.id, module);
this.#logger?.info('Module registered', { module: Module.id });
}
}
}
/**
* Starts the language server.
*/
start() {
this.#logger?.info('Starting language server');
this.#registerHandlers();
this.#documents.listen(this.#connection);
this.#connection.listen();
this.#logger?.info('Language server started');
}
/**
* @param {unknown} error
*/
#displayError(error) {
displayError(this.#connection, error);
}
/**
* Resolves the Stylelint package for the given document.
* @param {lsp.TextDocument} document
* @returns {Promise<StylelintResolutionResult | undefined>}
*/
async #resolveStylelint(document) {
this.#logger?.debug('Resolving Stylelint', { uri: document.uri });
try {
const result = await this.#resolver.resolve(this.#options, document);
if (result) {
this.#logger?.debug('Stylelint resolved', {
uri: document.uri,
resolvedPath: result.resolvedPath,
});
} else {
this.#logger?.warn('Failed to resolve Stylelint', { uri: document.uri });
}
return result;
} catch (error) {
this.#displayError(error);
this.#logger?.error('Error resolving Stylelint', { uri: document.uri, error });
return undefined;
}
}
/**
* Lints a document using Stylelint.
* @param {lsp.TextDocument} document
* @param {Partial<stylelint.LinterOptions>} [linterOptions]
* @returns {Promise<LintDiagnostics | undefined>}
*/
async #lintDocument(document, linterOptions = {}) {
this.#logger?.debug('Linting document', { uri: document.uri, linterOptions });
try {
const results = await this.#runner.lintDocument(document, linterOptions, this.#options);
this.#logger?.debug('Lint run complete', { uri: document.uri, results });
return results;
} catch (err) {
this.#displayError(err);
this.#logger?.error('Error running lint', { uri: document.uri, error: err });
return undefined;
}
}
/**
* Gets text edits for fixes made by Stylelint.
* @param {lsp.TextDocument} document
* @param {stylelint.LinterOptions} [linterOptions]
* @returns {Promise<lsp.TextEdit[]>}
*/
async #getFixes(document, linterOptions = {}) {
try {
const edits = await getFixes(this.#runner, document, linterOptions, this.#options);
this.#logger?.debug('Fixes retrieved', { uri: document.uri, edits });
return edits;
} catch (error) {
this.#displayError(error);
this.#logger?.error('Error getting fixes', { uri: document.uri, error });
return [];
}
}
/**
* Gets the registered module with the given ID if it exists.
* @param {string} id
* @returns {LanguageServerModule | undefined}
*/
#getModule(id) {
return this.#modules.get(id);
}
/**
* Sets the language server options.
* @param {ExtensionOptions} options
*/
#setOptions(options) {
/** @type {LanguageServerOptions} */
this.#options = {
config: options.config,
configBasedir: options.configBasedir,
configFile: options.configFile,
customSyntax: options.customSyntax,
ignoreDisables: options.ignoreDisables,
packageManager: options.packageManager || defaultOptions.packageManager,
reportInvalidScopeDisables: options.reportInvalidScopeDisables,
reportNeedlessDisables: options.reportNeedlessDisables,
snippet: options.snippet ?? defaultOptions.snippet,
stylelintPath: options.stylelintPath,
validate: options.validate ?? defaultOptions.validate,
};
Object.freeze(this.#options);
this.#context.options = this.#options;
this.#logger?.debug('Options updated', { options: this.#options });
}
/**
* Registers handlers on the language server connection, then invokes the
* `onDidRegisterHandlers` event for each registered module to allow them
* to register their handlers.
*/
#registerHandlers() {
this.#logger?.info('Registering handlers');
this.#connection.onInitialize(this.#onInitialize.bind(this));
this.#logger?.debug('onInitialize handler registered');
this.#connection.onDidChangeConfiguration(this.#onDidChangeConfiguration.bind(this));
this.#logger?.debug('onDidChangeConfiguration handler registered');
this.#invokeHandlers('onDidRegisterHandlers');
this.#logger?.info('Handlers registered');
}
/**
* Calls the given handler for all registered modules.
* @template {keyof LanguageServerHandlerParameters} K
* @template {LanguageServerHandlerParameters[K]} P
* @template {LanguageServerHandlerReturnValues[K]} R
* @param {K} handlerName
* @param {P} params
* @returns {{[moduleName: string]: R[]}}
*/
#invokeHandlers(handlerName, ...params) {
this.#logger?.debug(`Invoking ${handlerName}`);
/** @type {{[moduleName: string]: R[]}} */
const returnValues = Object.create(null);
for (const [id, module] of this.#modules) {
const handler = module[handlerName];
if (handler) {
try {
returnValues[id] = /** @type {(...args: P) => any} */ (handler).apply(module, params);
this.#logger?.debug(`Invoked ${handlerName}`, {
module: id,
returnValue: returnValues[id],
});
} catch (error) {
this.#displayError(error);
this.#logger?.error(`Error invoking ${handlerName}`, {
module: id,
error,
});
}
}
}
return returnValues;
}
/**
* @param {lsp.InitializeParams} params
* @returns {lsp.InitializeResult}
*/
#onInitialize(params) {
this.#logger?.debug('received onInitialize', { params });
/** @type {lsp.InitializeResult} */
const result = {
capabilities: {
textDocumentSync: {
openClose: true,
change: TextDocumentSyncKind.Full,
},
},
};
for (const [, moduleResult] of Object.entries(this.#invokeHandlers('onInitialize', params))) {
if (moduleResult) {
deepAssign(result, moduleResult);
}
}
this.#logger?.debug('Returning initialization results', { result });
return result;
}
/**
* @param {lsp.DidChangeConfigurationParams} params
* @returns {void}
*/
#onDidChangeConfiguration(params) {
this.#logger?.debug('received onDidChangeConfiguration', { params });
const oldOptions = this.#options;
this.#setOptions(params.settings.stylelint);
const validateLanguageSet = new Set(this.#options.validate);
const oldValidateLanguageSet = new Set(oldOptions.validate);
/** Whether or not the list of languages that should be validated has changed. */
let changed = validateLanguageSet.size !== oldValidateLanguageSet.size;
/** The languages removed from the list of languages that should be validated */
const removedLanguages = new Set();
// Check if the sets are unequal, which means that the list of languages that should be
// validated has changed.
for (const language of oldValidateLanguageSet) {
if (!validateLanguageSet.has(language)) {
removedLanguages.add(language);
changed = true;
}
}
if (changed) {
if (this.#logger?.isDebugEnabled()) {
this.#logger?.debug('Languages that should be validated changed', {
languages: [...validateLanguageSet],
removedLanguages: [...removedLanguages],
});
}
this.#invokeHandlers('onDidChangeValidateLanguages', {
languages: validateLanguageSet,
removedLanguages,
});
}
this.#invokeHandlers('onDidChangeConfiguration', { settings: this.#options });
}
}
module.exports = {
StylelintLanguageServer,
};