-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
483 lines (425 loc) · 13.3 KB
/
index.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/**
* @typedef {import('unist').Point} Point
* @typedef {import('unist').Position} UnistPosition
* @typedef {import('vfile-message').VFileMessage} VFileMessage
* @typedef {import('vscode-languageserver').Connection} Connection
* @typedef {import('unified-engine').Options} EngineOptions
* @typedef {Pick<
* EngineOptions,
* | 'ignoreName'
* | 'packageField'
* | 'pluginPrefix'
* | 'plugins'
* | 'rcName'
* >} EngineFields
*
* @typedef LanguageServerFields
* @property {string} processorName
* The package ID of the expected processor (example: `'remark'`).
* Will be loaded from the local workspace.
* @property {string} [processorSpecifier='default']
* The specifier to get the processor on the resolved module.
* For example, remark uses the specifier `remark` to expose its processor and
* a default export can be requested by passing `'default'` (the default).
* @property {EngineOptions['processor']} [defaultProcessor]
* Optional fallback processor to use if `processorName` can’t be found
* locally in `node_modules`.
* This can be used to ship a processor with your package, to be used if no
* processor is found locally.
* If this isn’t passed, a warning is shown if `processorName` can’t be found.
*
* @typedef {EngineFields & LanguageServerFields} Options
*/
import path from 'node:path'
import process from 'node:process'
import {PassThrough} from 'node:stream'
import {URL, pathToFileURL, fileURLToPath} from 'node:url'
import {loadPlugin} from 'load-plugin'
import {engine} from 'unified-engine'
import {VFile} from 'vfile'
import {
createConnection,
CodeAction,
CodeActionKind,
Diagnostic,
DiagnosticSeverity,
Position,
ProposedFeatures,
Range,
TextDocuments,
TextDocumentSyncKind,
TextEdit
} from 'vscode-languageserver/node.js'
import {TextDocument} from 'vscode-languageserver-textdocument'
/**
* Convert a unist point to a language server protocol position.
*
* @param {Point} point
* @returns {Position}
*/
function unistPointToLspPosition(point) {
return Position.create(point.line - 1, point.column - 1)
}
/**
* @param {Point|null|undefined} point
* @returns {boolean}
*/
function isValidUnistPoint(point) {
return Boolean(
point && Number.isInteger(point.line) && Number.isInteger(point.column)
)
}
/**
* Convert a unist position to a language server protocol range.
*
* If no position is given, a range is returned which represents the beginning
* of the document.
*
* @param {UnistPosition|null|undefined} position
* @returns {Range}
*/
function unistLocationToLspRange(position) {
if (position) {
const end = isValidUnistPoint(position.end)
? unistPointToLspPosition(position.end)
: undefined
const start = isValidUnistPoint(position.start)
? unistPointToLspPosition(position.start)
: end
if (start) {
return Range.create(start, end || start)
}
}
return Range.create(0, 0, 0, 0)
}
/**
* Convert a vfile message to a language server protocol diagnostic.
*
* @param {VFileMessage} message
* @returns {Diagnostic}
*/
function vfileMessageToDiagnostic(message) {
const diagnostic = Diagnostic.create(
unistLocationToLspRange(message.position),
String(message.stack || message.reason),
message.fatal === true
? DiagnosticSeverity.Error
: message.fatal === false
? DiagnosticSeverity.Warning
: DiagnosticSeverity.Information,
message.ruleId || undefined,
message.source || undefined
)
if (message.url) {
diagnostic.codeDescription = {href: message.url}
}
if (message.expected) {
diagnostic.data = {
expected: message.expected
}
}
if (message.note) {
diagnostic.message += '\n' + message.note
}
return diagnostic
}
/**
* Convert language server protocol text document to a vfile.
*
* @param {TextDocument} document
* @returns {VFile}
*/
function lspDocumentToVfile(document) {
return new VFile({path: new URL(document.uri), value: document.getText()})
}
/**
* @param {Connection} connection
* @param {TextDocuments<TextDocument>} documents
* @param {Options} options
*/
export function configureUnifiedLanguageServer(
connection,
documents,
{
ignoreName,
packageField,
pluginPrefix,
plugins,
processorName,
processorSpecifier = 'default',
defaultProcessor,
rcName
}
) {
/** @type {Set<string>} */
const workspaces = new Set()
let hasWorkspaceFolderCapability = false
/**
* Process various LSP text documents using unified and send back the
* resulting messages as diagnostics.
*
* @param {TextDocument[]} textDocuments
* @param {boolean} alwaysStringify
* @returns {Promise<VFile[]>}
*/
async function processDocuments(textDocuments, alwaysStringify = false) {
// LSP uses `file:` URLs (hrefs), `unified-engine` expects a paths.
// `process.cwd()` does not add a final slash, but `file:` URLs often do.
const workspacesAsPaths = [...workspaces].map((d) =>
fileURLToPath(d.replace(/\/$/, ''))
)
/** @type {Map<string, Array<VFile>>} */
const workspacePathToFiles = new Map()
if (workspacesAsPaths.length === 0) {
workspacesAsPaths.push(process.cwd())
}
for (const textDocument of textDocuments) {
const file = lspDocumentToVfile(textDocument)
const [cwd] = workspacesAsPaths
// Every workspace that includes the document.
.filter((d) => file.path.slice(0, d.length + 1) === d + path.sep)
// Sort the longest (closest to the file) first.
.sort((a, b) => b.length - a.length)
// This presumably should not occur: a file outside a workspace.
// So ignore the file.
/* c8 ignore next */
if (!cwd) continue
const files = workspacePathToFiles.get(cwd) || []
workspacePathToFiles.set(cwd, [...files, file])
}
/** @type {Array<Promise<Array<VFile>>>} */
const promises = []
for (const [cwd, files] of workspacePathToFiles) {
promises.push(
(async function () {
/** @type {EngineOptions['processor']} */
let processor
try {
// @ts-expect-error: assume we load a unified processor.
processor = await loadPlugin(processorName, {
cwd,
key: processorSpecifier
})
} catch (error) {
const exception = /** @type {NodeJS.ErrnoException} */ (error)
// Pass other funky errors through.
/* c8 ignore next 3 */
if (exception.code !== 'ERR_MODULE_NOT_FOUND') {
throw error
}
if (!defaultProcessor) {
connection.window.showInformationMessage(
'Cannot turn on language server without `' +
processorName +
'` locally. Run `npm install ' +
processorName +
'` to enable it'
)
return []
}
connection.console.log(
'Cannot find `' +
processorName +
'` locally but using `defaultProcessor`, original error:\n' +
exception.stack
)
processor = defaultProcessor
}
return new Promise((resolve, reject) => {
engine(
{
alwaysStringify,
cwd,
files,
ignoreName,
packageField,
pluginPrefix,
plugins,
processor,
quiet: false,
rcName,
silentlyIgnore: true,
streamError: new PassThrough(),
streamOut: new PassThrough()
},
(error, _, context) => {
// An error never occured and can’t be reproduced. This is an internal
// error in unified-engine. If a plugin throws, it’s reported as a
// vfile message.
/* c8 ignore start */
if (error) {
reject(error)
} else {
resolve((context && context.files) || [])
}
}
)
})
})()
/* c8 ignore stop */
)
}
const listsOfFiles = await Promise.all(promises)
// XXX [engine:node@>16] V8 coverage bug on Dubnium (Node 12).
/* c8 ignore next 3 */
return listsOfFiles.flat()
}
/* c8 ignore stop */
/**
* Process various LSP text documents using unified and send back the
* resulting messages as diagnostics.
*
* @param {TextDocument[]} textDocuments
*/
async function checkDocuments(...textDocuments) {
const documentVersions = new Map(
textDocuments.map((document) => [document.uri, document.version])
)
const files = await processDocuments(textDocuments)
for (const file of files) {
// VFile uses a file path, but LSP expects a file URL as a string.
const uri = String(pathToFileURL(file.path))
connection.sendDiagnostics({
uri,
version: documentVersions.get(uri),
diagnostics: file.messages.map((message) =>
vfileMessageToDiagnostic(message)
)
})
}
}
connection.onInitialize((event) => {
if (event.workspaceFolders) {
for (const workspace of event.workspaceFolders) {
workspaces.add(workspace.uri)
}
}
if (workspaces.size === 0 && event.rootUri) {
workspaces.add(event.rootUri)
}
hasWorkspaceFolderCapability = Boolean(
event.capabilities.workspace &&
event.capabilities.workspace.workspaceFolders
)
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
documentFormattingProvider: true,
codeActionProvider: {
codeActionKinds: [CodeActionKind.QuickFix],
resolveProvider: true
},
workspace: hasWorkspaceFolderCapability
? {workspaceFolders: {supported: true, changeNotifications: true}}
: undefined
}
}
})
connection.onInitialized(() => {
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders((event) => {
for (const workspace of event.removed) {
workspaces.delete(workspace.uri)
}
for (const workspace of event.added) {
workspaces.add(workspace.uri)
}
checkDocuments(...documents.all())
})
}
})
connection.onDocumentFormatting(async (event) => {
const document = documents.get(event.textDocument.uri)
// `vscode-languageserver` crashes for commands to format unopen documents.
/* c8 ignore next 3 */
if (!document) {
return
}
const [file] = await processDocuments([document], true)
const result = String(file)
const text = document.getText()
if (result === text) {
return
}
const start = Position.create(0, 0)
const end = document.positionAt(text.length)
// XXX [engine:node@>16] V8 coverage bug on Dubnium (Node 12).
/* c8 ignore next 2 */
return [TextEdit.replace(Range.create(start, end), result)]
})
documents.onDidChangeContent((event) => {
checkDocuments(event.document)
})
// Send empty diagnostics for closed files.
documents.onDidClose((event) => {
const {uri, version} = event.document
connection.sendDiagnostics({
uri,
version,
diagnostics: []
})
})
// Check everything again if the file system watched by the client changes.
connection.onDidChangeWatchedFiles(() => {
checkDocuments(...documents.all())
})
connection.onCodeAction((event) => {
/** @type {CodeAction[]} */
const codeActions = []
const document = documents.get(event.textDocument.uri)
// `vscode-languageserver` crashes for commands to act on unopen documents.
/* c8 ignore next 3 */
if (!document) {
return
}
const text = document.getText()
for (const diagnostic of event.context.diagnostics) {
const {data} = diagnostic
if (typeof data !== 'object' || !data) {
continue
}
const {expected} = /** @type {{expected?: string[]}} */ (data)
if (!Array.isArray(expected)) {
continue
}
const {end, start} = diagnostic.range
const actual = text.slice(
document.offsetAt(start),
document.offsetAt(end)
)
for (const replacement of expected) {
codeActions.push(
CodeAction.create(
replacement
? start.line === end.line && start.character === end.character
? 'Insert `' + replacement + '`'
: 'Replace `' + actual + '` with `' + replacement + '`'
: 'Remove `' + actual + '`',
{
changes: {
[document.uri]: [
TextEdit.replace(diagnostic.range, replacement)
]
}
},
CodeActionKind.QuickFix
)
)
}
}
return codeActions
})
}
/**
* Create a language server for a unified ecosystem.
*
* @param {Options} options
* Configuration for `unified-engine` and the language server.
*/
export function createUnifiedLanguageServer(options) {
const connection = createConnection(ProposedFeatures.all)
const documents = new TextDocuments(TextDocument)
configureUnifiedLanguageServer(connection, documents, options)
documents.listen(connection)
connection.listen()
}