-
Notifications
You must be signed in to change notification settings - Fork 45
/
server.ts
259 lines (215 loc) · 8.31 KB
/
server.ts
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
'use strict';
import * as path from 'path';
import * as semver from 'semver';
import {
BulkRegistration, CompletionItem, CompletionRequest,
createConnection, Definition,
DefinitionRequest, DidChangeTextDocumentNotification, DidCloseTextDocumentNotification,
DidOpenTextDocumentNotification, Hover,
HoverRequest, IConnection, InitializeResult,
IPCMessageReader, IPCMessageWriter,
Location, NotificationType,
ReferencesRequest,
ResponseError,
TextDocumentPositionParams,
TextDocumentRegistrationOptions,
TextDocuments,
TextDocumentSyncKind,
} from 'vscode-languageserver';
import {
commonNotifications,
filePathToURI,
makeDiagnostic,
mapLocation,
resolveModule,
toGQLPosition,
uriToFilePath,
} from './helpers';
const moduleName = '@playlyfe/gql';
// Create a connection for the server. The connection uses Node's IPC as a transport
const connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process));
// Create a simple text document manager. The text document manager
// supports full document sync only
const documents: TextDocuments = new TextDocuments();
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Define server notifications to be sent to the client
const serverInitialized = new NotificationType(commonNotifications.serverInitialized);
const serverExited = new NotificationType(commonNotifications.serverExited);
// After the server has started the client sends an initilize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilites.
let gqlService;
connection.onInitialize((params): PromiseLike<InitializeResult> => {
const initOptions: { nodePath: string, debug: boolean } = params.initializationOptions;
const workspaceRoot = params.rootPath;
const nodePath = toAbsolutePath(initOptions.nodePath || '', workspaceRoot);
const debug = initOptions.debug;
return (
resolveModule(moduleName, nodePath, trace) // loading gql from project
.then((gqlModule): PromiseLike<InitializeResult> | InitializeResult => {
if (!semver.satisfies(gqlModule.version, '2.x')) {
connection.sendNotification(serverExited);
return Promise.reject<InitializeResult>(
new ResponseError(
0,
'Plugin requires `@playlyfe/gql v2.x`. Please upgrade the `@playlyfe/gql` package and restart vscode.',
),
);
}
gqlService = createGQLService(gqlModule, workspaceRoot, debug);
const result: InitializeResult = {
capabilities: {}, // see registerLanguages
};
return result;
})
);
});
connection.onInitialized(() => {
registerLanguages(gqlService.getFileExtensions());
});
connection.onExit(() => {
connection.sendNotification(serverExited);
});
function registerLanguages(extensions: string[]) {
// tslint:disable-next-line no-console
console.info('[vscode] File extensions registered: ', extensions);
const registration = BulkRegistration.create();
const documentOptions: TextDocumentRegistrationOptions = {
documentSelector: [{
scheme: 'file',
pattern: `**/*.{${extensions.join(',')}}`,
}],
};
registration.add(DidOpenTextDocumentNotification.type, documentOptions);
registration.add(DidChangeTextDocumentNotification.type, {
documentSelector: documentOptions.documentSelector,
syncKind: TextDocumentSyncKind.Full,
});
registration.add(DidCloseTextDocumentNotification.type, documentOptions);
registration.add(CompletionRequest.type, documentOptions);
registration.add(HoverRequest.type, documentOptions);
registration.add(DefinitionRequest.type, documentOptions);
registration.add(ReferencesRequest.type, documentOptions);
connection.client.register(registration);
}
function toAbsolutePath(nodePath, workspaceRoot) {
if (!path.isAbsolute(nodePath)) {
return path.join(workspaceRoot, nodePath);
}
return nodePath;
}
function trace(message: string): void {
// tslint:disable-next-line no-console
connection.console.info(message);
}
function createGQLService(gqlModule, workspaceRoot, debug) {
let lastSendDiagnostics = [];
let hasNotifiedClient = false;
return new gqlModule.GQLService({
cwd: workspaceRoot,
debug,
onChange() {
// @todo: move this it an `onInit()` function when implemented in @playlyfe/gql
if (gqlService._isInitialized && !hasNotifiedClient) {
hasNotifiedClient = true;
connection.sendNotification(serverInitialized);
}
const errors = gqlService.status();
const SCHEMA_FILE = '__schema__';
const diagnosticsMap = {};
errors.map((error) => {
const { locations } = error;
if (!locations) {
// global error will be grouped under __schema__
if (!diagnosticsMap[SCHEMA_FILE]) {
diagnosticsMap[SCHEMA_FILE] = {
uri: SCHEMA_FILE,
diagnostics: [],
};
}
diagnosticsMap[SCHEMA_FILE].diagnostics.push(makeDiagnostic(error, { line: 1, column: 1 }));
} else {
locations.forEach((loc) => {
if (!diagnosticsMap[loc.path]) {
diagnosticsMap[loc.path] = {
uri: filePathToURI(loc.path),
diagnostics: [],
};
}
diagnosticsMap[loc.path].diagnostics.push(makeDiagnostic(error, loc));
});
}
});
const sendDiagnostics = [];
// report new errors
Object.keys(diagnosticsMap).forEach((file) => {
sendDiagnostics.push({file, diagnostic: diagnosticsMap[file]});
connection.sendDiagnostics(diagnosticsMap[file]);
});
// clear old errors
lastSendDiagnostics.forEach(({file, diagnostic}) => {
if (diagnosticsMap[file]) { return; } // already reported error above
connection.sendDiagnostics({uri: diagnostic.uri, diagnostics: [] });
});
lastSendDiagnostics = sendDiagnostics;
},
});
}
connection.onDefinition((textDocumentPosition: TextDocumentPositionParams, token): Definition => {
if (token.isCancellationRequested) { return; }
const defLocation = gqlService.getDef({
sourceText: documents.get(textDocumentPosition.textDocument.uri).getText(),
sourcePath: uriToFilePath(textDocumentPosition.textDocument.uri),
position: toGQLPosition(textDocumentPosition.position),
});
if (defLocation) { return mapLocation(defLocation); }
});
// show symbol info onHover
connection.onHover((textDocumentPosition: TextDocumentPositionParams, token): Hover => {
if (token.isCancellationRequested) { return; }
const info = gqlService.getInfo({
sourceText: documents.get(textDocumentPosition.textDocument.uri).getText(),
sourcePath: uriToFilePath(textDocumentPosition.textDocument.uri),
position: toGQLPosition(textDocumentPosition.position),
});
if (info) {
return {
contents: info.contents.map((content) => ({
language: 'graphql',
value: content,
})),
};
}
});
// This handler provides the initial list of the completion items.
connection.onCompletion((textDocumentPosition: TextDocumentPositionParams, token): CompletionItem[] => {
if (token.isCancellationRequested) { return; }
const results = gqlService.autocomplete({
sourceText: documents.get(textDocumentPosition.textDocument.uri).getText(),
sourcePath: uriToFilePath(textDocumentPosition.textDocument.uri),
position: toGQLPosition(textDocumentPosition.position),
});
return results.map(({ text, type, description }) => ({
label: text,
detail: type,
documentation: description,
}));
});
// This handler resolve additional information for the item selected in
// the completion list.
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
return item;
});
// Find all references
connection.onReferences((textDocumentPosition: TextDocumentPositionParams, token): Location[] => {
if (token.isCancellationRequested) { return; }
const refLocations = gqlService.findRefs({
sourceText: documents.get(textDocumentPosition.textDocument.uri).getText(),
sourcePath: uriToFilePath(textDocumentPosition.textDocument.uri),
position: toGQLPosition(textDocumentPosition.position),
});
return refLocations.map(mapLocation);
});
// Listen on the connection
connection.listen();