-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
json-server.ts
269 lines (242 loc) · 10.3 KB
/
json-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
260
261
262
263
264
265
266
267
268
269
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2018 TypeFox GmbH (http://www.typefox.io). All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as fs from "fs";
import { xhr, getErrorStatusDescription } from 'request-light';
import { URI } from 'vscode-uri';
import { MessageReader, MessageWriter } from "vscode-jsonrpc";
import { IConnection, TextDocuments, DocumentSymbolParams, createConnection } from 'vscode-languageserver';
import {
TextDocument, Diagnostic, Command, CompletionList, CompletionItem, Hover,
SymbolInformation, TextEdit, FoldingRange, ColorInformation, ColorPresentation
} from "vscode-languageserver-types";
import { TextDocumentPositionParams, DocumentRangeFormattingParams, ExecuteCommandParams, CodeActionParams, FoldingRangeRequestParam, DocumentColorParams, ColorPresentationParams, TextDocumentSyncKind } from 'vscode-languageserver-protocol';
import { getLanguageService, LanguageService, JSONDocument } from "vscode-json-languageservice";
import * as TextDocumentImpl from "vscode-languageserver-textdocument";
export function start(reader: MessageReader, writer: MessageWriter): JsonServer {
const connection = createConnection(reader, writer);
const server = new JsonServer(connection);
server.start();
return server;
}
export class JsonServer {
protected workspaceRoot: URI | undefined;
protected readonly documents = new TextDocuments(TextDocumentImpl.TextDocument);
protected readonly jsonService: LanguageService = getLanguageService({
schemaRequestService: this.resolveSchema.bind(this)
});
protected readonly pendingValidationRequests = new Map<string, number>();
constructor(
protected readonly connection: IConnection
) {
this.documents.listen(this.connection);
this.documents.onDidChangeContent(change =>
this.validate(change.document)
);
this.documents.onDidClose(event => {
this.cleanPendingValidation(event.document);
this.cleanDiagnostics(event.document);
});
this.connection.onInitialize(params => {
if (params.rootPath) {
this.workspaceRoot = URI.file(params.rootPath);
} else if (params.rootUri) {
this.workspaceRoot = URI.parse(params.rootUri);
}
this.connection.console.log("The server is initialized.");
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Incremental,
codeActionProvider: true,
completionProvider: {
resolveProvider: true,
triggerCharacters: ['"', ':']
},
hoverProvider: true,
documentSymbolProvider: true,
documentRangeFormattingProvider: true,
executeCommandProvider: {
commands: ['json.documentUpper']
},
colorProvider: true,
foldingRangeProvider: true
}
}
});
this.connection.onCodeAction(params =>
this.codeAction(params)
);
this.connection.onCompletion(params =>
this.completion(params)
);
this.connection.onCompletionResolve(item =>
this.resolveCompletion(item)
);
this.connection.onExecuteCommand(params =>
this.executeCommand(params)
);
this.connection.onHover(params =>
this.hover(params)
)
this.connection.onDocumentSymbol(params =>
this.findDocumentSymbols(params)
);
this.connection.onDocumentRangeFormatting(params =>
this.format(params)
);
this.connection.onDocumentColor(params =>
this.findDocumentColors(params)
);
this.connection.onColorPresentation(params =>
this.getColorPresentations(params)
);
this.connection.onFoldingRanges(params =>
this.getFoldingRanges(params)
);
}
start() {
this.connection.listen();
}
protected getFoldingRanges(params: FoldingRangeRequestParam): FoldingRange[] {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return [];
}
return this.jsonService.getFoldingRanges(document);
}
protected findDocumentColors(params: DocumentColorParams): Thenable<ColorInformation[]> {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return Promise.resolve([]);
}
const jsonDocument = this.getJSONDocument(document);
return this.jsonService.findDocumentColors(document, jsonDocument);
}
protected getColorPresentations(params: ColorPresentationParams): ColorPresentation[] {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return [];
}
const jsonDocument = this.getJSONDocument(document);
return this.jsonService.getColorPresentations(document, jsonDocument, params.color, params.range);
}
protected codeAction(params: CodeActionParams): Command[] {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return [];
}
return [{
title: "Upper Case Document",
command: "json.documentUpper",
// Send a VersionedTextDocumentIdentifier
arguments: [{
...params.textDocument,
version: document.version
}]
}];
}
protected format(params: DocumentRangeFormattingParams): TextEdit[] {
const document = this.documents.get(params.textDocument.uri);
return document ? this.jsonService.format(document, params.range, params.options) : [];
}
protected findDocumentSymbols(params: DocumentSymbolParams): SymbolInformation[] {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return [];
}
const jsonDocument = this.getJSONDocument(document);
return this.jsonService.findDocumentSymbols(document, jsonDocument);
}
protected executeCommand(params: ExecuteCommandParams): any {
if (params.command === "json.documentUpper" && params.arguments) {
const versionedTextDocumentIdentifier = params.arguments[0];
const document = this.documents.get(versionedTextDocumentIdentifier.uri);
if (document) {
this.connection.workspace.applyEdit({
documentChanges: [{
textDocument: versionedTextDocumentIdentifier,
edits: [{
range: {
start: { line: 0, character: 0 },
end: { line: Number.MAX_SAFE_INTEGER, character: Number.MAX_SAFE_INTEGER }
},
newText: document.getText().toUpperCase()
}]
}]
});
}
}
}
protected hover(params: TextDocumentPositionParams): Thenable<Hover | null> {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return Promise.resolve(null);
}
const jsonDocument = this.getJSONDocument(document);
return this.jsonService.doHover(document, params.position, jsonDocument);
}
protected async resolveSchema(url: string): Promise<string> {
const uri = URI.parse(url);
if (uri.scheme === 'file') {
return new Promise<string>((resolve, reject) => {
fs.readFile(uri.fsPath, 'UTF-8', (err, result) => {
err ? reject('') : resolve(result.toString());
});
});
}
try {
const response = await xhr({ url, followRedirects: 5 });
return response.responseText;
}
catch (error) {
return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString());
}
}
protected resolveCompletion(item: CompletionItem): Thenable<CompletionItem> {
return this.jsonService.doResolve(item);
}
protected completion(params: TextDocumentPositionParams): Thenable<CompletionList | null> {
const document = this.documents.get(params.textDocument.uri);
if (!document) {
return Promise.resolve(null);
}
const jsonDocument = this.getJSONDocument(document);
return this.jsonService.doComplete(document, params.position, jsonDocument);
}
protected validate(document: TextDocument): void {
this.cleanPendingValidation(document);
this.pendingValidationRequests.set(document.uri, setTimeout(() => {
this.pendingValidationRequests.delete(document.uri);
this.doValidate(document);
}));
}
protected cleanPendingValidation(document: TextDocument): void {
const request = this.pendingValidationRequests.get(document.uri);
if (request !== undefined) {
clearTimeout(request);
this.pendingValidationRequests.delete(document.uri);
}
}
protected doValidate(document: TextDocument): void {
if (document.getText().length === 0) {
this.cleanDiagnostics(document);
return;
}
const jsonDocument = this.getJSONDocument(document);
this.jsonService.doValidation(document, jsonDocument).then(diagnostics =>
this.sendDiagnostics(document, diagnostics)
);
}
protected cleanDiagnostics(document: TextDocument): void {
this.sendDiagnostics(document, []);
}
protected sendDiagnostics(document: TextDocument, diagnostics: Diagnostic[]): void {
this.connection.sendDiagnostics({
uri: document.uri, diagnostics
});
}
protected getJSONDocument(document: TextDocument): JSONDocument {
return this.jsonService.parseJSONDocument(document);
}
}