-
Notifications
You must be signed in to change notification settings - Fork 327
/
client.ts
2286 lines (2055 loc) · 93 KB
/
client.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import {
workspace as Workspace, window as Window, languages as Languages, version as VSCodeVersion, TextDocument, Disposable, OutputChannel,
FileSystemWatcher as VFileSystemWatcher, DiagnosticCollection, Diagnostic as VDiagnostic, Uri, CancellationToken, WorkspaceEdit as VWorkspaceEdit,
MessageItem, WorkspaceFolder as VWorkspaceFolder, env as Env, TextDocumentShowOptions, CancellationError, CancellationTokenSource, FileCreateEvent,
FileRenameEvent, FileDeleteEvent, FileWillCreateEvent, FileWillRenameEvent, FileWillDeleteEvent, CompletionItemProvider, HoverProvider, SignatureHelpProvider,
DefinitionProvider, ReferenceProvider, DocumentHighlightProvider, CodeActionProvider, DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider,
OnTypeFormattingEditProvider, RenameProvider, DocumentSymbolProvider, DocumentLinkProvider, DeclarationProvider, ImplementationProvider,
DocumentColorProvider, SelectionRangeProvider, TypeDefinitionProvider, CallHierarchyProvider, LinkedEditingRangeProvider, TypeHierarchyProvider, WorkspaceSymbolProvider,
ProviderResult, TextEdit as VTextEdit, InlineCompletionItemProvider
} from 'vscode';
import {
RAL, Message, MessageSignature, Logger, ResponseError, RequestType0, RequestType, NotificationType0, NotificationType,
ProtocolRequestType, ProtocolRequestType0, RequestHandler, RequestHandler0, GenericRequestHandler,
ProtocolNotificationType, ProtocolNotificationType0, NotificationHandler, NotificationHandler0, GenericNotificationHandler,
MessageReader, MessageWriter, Trace, Tracer, TraceFormat, TraceOptions, Event, Emitter, createProtocolConnection,
ClientCapabilities, WorkspaceEdit, RegistrationRequest, RegistrationParams, UnregistrationRequest, UnregistrationParams,
InitializeRequest, InitializeParams, InitializeResult, ServerCapabilities, TextDocumentSyncKind, TextDocumentSyncOptions,
InitializedNotification, ShutdownRequest, ExitNotification, LogMessageNotification, MessageType, ShowMessageNotification,
ShowMessageRequest, TelemetryEventNotification, DocumentSelector, DidChangeTextDocumentNotification,
DidChangeWatchedFilesNotification, FileEvent, PublishDiagnosticsNotification, PublishDiagnosticsParams, ApplyWorkspaceEditRequest,
ApplyWorkspaceEditParams, TextDocumentEdit, ResourceOperationKind, FailureHandlingKind, ProgressType, ProgressToken, DiagnosticTag,
LSPErrorCodes, ShowDocumentRequest, ShowDocumentParams, ShowDocumentResult, WorkDoneProgress, SemanticTokensRequest,
SemanticTokensRangeRequest, SemanticTokensDeltaRequest, Diagnostic, ApplyWorkspaceEditResult, CancellationStrategy, InitializeError, WorkDoneProgressBegin,
WorkDoneProgressReport, WorkDoneProgressEnd, DidOpenTextDocumentNotification, WillSaveTextDocumentNotification, WillSaveTextDocumentWaitUntilRequest,
DidSaveTextDocumentNotification, DidCloseTextDocumentNotification, DidCreateFilesNotification, DidRenameFilesNotification, DidDeleteFilesNotification,
WillRenameFilesRequest, WillCreateFilesRequest, WillDeleteFilesRequest, CompletionRequest, HoverRequest, SignatureHelpRequest, DefinitionRequest,
ReferencesRequest, DocumentHighlightRequest, CodeActionRequest, CodeLensRequest, DocumentFormattingRequest, DocumentRangeFormattingRequest,
DocumentOnTypeFormattingRequest, RenameRequest, DocumentSymbolRequest, DocumentLinkRequest, DocumentColorRequest, DeclarationRequest, FoldingRangeRequest,
ImplementationRequest, SelectionRangeRequest, TypeDefinitionRequest, CallHierarchyPrepareRequest, SemanticTokensRegistrationType, LinkedEditingRangeRequest,
TypeHierarchyPrepareRequest, InlineValueRequest, InlayHintRequest, WorkspaceSymbolRequest, TextDocumentRegistrationOptions, FileOperationRegistrationOptions,
ConnectionOptions, PositionEncodingKind, DocumentDiagnosticRequest, NotebookDocumentSyncRegistrationType, NotebookDocumentSyncRegistrationOptions, ErrorCodes,
MessageStrategy, DidOpenTextDocumentParams, CodeLensResolveRequest, CompletionResolveRequest, CodeActionResolveRequest, InlayHintResolveRequest, DocumentLinkResolveRequest, WorkspaceSymbolResolveRequest,
CancellationToken as ProtocolCancellationToken, InlineCompletionRequest, InlineCompletionRegistrationOptions, ExecuteCommandRequest, ExecuteCommandOptions, HandlerResult
} from 'vscode-languageserver-protocol';
import * as c2p from './codeConverter';
import * as p2c from './protocolConverter';
import * as Is from './utils/is';
import { Delayer, Semaphore } from './utils/async';
import * as UUID from './utils/uuid';
import { ProgressPart } from './progressPart';
import {
DynamicFeature, ensure, FeatureClient, LSPCancellationError, TextDocumentSendFeature, RegistrationData, StaticFeature,
TextDocumentProviderFeature, WorkspaceProviderFeature
} from './features';
import { DiagnosticFeature, DiagnosticProviderMiddleware, DiagnosticProviderShape, $DiagnosticPullOptions, DiagnosticFeatureShape } from './diagnostic';
import { NotebookDocumentMiddleware, $NotebookDocumentOptions, NotebookDocumentProviderShape, NotebookDocumentSyncFeature } from './notebook';
import {
ConfigurationFeature, ConfigurationMiddleware, $ConfigurationOptions, DidChangeConfigurationMiddleware, SyncConfigurationFeature,
SynchronizeOptions
} from './configuration';
import {
DidChangeTextDocumentFeature, DidChangeTextDocumentFeatureShape, DidCloseTextDocumentFeature, DidCloseTextDocumentFeatureShape, DidOpenTextDocumentFeature,
DidOpenTextDocumentFeatureShape, DidSaveTextDocumentFeature, DidSaveTextDocumentFeatureShape, ResolvedTextDocumentSyncCapabilities, TextDocumentSynchronizationMiddleware, WillSaveFeature,
WillSaveWaitUntilFeature
} from './textSynchronization';
import { CompletionItemFeature, CompletionMiddleware } from './completion';
import { HoverFeature, HoverMiddleware } from './hover';
import { DefinitionFeature, DefinitionMiddleware } from './definition';
import { SignatureHelpFeature, SignatureHelpMiddleware } from './signatureHelp';
import { DocumentHighlightFeature, DocumentHighlightMiddleware } from './documentHighlight';
import { DocumentSymbolFeature, DocumentSymbolMiddleware } from './documentSymbol';
import { WorkspaceSymbolFeature, WorkspaceSymbolMiddleware } from './workspaceSymbol';
import { ReferencesFeature, ReferencesMiddleware } from './reference';
import { TypeDefinitionFeature, TypeDefinitionMiddleware } from './typeDefinition';
import { ImplementationFeature, ImplementationMiddleware } from './implementation';
import { ColorProviderFeature, ColorProviderMiddleware } from './colorProvider';
import { CodeActionFeature, CodeActionMiddleware } from './codeAction';
import { CodeLensFeature, CodeLensMiddleware, CodeLensProviderShape } from './codeLens';
import { DocumentFormattingFeature, DocumentOnTypeFormattingFeature, DocumentRangeFormattingFeature, FormattingMiddleware } from './formatting';
import { RenameFeature, RenameMiddleware } from './rename';
import { DocumentLinkFeature, DocumentLinkMiddleware } from './documentLink';
import { ExecuteCommandFeature, ExecuteCommandMiddleware } from './executeCommand';
import { FoldingRangeFeature, FoldingRangeProviderMiddleware, FoldingRangeProviderShape } from './foldingRange';
import { DeclarationFeature, DeclarationMiddleware } from './declaration';
import { SelectionRangeFeature, SelectionRangeProviderMiddleware } from './selectionRange';
import { CallHierarchyFeature, CallHierarchyMiddleware } from './callHierarchy';
import { SemanticTokensFeature, SemanticTokensMiddleware, SemanticTokensProviderShape } from './semanticTokens';
import { LinkedEditingFeature, LinkedEditingRangeMiddleware } from './linkedEditingRange';
import { TypeHierarchyFeature, TypeHierarchyMiddleware } from './typeHierarchy';
import { InlineValueFeature, InlineValueMiddleware, InlineValueProviderShape } from './inlineValue';
import { InlayHintsFeature, InlayHintsMiddleware, InlayHintsProviderShape } from './inlayHint';
import { WorkspaceFoldersFeature, WorkspaceFolderMiddleware } from './workspaceFolder';
import { DidCreateFilesFeature, DidDeleteFilesFeature, DidRenameFilesFeature, WillCreateFilesFeature, WillDeleteFilesFeature, WillRenameFilesFeature, FileOperationsMiddleware } from './fileOperations';
import { InlineCompletionItemFeature, InlineCompletionMiddleware } from './inlineCompletion';
import { FileSystemWatcherFeature } from './fileSystemWatcher';
import { ProgressFeature } from './progress';
/**
* Controls when the output channel is revealed.
*/
export enum RevealOutputChannelOn {
Debug = 0,
Info = 1,
Warn = 2,
Error = 3,
Never = 4
}
/**
* A handler that is invoked when the initialization of the server failed.
*/
export type InitializationFailedHandler =
/**
* @param error The error returned from the server
* @returns if true is returned the client tries to reinitialize the server.
* Implementors of a handler are responsible to not initialize the server
* infinitely. Return false if initialization should stop and an error
* should be reported.
*/
(error: ResponseError<InitializeError> | Error | any) => boolean;
/**
* An action to be performed when the connection is producing errors.
*/
export enum ErrorAction {
/**
* Continue running the server.
*/
Continue = 1,
/**
* Shutdown the server.
*/
Shutdown = 2
}
export type ErrorHandlerResult = {
/**
* The action to take.
*/
action: ErrorAction;
/**
* An optional message to be presented to the user.
*/
message?: string;
/**
* If set to true the client assumes that the corresponding
* error handler has presented an appropriate message to the
* user and the message will only be log to the client's
* output channel.
*/
handled?: boolean;
};
/**
* An action to be performed when the connection to a server got closed.
*/
export enum CloseAction {
/**
* Don't restart the server. The connection stays closed.
*/
DoNotRestart = 1,
/**
* Restart the server.
*/
Restart = 2,
}
export type CloseHandlerResult = {
/**
* The action to take.
*/
action: CloseAction;
/**
* An optional message to be presented to the user.
*/
message?: string;
/**
* If set to true the client assumes that the corresponding
* close handler has presented an appropriate message to the
* user and the message will only be log to the client's
* output channel.
*/
handled?: boolean;
};
/**
* A plugable error handler that is invoked when the connection is either
* producing errors or got closed.
*/
export interface ErrorHandler {
/**
* An error has occurred while writing or reading from the connection.
*
* @param error - the error received
* @param message - the message to be delivered to the server if know.
* @param count - a count indicating how often an error is received. Will
* be reset if a message got successfully send or received.
*/
error(error: Error, message: Message | undefined, count: number | undefined): ErrorHandlerResult | Promise<ErrorHandlerResult>;
/**
* The connection to the server got closed.
*/
closed(): CloseHandlerResult | Promise<CloseHandlerResult>;
}
/**
* Signals in which state the language client is in.
*/
export enum State {
/**
* The client is stopped or got never started.
*/
Stopped = 1,
/**
* The client is starting but not ready yet.
*/
Starting = 3,
/**
* The start has failed.
*/
StartFailed = 4,
/**
* The client is running and ready.
*/
Running = 2,
}
/**
* An event signaling a state change.
*/
export interface StateChangeEvent {
oldState: State;
newState: State;
}
export enum SuspendMode {
/**
* Don't allow suspend mode.
*/
off = 'off',
/**
* Support suspend mode even if not all
* registered providers have a corresponding
* activation listener.
*/
on = 'on',
}
export type SuspendOptions = {
/**
* Whether suspend mode is supported. If suspend mode is allowed
* the client will stop a running server when going into suspend mode.
* If omitted defaults to SuspendMode.off;
*/
mode?: SuspendMode;
/**
* A callback that is invoked before actually suspending
* the server. If `false` is returned the client will not continue
* suspending the server.
*/
callback?: () => Promise<boolean>;
/**
* The interval in milliseconds used to check if the server
* can be suspended. If the check passes three times in a row
* (e.g. the server can be suspended for 3 * interval ms) the
* server is suspended. Defaults to 60000ms, which is also the
* minimum allowed value.
*/
interval?: number;
};
export interface DidChangeWatchedFileSignature {
(this: void, event: FileEvent): Promise<void>;
}
type _WorkspaceMiddleware = {
didChangeWatchedFile?: (this: void, event: FileEvent, next: DidChangeWatchedFileSignature) => Promise<void>;
handleApplyEdit?: (this: void, params: ApplyWorkspaceEditParams, next: ApplyWorkspaceEditRequest.HandlerSignature) => HandlerResult<ApplyWorkspaceEditResult, void>;
};
export type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationMiddleware & DidChangeConfigurationMiddleware & WorkspaceFolderMiddleware & FileOperationsMiddleware;
interface _WindowMiddleware {
showDocument?: ShowDocumentRequest.MiddlewareSignature;
}
export type WindowMiddleware = _WindowMiddleware;
export interface HandleDiagnosticsSignature {
(this: void, uri: Uri, diagnostics: VDiagnostic[]): void;
}
export interface HandleWorkDoneProgressSignature {
(this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd): void;
}
interface _Middleware {
handleDiagnostics?: (this: void, uri: Uri, diagnostics: VDiagnostic[], next: HandleDiagnosticsSignature) => void;
handleWorkDoneProgress?: (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd, next: HandleWorkDoneProgressSignature) => void;
handleRegisterCapability?: (this: void, params: RegistrationParams, next: RegistrationRequest.HandlerSignature) => Promise<void>;
handleUnregisterCapability?: (this: void, params: UnregistrationParams, next: UnregistrationRequest.HandlerSignature) => Promise<void>;
workspace?: WorkspaceMiddleware;
window?: WindowMiddleware;
}
// A general middleware is applied to both requests and notifications
interface GeneralMiddleware {
sendRequest?<P, R>(
this: void,
type: string | MessageSignature,
param: P | undefined,
token: CancellationToken | undefined,
next: (type: string | MessageSignature, param?: P, token?: CancellationToken) => Promise<R>,
): Promise<R>;
sendNotification?<R>(
this: void,
type: string | MessageSignature,
next: (type: string | MessageSignature, params?: R) => Promise<void>,
params: R
): Promise<void>;
}
/**
* The Middleware lets extensions intercept the request and notifications send and received
* from the server
*/
export type Middleware = _Middleware & TextDocumentSynchronizationMiddleware & CompletionMiddleware & HoverMiddleware & DefinitionMiddleware & SignatureHelpMiddleware &
DocumentHighlightMiddleware & DocumentSymbolMiddleware & WorkspaceSymbolMiddleware & ReferencesMiddleware & TypeDefinitionMiddleware & ImplementationMiddleware &
ColorProviderMiddleware & CodeActionMiddleware & CodeLensMiddleware & FormattingMiddleware & RenameMiddleware & DocumentLinkMiddleware & ExecuteCommandMiddleware &
FoldingRangeProviderMiddleware & DeclarationMiddleware & SelectionRangeProviderMiddleware & CallHierarchyMiddleware & SemanticTokensMiddleware &
LinkedEditingRangeMiddleware & TypeHierarchyMiddleware & InlineValueMiddleware & InlayHintsMiddleware & NotebookDocumentMiddleware & DiagnosticProviderMiddleware & InlineCompletionMiddleware & GeneralMiddleware;
export type LanguageClientOptions = {
documentSelector?: DocumentSelector | string[];
diagnosticCollectionName?: string;
outputChannel?: OutputChannel;
outputChannelName?: string;
traceOutputChannel?: OutputChannel;
revealOutputChannelOn?: RevealOutputChannelOn;
/**
* The encoding use to read stdout and stderr. Defaults
* to 'utf8' if omitted.
*/
stdioEncoding?: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
progressOnInitialization?: boolean;
errorHandler?: ErrorHandler;
middleware?: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter;
protocol2Code: p2c.URIConverter;
};
workspaceFolder?: VWorkspaceFolder;
connectionOptions?: {
cancellationStrategy?: CancellationStrategy;
messageStrategy?: MessageStrategy;
maxRestartCount?: number;
};
markdown?: {
isTrusted?: boolean | { readonly enabledCommands: readonly string[] };
supportHtml?: boolean;
};
} & $NotebookDocumentOptions & $DiagnosticPullOptions & $ConfigurationOptions;
// type TestOptions = {
// $testMode?: boolean;
// };
type ResolvedClientOptions = {
documentSelector?: DocumentSelector;
synchronize: SynchronizeOptions;
diagnosticCollectionName?: string;
outputChannelName: string;
revealOutputChannelOn: RevealOutputChannelOn;
stdioEncoding: string;
initializationOptions?: any | (() => any);
initializationFailedHandler?: InitializationFailedHandler;
progressOnInitialization: boolean;
errorHandler: ErrorHandler;
middleware: Middleware;
uriConverters?: {
code2Protocol: c2p.URIConverter;
protocol2Code: p2c.URIConverter;
};
workspaceFolder?: VWorkspaceFolder;
connectionOptions?: {
cancellationStrategy?: CancellationStrategy;
messageStrategy?: MessageStrategy;
maxRestartCount?: number;
};
markdown: {
isTrusted: boolean | { readonly enabledCommands: readonly string[] };
supportHtml: boolean;
};
} & Required<$NotebookDocumentOptions> & Required<$DiagnosticPullOptions>;
namespace ResolvedClientOptions {
export function sanitizeIsTrusted(isTrusted?: boolean | { readonly enabledCommands: readonly string[] }): boolean | { readonly enabledCommands: readonly string[] } {
if (isTrusted === undefined || isTrusted === null) {
return false;
}
if ((typeof isTrusted === 'boolean') || (typeof isTrusted === 'object' && isTrusted !== null && Is.stringArray(isTrusted.enabledCommands))) {
return isTrusted;
}
return false;
}
}
class DefaultErrorHandler implements ErrorHandler {
private readonly restarts: number[];
constructor(private client: BaseLanguageClient, private maxRestartCount: number) {
this.restarts = [];
}
public error(_error: Error, _message: Message, count: number): ErrorHandlerResult {
if (count && count <= 3) {
return { action: ErrorAction.Continue };
}
return { action: ErrorAction.Shutdown };
}
public closed(): CloseHandlerResult {
this.restarts.push(Date.now());
if (this.restarts.length <= this.maxRestartCount) {
return { action: CloseAction.Restart };
} else {
const diff = this.restarts[this.restarts.length - 1] - this.restarts[0];
if (diff <= 3 * 60 * 1000) {
return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount+1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` };
} else {
this.restarts.shift();
return { action: CloseAction.Restart };
}
}
}
}
enum ClientState {
Initial = 'initial',
Starting = 'starting',
StartFailed = 'startFailed',
Running = 'running',
Stopping = 'stopping',
Stopped = 'stopped'
}
export interface MessageTransports {
reader: MessageReader;
writer: MessageWriter;
detached?: boolean;
}
export namespace MessageTransports {
export function is(value: any): value is MessageTransports {
const candidate: MessageTransports = value;
return candidate && MessageReader.is(value.reader) && MessageWriter.is(value.writer);
}
}
export enum ShutdownMode {
Restart = 'restart',
Stop = 'stop'
}
export abstract class BaseLanguageClient implements FeatureClient<Middleware, LanguageClientOptions> {
private _id: string;
private _name: string;
private _clientOptions: ResolvedClientOptions;
private _state: ClientState;
private _onStart: Promise<void> | undefined;
private _onStop: Promise<void> | undefined;
private _connection: Connection | undefined;
private _idleInterval: Disposable | undefined;
private readonly _ignoredRegistrations: Set<string>;
// private _idleStart: number | undefined;
private readonly _listeners: Disposable[];
private _disposed: 'disposing' | 'disposed' | undefined;
private readonly _notificationHandlers: Map<string, GenericNotificationHandler>;
private readonly _notificationDisposables: Map<string, Disposable>;
private readonly _pendingNotificationHandlers: Map<string, GenericNotificationHandler>;
private readonly _requestHandlers: Map<string, GenericRequestHandler<unknown, unknown>>;
private readonly _requestDisposables: Map<string, Disposable>;
private readonly _pendingRequestHandlers: Map<string, GenericRequestHandler<unknown, unknown>>;
private readonly _progressHandlers: Map<string | number, { type: ProgressType<any>; handler: NotificationHandler<any> }>;
private readonly _pendingProgressHandlers: Map<string | number, { type: ProgressType<any>; handler: NotificationHandler<any> }>;
private readonly _progressDisposables: Map<string | number, Disposable>;
private _initializeResult: InitializeResult | undefined;
private _outputChannel: OutputChannel | undefined;
private _disposeOutputChannel: boolean;
private _traceOutputChannel: OutputChannel | undefined;
private _capabilities!: ServerCapabilities & ResolvedTextDocumentSyncCapabilities;
private _diagnostics: DiagnosticCollection | undefined;
private _syncedDocuments: Map<string, TextDocument>;
private _didChangeTextDocumentFeature: DidChangeTextDocumentFeature | undefined;
private readonly _pendingOpenNotifications: Set<string>;
private readonly _pendingChangeSemaphore: Semaphore<void>;
private readonly _pendingChangeDelayer: Delayer<void>;
private _fileEvents: FileEvent[];
private _fileEventDelayer: Delayer<void>;
private _telemetryEmitter: Emitter<any>;
private _stateChangeEmitter: Emitter<StateChangeEvent>;
private _trace: Trace;
private _traceFormat: TraceFormat = TraceFormat.Text;
private _tracer: Tracer;
private readonly _c2p: c2p.Converter;
private readonly _p2c: p2c.Converter;
public constructor(id: string, name: string, clientOptions: LanguageClientOptions) {
this._id = id;
this._name = name;
clientOptions = clientOptions || {};
const markdown: ResolvedClientOptions['markdown'] = { isTrusted: false, supportHtml: false };
if (clientOptions.markdown !== undefined) {
markdown.isTrusted = ResolvedClientOptions.sanitizeIsTrusted(clientOptions.markdown.isTrusted);
markdown.supportHtml = clientOptions.markdown.supportHtml === true;
}
// const defaultInterval = (clientOptions as TestOptions).$testMode ? 50 : 60000;
this._clientOptions = {
documentSelector: clientOptions.documentSelector ?? [],
synchronize: clientOptions.synchronize ?? {},
diagnosticCollectionName: clientOptions.diagnosticCollectionName,
outputChannelName: clientOptions.outputChannelName ?? this._name,
revealOutputChannelOn: clientOptions.revealOutputChannelOn ?? RevealOutputChannelOn.Error,
stdioEncoding: clientOptions.stdioEncoding ?? 'utf8',
initializationOptions: clientOptions.initializationOptions,
initializationFailedHandler: clientOptions.initializationFailedHandler,
progressOnInitialization: !!clientOptions.progressOnInitialization,
errorHandler: clientOptions.errorHandler ?? this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount),
middleware: clientOptions.middleware ?? {},
uriConverters: clientOptions.uriConverters,
workspaceFolder: clientOptions.workspaceFolder,
connectionOptions: clientOptions.connectionOptions,
markdown,
// suspend: {
// mode: clientOptions.suspend?.mode ?? SuspendMode.off,
// callback: clientOptions.suspend?.callback ?? (() => Promise.resolve(true)),
// interval: clientOptions.suspend?.interval ? Math.max(clientOptions.suspend.interval, defaultInterval) : defaultInterval
// },
diagnosticPullOptions: clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false },
notebookDocumentOptions: clientOptions.notebookDocumentOptions ?? { }
};
this._clientOptions.synchronize = this._clientOptions.synchronize || {};
this._state = ClientState.Initial;
this._ignoredRegistrations = new Set();
this._listeners = [];
this._notificationHandlers = new Map();
this._pendingNotificationHandlers = new Map();
this._notificationDisposables = new Map();
this._requestHandlers = new Map();
this._pendingRequestHandlers = new Map();
this._requestDisposables = new Map();
this._progressHandlers = new Map();
this._pendingProgressHandlers = new Map();
this._progressDisposables = new Map();
this._connection = undefined;
// this._idleStart = undefined;
this._initializeResult = undefined;
if (clientOptions.outputChannel) {
this._outputChannel = clientOptions.outputChannel;
this._disposeOutputChannel = false;
} else {
this._outputChannel = undefined;
this._disposeOutputChannel = true;
}
this._traceOutputChannel = clientOptions.traceOutputChannel;
this._diagnostics = undefined;
this._pendingOpenNotifications = new Set();
this._pendingChangeSemaphore = new Semaphore(1);
this._pendingChangeDelayer = new Delayer<void>(250);
this._fileEvents = [];
this._fileEventDelayer = new Delayer<void>(250);
this._onStop = undefined;
this._telemetryEmitter = new Emitter<any>();
this._stateChangeEmitter = new Emitter<StateChangeEvent>();
this._trace = Trace.Off;
this._tracer = {
log: (messageOrDataObject: string | any, data?: string) => {
if (Is.string(messageOrDataObject)) {
this.logTrace(messageOrDataObject, data);
} else {
this.logObjectTrace(messageOrDataObject);
}
},
};
this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined);
this._p2c = p2c.createConverter(
clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined,
this._clientOptions.markdown.isTrusted,
this._clientOptions.markdown.supportHtml);
this._syncedDocuments = new Map<string, TextDocument>();
this.registerBuiltinFeatures();
}
public get name(): string {
return this._name;
}
public get middleware(): Middleware {
return this._clientOptions.middleware ?? Object.create(null);
}
public get clientOptions(): LanguageClientOptions {
return this._clientOptions;
}
public get protocol2CodeConverter(): p2c.Converter {
return this._p2c;
}
public get code2ProtocolConverter(): c2p.Converter {
return this._c2p;
}
public get onTelemetry(): Event<any> {
return this._telemetryEmitter.event;
}
public get onDidChangeState(): Event<StateChangeEvent> {
return this._stateChangeEmitter.event;
}
public get outputChannel(): OutputChannel {
if (!this._outputChannel) {
this._outputChannel = Window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name);
}
return this._outputChannel;
}
public get traceOutputChannel(): OutputChannel {
if (this._traceOutputChannel) {
return this._traceOutputChannel;
}
return this.outputChannel;
}
public get diagnostics(): DiagnosticCollection | undefined {
return this._diagnostics;
}
public get state(): State {
return this.getPublicState();
}
private get $state(): ClientState {
return this._state;
}
private set $state(value: ClientState) {
const oldState = this.getPublicState();
this._state = value;
const newState = this.getPublicState();
if (newState !== oldState) {
this._stateChangeEmitter.fire({ oldState, newState });
}
}
private getPublicState(): State {
switch (this.$state) {
case ClientState.Starting:
return State.Starting;
case ClientState.Running:
return State.Running;
case ClientState.StartFailed:
return State.StartFailed;
default:
return State.Stopped;
}
}
public get initializeResult(): InitializeResult | undefined {
return this._initializeResult;
}
public sendRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, token?: CancellationToken): Promise<R>;
public sendRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, params: P, token?: CancellationToken): Promise<R>;
public sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>;
public sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>;
public sendRequest<R>(method: string, token?: CancellationToken): Promise<R>;
public sendRequest<R>(method: string, param: any, token?: CancellationToken): Promise<R>;
public async sendRequest<R>(type: string | MessageSignature, ...params: any[]): Promise<R> {
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`));
}
// Ensure we have a connection before we force the document sync.
const connection = await this.$start();
// If any document is synced in full mode make sure we flush any pending
// full document syncs.
if (this._didChangeTextDocumentFeature!.syncKind === TextDocumentSyncKind.Full) {
await this.sendPendingFullTextDocumentChanges(connection);
}
let param: any | undefined = undefined;
let token: CancellationToken | undefined = undefined;
// Separate cancellation tokens from other parameters for a better client interface
if (params.length === 1) {
// CancellationToken is an interface, so we need to check if the first param complies to it
if (ProtocolCancellationToken.is(params[0])) {
token = params[0];
} else {
param = params[0];
}
} else if (params.length === 2) {
param = params[0];
token = params[1];
}
if (token !== undefined && token.isCancellationRequested) {
return Promise.reject(new ResponseError(LSPErrorCodes.RequestCancelled, 'Request got cancelled'));
}
const _sendRequest = this._clientOptions.middleware?.sendRequest;
if (_sendRequest !== undefined) {
// Return the general middleware invocation defining `next` as a utility function that reorganizes parameters to
// pass them to the original sendRequest function.
return _sendRequest(type, param, token, (type, param, token) => {
const params: any[] = [];
// Add the parameters if there are any
if (param !== undefined) {
params.push(param);
}
// Add the cancellation token if there is one
if (token !== undefined) {
params.push(token);
}
return connection.sendRequest<R>(type, ...params);
});
} else {
return connection.sendRequest<R>(type, ...params);
}
}
public onRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, handler: RequestHandler0<R, E>): Disposable;
public onRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, handler: RequestHandler<P, R, E>): Disposable;
public onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable;
public onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable;
public onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable;
public onRequest<R, E>(type: string | MessageSignature, handler: GenericRequestHandler<R, E>): Disposable {
const method = typeof type === 'string' ? type : type.method;
this._requestHandlers.set(method, handler);
const connection = this.activeConnection();
let disposable: Disposable;
if (connection !== undefined) {
this._requestDisposables.set(method, connection.onRequest(type, handler));
disposable = {
dispose: () => {
const disposable = this._requestDisposables.get(method);
if (disposable !== undefined) {
disposable.dispose();
this._requestDisposables.delete(method);
}
}
};
} else {
this._pendingRequestHandlers.set(method, handler);
disposable = {
dispose: () => {
this._pendingRequestHandlers.delete(method);
const disposable = this._requestDisposables.get(method);
if (disposable !== undefined) {
disposable.dispose();
this._requestDisposables.delete(method);
}
}
};
}
return {
dispose: () => {
this._requestHandlers.delete(method);
disposable.dispose();
}
};
}
public sendNotification<RO>(type: ProtocolNotificationType0<RO>): Promise<void>;
public sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): Promise<void>;
public sendNotification(type: NotificationType0): Promise<void>;
public sendNotification<P>(type: NotificationType<P>, params?: P): Promise<void>;
public sendNotification(method: string): Promise<void>;
public sendNotification(method: string, params: any): Promise<void>;
public async sendNotification<P>(type: string | MessageSignature, params?: P): Promise<void> {
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`));
}
const needsPendingFullTextDocumentSync: boolean = this._didChangeTextDocumentFeature!.syncKind === TextDocumentSyncKind.Full;
let openNotification: string | undefined;
if (needsPendingFullTextDocumentSync && typeof type !== 'string' && type.method === DidOpenTextDocumentNotification.method) {
openNotification = (params as DidOpenTextDocumentParams)?.textDocument.uri;
this._pendingOpenNotifications.add(openNotification);
}
// Ensure we have a connection before we force the document sync.
const connection = await this.$start();
// If any document is synced in full mode make sure we flush any pending
// full document syncs.
if (needsPendingFullTextDocumentSync) {
await this.sendPendingFullTextDocumentChanges(connection);
}
// We need to remove the pending open notification before we actually
// send the notification over the connection. Otherwise there could be
// a request coming in that although the open notification got already put
// onto the wire will ignore pending document changes.
//
// Since the code path of connection.sendNotification is actually sync
// until the message is handed of to the writer and the writer as a semaphore
// lock with a capacity of 1 no additional async scheduling can happen until
// the message is actually handed of.
if (openNotification !== undefined) {
this._pendingOpenNotifications.delete(openNotification);
}
const _sendNotification = this._clientOptions.middleware?.sendNotification;
return _sendNotification
? _sendNotification(type, connection.sendNotification.bind(connection), params)
: connection.sendNotification(type, params);
}
public onNotification<RO>(type: ProtocolNotificationType0<RO>, handler: NotificationHandler0): Disposable;
public onNotification<P, RO>(type: ProtocolNotificationType<P, RO>, handler: NotificationHandler<P>): Disposable;
public onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable;
public onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable;
public onNotification(method: string, handler: GenericNotificationHandler): Disposable;
public onNotification(type: string | MessageSignature, handler: GenericNotificationHandler): Disposable {
const method = typeof type === 'string' ? type : type.method;
this._notificationHandlers.set(method, handler);
const connection = this.activeConnection();
let disposable: Disposable;
if (connection !== undefined) {
this._notificationDisposables.set(method, connection.onNotification(type, handler));
disposable = {
dispose: () => {
const disposable = this._notificationDisposables.get(method);
if (disposable !== undefined) {
disposable.dispose();
this._notificationDisposables.delete(method);
}
}
};
} else {
this._pendingNotificationHandlers.set(method, handler);
disposable = {
dispose: () => {
this._pendingNotificationHandlers.delete(method);
const disposable = this._notificationDisposables.get(method);
if (disposable !== undefined) {
disposable.dispose();
this._notificationDisposables.delete(method);
}
}
};
}
return {
dispose: () => {
this._notificationHandlers.delete(method);
disposable.dispose();
}
};
}
public async sendProgress<P>(type: ProgressType<P>, token: string | number, value: P): Promise<void> {
if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) {
return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`));
}
try {
// Ensure we have a connection before we force the document sync.
const connection = await this.$start();
return connection.sendProgress(type, token, value);
} catch (error) {
this.error(`Sending progress for token ${token} failed.`, error);
throw error;
}
}
public onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable {
this._progressHandlers.set(token, { type, handler });
const connection = this.activeConnection();
let disposable: Disposable;
const handleWorkDoneProgress = this._clientOptions.middleware?.handleWorkDoneProgress;
const realHandler = WorkDoneProgress.is(type) && handleWorkDoneProgress !== undefined
? (params: P) => {
handleWorkDoneProgress(token, params as any, () => handler(params as unknown as P));
}
: handler;
if (connection !== undefined) {
this._progressDisposables.set(token, connection.onProgress(type, token, realHandler));
disposable = {
dispose: () => {
const disposable = this._progressDisposables.get(token);
if (disposable !== undefined) {
disposable.dispose();
this._progressDisposables.delete(token);
}
}
};
} else {
this._pendingProgressHandlers.set(token, { type, handler });
disposable = {
dispose: () => {
this._pendingProgressHandlers.delete(token);
const disposable = this._progressDisposables.get(token);
if (disposable !== undefined) {
disposable.dispose();
this._progressDisposables.delete(token);
}
}
};
}
return {
dispose: (): void => {
this._progressHandlers.delete(token);
disposable.dispose();
}
};
}
public createDefaultErrorHandler(maxRestartCount?: number): ErrorHandler {
if (maxRestartCount !== undefined && maxRestartCount < 0) {
throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`);
}
return new DefaultErrorHandler(this, maxRestartCount ?? 4);
}
public async setTrace(value: Trace): Promise<void> {
this._trace = value;
const connection = this.activeConnection();
if (connection !== undefined) {
await connection.trace(this._trace, this._tracer, {
sendNotification: false,
traceFormat: this._traceFormat
});
}
}
private data2String(data: Object): string {
if (data instanceof ResponseError) {
const responseError = data as ResponseError<any>;
return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`;
}
if (data instanceof Error) {
if (Is.string(data.stack)) {
return data.stack;
}
return (data as Error).message;
}
if (Is.string(data)) {
return data;
}
return data.toString();
}
public debug(message: string, data?: any, showNotification: boolean = true): void {
this.logOutputMessage(MessageType.Debug, RevealOutputChannelOn.Debug, 'Debug', message, data, showNotification);
}
public info(message: string, data?: any, showNotification: boolean = true): void {
this.logOutputMessage(MessageType.Info, RevealOutputChannelOn.Info, 'Info', message, data, showNotification);
}
public warn(message: string, data?: any, showNotification: boolean = true): void {
this.logOutputMessage(MessageType.Warning, RevealOutputChannelOn.Warn, 'Warn', message, data, showNotification);
}
public error(message: string, data?: any, showNotification: boolean | 'force' = true): void {
this.logOutputMessage(MessageType.Error, RevealOutputChannelOn.Error, 'Error', message, data, showNotification);
}