/
MessageProcessor.js
480 lines (435 loc) · 12.4 KB
/
MessageProcessor.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
/**
* Copyright (c) Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Diagnostic, Uri} from 'graphql-language-service-types';
import {findGraphQLConfigDir} from 'graphql-language-service-config';
import {
getOutline,
GraphQLLanguageService,
} from 'graphql-language-service-interface';
import {Position} from 'graphql-language-service-utils';
import path from 'path';
import {getGraphQLCache} from './GraphQLCache';
// Response message error codes
const ERROR_CODES = {
PARSE_ERROR: -32700,
INVALID_REQUEST: -32600,
METHOD_NOT_FOUND: -32601,
INVALID_PARAMS: -32602,
INTERNAL_ERROR: -32603,
SERVER_ERROR_START: -32099,
SERVER_ERROR_END: -32000,
SERVER_NOT_INITIALIZED: -32002,
UNKNOWN_ERROR_CODE: -32001,
};
type RequestMessage = {
jsonrpc: string,
id: number | string,
method: string,
params?: any,
};
type ResponseMessage = {
jsonrpc: string,
id: number | string,
result?: any,
error?: ResponseError<any>,
};
type ResponseError<D> = {
code: number,
message: string,
data?: D,
};
type NotificationMessage = {
jsonrpc: string,
method: string,
params?: any,
};
type ServerCapabilities = {
capabilities: {
completionProvider: Object,
textDocumentSync: Object | number,
},
};
const REQUEST_IDS_IN_PROGRESS = [];
let graphQLCache;
let languageService;
const textDocumentCache: Map<string, Object> = new Map();
export async function processIPCNotificationMessage(
message: NotificationMessage,
): Promise<void> {
const method = message.method;
let response;
let textDocument;
switch (method) {
case 'textDocument/didOpen':
case 'textDocument/didSave':
if (!message.params || !message.params.textDocument) {
// `textDocument` is required.
return;
}
textDocument = message.params.textDocument;
const uri = textDocument.uri;
let text = textDocument.text;
// Create/modify the cached entry if text is provided.
// Otherwise, try searching the cache to perform diagnostics.
if (text) {
invalidateCache(textDocument, {text});
} else {
if (textDocumentCache.has(uri)) {
const cachedDocument = textDocumentCache.get(uri);
if (cachedDocument) {
text = cachedDocument.content.text;
}
}
}
const diagnostics = await provideDiagnosticsMessage(text, uri);
response = convertToRpcMessage({
method: 'textDocument/publishDiagnostics',
params: {uri, diagnostics},
});
sendMessageIPC(response);
break;
case 'textDocument/didChange':
// TODO: support onEdit diagnostics
// For every `textDocument/didChange` event, keep a cache of textDocuments
// with version information up-to-date, so that the textDocument contents
// may be used during performing language service features,
// e.g. autocompletions.
if (
!message.params ||
!message.params.textDocument ||
!message.params.contentChanges
) {
// `textDocument` and `contentChanges` are required.
return;
}
textDocument = message.params.textDocument;
const contentChanges = message.params.contentChanges;
// As `contentChanges` is an array and we just want the
// latest update to the text, grab the last entry from the array.
invalidateCache(textDocument, contentChanges[contentChanges.length - 1]);
break;
case 'textDocument/didClose':
// For every `textDocument/didClose` event, delete the cached entry.
// This is to keep a low memory usage && switch the source of truth to
// the file on disk.
if (!message.params || !message.params.textDocument) {
// `textDocument` is required.
return;
}
textDocument = message.params.textDocument;
if (textDocumentCache.has(textDocument.uri)) {
textDocumentCache.delete(textDocument.uri);
}
break;
case 'exit':
process.exit(0);
break;
}
}
export async function processIPCRequestMessage(
message: RequestMessage,
configDir: ?string,
): Promise<void> {
const method = message.method;
let response;
let textDocument;
let cachedDocument;
let query;
let result;
switch (method) {
case 'initialize':
if (!message.params || !message.params.rootPath) {
// `rootPath` is required
return;
}
const serverCapabilities = await initialize(
configDir ? configDir.trim() : message.params.rootPath,
);
if (serverCapabilities === null) {
response = convertToRpcMessage({
id: '-1',
error: {
code: ERROR_CODES.SERVER_NOT_INITIALIZED,
message: '.graphqlrc not found',
},
});
} else {
response = convertToRpcMessage({
id: message.id,
result: serverCapabilities,
});
}
sendMessageIPC(response);
break;
case 'textDocument/completion':
// `textDocument/comletion` event takes advantage of the fact that
// `textDocument/didChange` event always fires before, which would have
// updated the cache with the query text from the editor.
// Treat the computed list always complete.
// (response: Array<CompletionItem>)
if (
!message.params ||
!message.params.textDocument ||
!message.params.position
) {
// `textDocument` is required.
return;
}
textDocument = message.params.textDocument;
const position = message.params.position;
cachedDocument = getCachedDocument(textDocument.uri);
if (!cachedDocument) {
// `cachedDocument` is required.
return;
}
query = cachedDocument.content.text;
result = await languageService.getAutocompleteSuggestions(
query,
position,
textDocument.uri,
);
sendMessageIPC(convertToRpcMessage({
id: message.id,
result,
}));
break;
case 'textDocument/definition':
if (
!message.params ||
!message.params.textDocument ||
!message.params.position
) {
// `textDocument` is required.
return;
}
textDocument = message.params.textDocument;
const pos = message.params.position;
cachedDocument = getCachedDocument(textDocument.uri);
if (!cachedDocument) {
// `cachedDocument` is required.
return;
}
query = cachedDocument.content.text;
result = await languageService.getDefinition(
query,
pos,
textDocument.uri,
);
const formatted = result ? result.definitions.map(res => ({
uri: path.join('file://', res.path),
range: res.range,
})) : [];
sendMessageIPC(convertToRpcMessage({
id: message.id,
result: formatted,
}));
break;
case '$/cancelRequest':
if (!message.params || !message.params.id) {
// `id` is required.
return;
}
const requestIDToCancel = message.params.id;
const index = REQUEST_IDS_IN_PROGRESS.indexOf(requestIDToCancel);
if (index !== -1) {
REQUEST_IDS_IN_PROGRESS.splice(index, 1);
// A cancelled request still needs to send an empty response back
sendMessageIPC({id: requestIDToCancel});
}
break;
case 'shutdown':
// prepare to shut down the server
break;
}
}
export async function processStreamMessage(
message: string,
configDir: ?string,
): Promise<void> {
if (message.length === 0) {
return;
}
if (!graphQLCache) {
const graphQLConfigDir = findGraphQLConfigDir(
configDir ? configDir.trim() : process.cwd(),
);
if (!graphQLConfigDir) {
process.stdout.write(JSON.stringify(
convertToRpcMessage({
id: '-1',
error: {
code: ERROR_CODES.SERVER_NOT_INITIALIZED,
message: '.graphqlrc not found',
},
}),
));
return;
}
graphQLCache = await getGraphQLCache(graphQLConfigDir);
}
if (!languageService) {
languageService = new GraphQLLanguageService(graphQLCache);
}
let json;
try {
json = JSON.parse(message);
} catch (error) {
process.stdout.write(JSON.stringify(
convertToRpcMessage({
id: '-1',
error: {
code: ERROR_CODES.PARSE_ERROR,
message: 'Request contains incorrect JSON format',
},
}),
));
return;
}
const id = json.id;
const method = json.method;
let result = null;
let responseMsg = null;
const {query, filePath, position} = json.args;
switch (method) {
case 'disconnect':
process.exit(0);
break;
case 'getDiagnostics':
result = await provideDiagnosticsMessage(query, filePath);
responseMsg = convertToRpcMessage({
type: 'response',
id,
result,
});
process.stdout.write(JSON.stringify(responseMsg) + '\n');
break;
case 'getDefinition':
result = await languageService.getDefinition(query, position, filePath);
responseMsg = convertToRpcMessage({
type: 'response',
id,
result,
});
process.stdout.write(JSON.stringify(responseMsg) + '\n');
break;
case 'getAutocompleteSuggestions':
result = await languageService.getAutocompleteSuggestions(
query,
position,
filePath,
);
const formatted = result.map(
res => ({
text: res.label,
typeName: res.detail ? String(res.detail) : null,
description: res.documentation || null,
}),
);
responseMsg = convertToRpcMessage({
type: 'response',
id,
formatted,
});
process.stdout.write(JSON.stringify(responseMsg) + '\n');
break;
case 'getOutline':
result = getOutline(query);
responseMsg = convertToRpcMessage({
type: 'response',
id,
result,
});
process.stdout.write(JSON.stringify(responseMsg) + '\n');
break;
default:
break;
}
}
/**
* Helper functions to perform requested services from client/server.
*/
async function initialize(
rootPath: Uri,
): Promise<?ServerCapabilities> {
const serverCapabilities = {
capabilities: {
completionProvider: {resolveProvider: true},
definitionProvider: true,
textDocumentSync: 1,
},
};
const configDir = findGraphQLConfigDir(rootPath);
if (!configDir) {
return null;
}
graphQLCache = await getGraphQLCache(configDir);
languageService = new GraphQLLanguageService(graphQLCache);
return serverCapabilities;
}
async function provideDiagnosticsMessage(
query: string,
uri: Uri,
): Promise<Array<Diagnostic>> {
let results = await languageService.getDiagnostics(query, uri);
if (results && results.length > 0) {
const queryLines = query.split('\n');
const totalLines = queryLines.length;
const lastLineLength = queryLines[totalLines - 1].length;
const lastCharacterPosition = new Position(totalLines, lastLineLength);
results = results.filter(diagnostic =>
diagnostic.range.end.lessThanOrEqualTo(lastCharacterPosition),
);
}
return results;
}
function sendMessageIPC(message: any): void {
if (process.send !== undefined) {
process.send(message);
}
}
/**
* Composes a language server protocol JSON message.
*/
function convertToRpcMessage(metaMessage: Object): ResponseMessage {
const message: ResponseMessage = {
jsonrpc: '2.0',
protocol: 'graphql_language_service',
...metaMessage,
};
return message;
}
function invalidateCache(textDocument: Object, content: Object): void {
const uri = textDocument.uri;
if (textDocumentCache.has(uri)) {
const cachedDocument = textDocumentCache.get(uri);
if (cachedDocument && cachedDocument.version < textDocument.version) {
// Current server capabilities specify the full sync of the contents.
// Therefore always overwrite the entire content.
textDocumentCache.set(uri, {
version: textDocument.version,
content,
});
}
} else {
textDocumentCache.set(uri, {
version: textDocument.version,
content,
});
}
}
function getCachedDocument(uri: string): ?Object {
if (textDocumentCache.has(uri)) {
const cachedDocument = textDocumentCache.get(uri);
if (cachedDocument) {
return cachedDocument;
}
}
return null;
}