-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
810 lines (695 loc) · 25.7 KB
/
index.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
'use strict';
import ts = require('typescript');
import promise = require('./promise');
import ProjectManager = require('./projectManager');
import fs = require('./fileSystem');
import ws = require('./workingSet');
import project = require('./project');
import serviceUtils = require('./serviceUtils');
import Logger = require('./logger');
import utils = require('./utils');
//--------------------------------------------------------------------------
//
// Logger Injection
//
//--------------------------------------------------------------------------
/**
* Let the user inject logger used by the service.
*
* @param info information logger.
* @param warn warning logger.
* @param error error logger.
*/
export import injectLogger = Logger.injectLogger;
//--------------------------------------------------------------------------
//
// Promise Injection
//
//--------------------------------------------------------------------------
/**
* Let the user inject Promise library used by the service,
* it must be an es6 spec comliant promise library
*
* @param promise the Promise constructor of the injected library.
*/
export import injectPromiseLibrary = promise.injectPromiseLibrary;
//--------------------------------------------------------------------------
//
// Project LifeCycle
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Definitions
//--------------------------------------------------------------------------
/**
* ProjectManager configuration
*/
export import ProjectManagerConfig = ProjectManager.ProjectManagerConfig;
/**
* Interface abstracting file system to provide adapter to the service.
*/
export import IFileSystem = fs.IFileSystem;
/**
* FileSystem change descriptor.
*/
export import FileChangeRecord = fs.FileChangeRecord;
/**
* An Enum representing the kind of change that migth occur in the fileSysem.
*/
export import FileChangeKind = fs.FileChangeKind
/**
* A service that will reflect files in the working set of the editor.
*/
export import IWorkingSet = ws.IWorkingSet;
/**
* Describe a change in a document.
*/
export import DocumentChangeDescriptor = ws.DocumentChangeDescriptor;
/**
* Describe a list of changes in a document.
* You can provided either a `changeList` containing a description of all edition in the document,
* or documentText providing the new document text.
* If the first method is used (`changeList`) the compiler will be able to use incremental compilation.
*/
export import DocumentChangeRecord = ws.DocumentChangeRecord;
/**
* Describe a change in the working set.
*/
export import WorkingSetChangeRecord = ws.WorkingSetChangeRecord;
/**
* An Enum listing the kind of change that might occur in the working set.
*/
export import WorkingSetChangeKind = ws.WorkingSetChangeKind;
/**
* Project Configuration.
*/
export import TypeScriptProjectConfig = project.TypeScriptProjectConfig;
/**
* C# like events and delegates for typed events dispatching.
*/
export import ISignal = utils.ISignal;
//--------------------------------------------------------------------------
// init
//--------------------------------------------------------------------------
/**
* Initializate the service.
*
* @param config the main service configuration
*/
export function init(config: ProjectManagerConfig): promise.Promise<void> {
return ProjectManager.init(config);
}
//--------------------------------------------------------------------------
// updateProjectConfigs
//--------------------------------------------------------------------------
/**
* Update the configurations of the projects managed by this service.
*
* @param configs
* A map project name to project config file.
* if a project previously managed by this service is not present in the map
* the project will be disposed.
* If a new project is present in the map, the project will be initialized
* Otherwise the project will be updated accordingly to the new configuration
*/
export function updateProjectConfigs(configs: { [projectId: string]: TypeScriptProjectConfig; }): promise.Promise<void> {
return ProjectManager.updateProjectConfigs(configs);
}
/**
* Dispose the service.
*/
export function dispose(): void {
ProjectManager.dispose();
}
//--------------------------------------------------------------------------
//
// Services
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// Globally used definition
//--------------------------------------------------------------------------
/**
* Represent a text span in the document.
*/
export type TextSpan = {
/**
* The start of the text span.
*/
start: number;
/**
* The length of the text span.
*/
length: number;
}
/**
* Convert a TextSpan in typescript compiler format to raw json format.
* Since depending of the version of the language service
*
* @param span the text span to convert.
*/
function tsSpanToTextSpan(span : ts.TextSpan | { start: number; length: number; }): TextSpan {
var start: number;
var length: number;
if (typeof span.start === 'function') {
start = (<ts.TextSpan>span).start();
length = (<ts.TextSpan>span).length();
} else {
start = (<TextSpan>span).start;
length = (<TextSpan>span).length
}
return { start, length };
}
//--------------------------------------------------------------------------
// getDiagnosticsForFile
//--------------------------------------------------------------------------
/**
* Represent an error diagnostic.
*/
export type Diagnostics = {
/**
* The name of the file related to this diagnostic.
*/
fileName: string;
/**
* Start position of the error.
*/
start: number;
/**
* Length of the error.
*/
length: number;
/**
* Error message.
*/
messageText: string;
/**
* Diagnostic category. (warning, error, message)
*/
category: ts.DiagnosticCategory;
/**
* Error code
*/
code: number;
}
/**
* Retrieve a list of errors for a given file
* return a promise resolving to a list of errors
*
* @param fileName the absolute file name
* @param allErrors by default errors are checked in 3 phases, options check, syntax check,
* semantic check, is allErrors is set to false, the service won't check the nex phase
* if there is error in the precedent one
*/
export function getDiagnosticsForFile(fileName: string, allErrors = false): promise.Promise<Diagnostics[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
var diagnostics = languageService.getCompilerOptionsDiagnostics();
if (diagnostics.length === 0 || allErrors) {
diagnostics = languageService.getSyntacticDiagnostics(fileName);
}
if (diagnostics.length === 0 || allErrors) {
diagnostics = languageService.getSemanticDiagnostics(fileName);
}
return diagnostics.map(diagnostic => ({
fileName: fileName,
start: diagnostic.start,
length: diagnostic.length,
messageText: diagnostic.messageText,
category: diagnostic.category,
code: diagnostic.code
}));
});
}
//--------------------------------------------------------------------------
// getCompletionAtPosition
//--------------------------------------------------------------------------
/**
* Represent the result of completion request
*/
export type CompletionResult = {
/**
* the matched string portion
*/
match: string;
/**
* list of proposed entries for code completion
*/
entries: ts.CompletionEntryDetails[];
}
/**
* Retrieve completion proposal at a given point in a given file.
* return a promise resolving to a list of completion proposals.
*
* @param fileName the absolute file name.
* @param position the position in the file where the completion is requested.
* @param limit the max number of proposition this service shoudl return.
* @param skip the number of proposition this service should skip.
*
*/
export function getCompletionAtPosition(fileName: string, position: number, limit = 50, skip = 0): promise.Promise<CompletionResult> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService(),
completionInfo = languageService.getCompletionsAtPosition(fileName, position),
typeScriptEntries = completionInfo && completionInfo.entries;
if (!typeScriptEntries) {
return { entries: [], match: '' };
}
var match: string;
var sourceFile = languageService.getSourceFile(fileName);
var ts = project.getTypeScriptInfo().ts;
var word = serviceUtils.getTouchingWord(sourceFile, position, ts);
if (word && serviceUtils.isWord(word.kind, ts)) {
match = word.getText();
typeScriptEntries = typeScriptEntries.filter(entry => {
return entry.name && entry.name.toLowerCase().indexOf(match.toLowerCase()) === 0;
});
}
var completionEntries = typeScriptEntries
.sort((entry1, entry2) => {
var match1 = entry1 ? entry1.name.indexOf(match) : -1,
match2 = entry2 ? entry2.name.indexOf(match) : -1;
if (match1 === 0 && match2 !== 0) {
return -1;
} else if (match2 === 0 && match1 !== 0) {
return 1;
} else {
var name1 = entry1 && entry1.name.toLowerCase(),
name2 = entry2 && entry2.name.toLowerCase();
if (name1 < name2) {
return -1;
} else if (name1 > name2) {
return 1;
} else {
return 0;
}
}
})
.slice(skip, limit + skip)
.map(typeScriptEntry => languageService.getCompletionEntryDetails(fileName, position, typeScriptEntry.name));
return {
entries: completionEntries,
match: match
};
});
}
//--------------------------------------------------------------------------
// getQuickInfoAtPosition
//--------------------------------------------------------------------------
/**
* Represent the result of a quickInfo request
*/
export type QuickInfo = {
kind: string;
kindModifiers: string;
textSpan: TextSpan;
displayParts: ts.SymbolDisplayPart[];
documentation: ts.SymbolDisplayPart[];
}
/**
* Retrieve information about type/documentation for the givent file name at the given position.
*
* @param fileName the absolute file name.
* @param position the position in the file where the informations are requested.
*/
export function getQuickInfoAtPosition(fileName:string, position: number): promise.Promise<QuickInfo> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
var info = languageService.getQuickInfoAtPosition(fileName, position)
return {
kind: info.kind,
kindModifiers: info.kindModifiers,
textSpan: tsSpanToTextSpan(info.textSpan),
displayParts: info.displayParts,
documentation: info.documentation
}
});
}
//--------------------------------------------------------------------------
// getSignatureHelpItems
//--------------------------------------------------------------------------
/**
* Represent information about a function signature
*/
export type SignatureHelpItems = {
items: ts.SignatureHelpItem[];
applicableSpan: TextSpan;
selectedItemIndex: number;
argumentIndex: number;
argumentCount: number;
}
/**
* Retrieve signature information about a function being called.
*
* @param fileName the absolute file name.
* @param position the position in the file where the informations are requested.
*/
export function getSignatureHelpItems(fileName:string, position: number): promise.Promise<SignatureHelpItems> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
var signature = languageService.getSignatureHelpItems(fileName, position)
return {
items: signature.items,
applicableSpan: tsSpanToTextSpan(signature.applicableSpan),
selectedItemIndex: signature.selectedItemIndex,
argumentIndex: signature.argumentIndex,
argumentCount: signature.argumentCount
}
});
}
//--------------------------------------------------------------------------
// getRenameInfo
//--------------------------------------------------------------------------
/**
* Represent renam information
*/
export type RenameInfo = {
canRename: boolean;
localizedErrorMessage: string;
displayName: string;
fullDisplayName: string;
kind: string;
kindModifiers: string;
triggerSpan: TextSpan;
}
/**
* Retrieve rename informations about a symbol at a given position.
* This method will look into all the projects, and returns the first positive renameInfo found.
*
* @param fileName the absolute file name.
* @param position the position in the file where the rename informations are requested.
*/
export function getRenameInfo(fileName:string, position: number): promise.Promise<RenameInfo> {
return ProjectManager.getAllProjectsForFile(fileName).then(projects => {
for (var i = 0; i < projects.length; i++) {
var project = projects[i];
var languageService = project.getLanguageService();
var info = languageService.getRenameInfo(fileName, position);
if (info && info.canRename || i === projects.length -1) {
return {
canRename: info.canRename,
localizedErrorMessage: info.localizedErrorMessage,
displayName: info.displayName,
fullDisplayName: info.fullDisplayName,
kind: info.kind,
kindModifiers: info.kindModifiers,
triggerSpan: tsSpanToTextSpan(info.triggerSpan)
}
}
}
});
}
//--------------------------------------------------------------------------
// getRenameInfo
//--------------------------------------------------------------------------
/**
* Retrieve locations where a rename must occurs.
* This methods apply to all the project that manage the given file.
*
* @param fileName the absolute file name.
* @param position the position of the symbol to rename.
* @param findInComments if true the service will also look into comments.
*/
export function findRenameLocations(
fileName:string, position: number,
findInStrings: boolean, findInComments: boolean
): promise.Promise<{ textSpan: TextSpan; fileName: string;}[]> {
return ProjectManager.getAllProjectsForFile(fileName).then(projects => {
return utils.flatten<{ textSpan: TextSpan; fileName: string;}>(
projects.map(project => {
var languageService = project.getLanguageService();
return languageService.findRenameLocations(fileName, position, findInStrings, findInComments)
.map(location => ({
textSpan: tsSpanToTextSpan(location.textSpan),
fileName: location.fileName
}));
})
).filter((info, index, array) => {
return array.slice(index + 1).every(info1 => (
info1.fileName !== info.fileName ||
info1.textSpan.start !== info.textSpan.start
));
})
});
}
//--------------------------------------------------------------------------
// getDefinitionAtPosition
//--------------------------------------------------------------------------
/**
* Represent information about a typescript definition.
*/
export type DefinitionInfo = {
fileName: string;
textSpan: TextSpan;
kind: string;
name: string;
containerKind: string;
containerName: string;
}
/**
* Retrieve informations about a typescript definition.
*
* @param fileName the absolute file name.
* @param position the position of the definition in the file.
*/
export function getDefinitionAtPosition(fileName: string, position: number): promise.Promise<DefinitionInfo[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
return languageService.getDefinitionAtPosition(fileName, position)
.map(def => ({
fileName: def.fileName,
textSpan: tsSpanToTextSpan(def.textSpan),
kind: def.kind,
name: def.name,
containerKind: def.containerKind,
containerName: def.containerName
}))
});
}
//--------------------------------------------------------------------------
// getReferencesAtPosition
//--------------------------------------------------------------------------
/**
* Represent information about a reference.
*/
export type ReferenceEntry = {
textSpan: TextSpan;
fileName: string;
isWriteAccess: boolean;
}
/**
* Retrieve a symbol references accros a project.
* This method look into every project that manage the given file.
*
* @param fileName the absolute file name.
* @param position the position of the symbol.
*/
export function getReferencesAtPosition(fileName: string, position: number): promise.Promise<ReferenceEntry[]> {
return ProjectManager.getAllProjectsForFile(fileName).then(projects => {
return utils.flatten<{ textSpan: TextSpan; fileName: string;}>(
projects.map(project => {
var languageService = project.getLanguageService();
return languageService.getReferencesAtPosition(fileName, position)
.map(ref => ({
fileName: ref.fileName,
textSpan: tsSpanToTextSpan(ref.textSpan),
isWriteAccess: ref.isWriteAccess
}))
})
).filter((info, index, array) => {
return array.slice(index + 1).every(info1 => (
info1.fileName !== info.fileName ||
info1.textSpan.start !== info.textSpan.start
));
});
});
}
//--------------------------------------------------------------------------
// getOccurrencesAtPosition
//--------------------------------------------------------------------------
/**
* Retrieve a symbol references accros a file.
*
* @param fileName the absolute file name.
* @param position the position of the symbol.
*/
export function getOccurrencesAtPosition(fileName: string, position: number): promise.Promise<ReferenceEntry[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
return languageService.getOccurrencesAtPosition(fileName, position)
.map(ref => ({
fileName: ref.fileName,
textSpan: tsSpanToTextSpan(ref.textSpan),
isWriteAccess: ref.isWriteAccess
}))
});
}
//--------------------------------------------------------------------------
// getNavigateToItems
//--------------------------------------------------------------------------
/**
* Retrieve navigation information
*/
export type NavigateToItem = {
name: string;
kind: string;
kindModifiers: string;
matchKind: string;
fileName: string;
textSpan: TextSpan;
containerName: string;
containerKind: string;
}
/**
* Retrieve information about navigation between files of the project
*
* @param position the searched string.
*/
export function getNavigateToItems(search: string): promise.Promise<NavigateToItem[]> {
return ProjectManager.getAllProjects().then(projects => {
return utils.flatten<{ textSpan: TextSpan; fileName: string;}>(
projects.map(project => {
var languageService = project.getLanguageService();
return languageService.getNavigateToItems(search)
.map(item => ({
name: item.name,
kind: item.kind,
kindModifiers: item.kindModifiers,
matchKind: item.matchKind,
fileName: item.fileName,
textSpan: tsSpanToTextSpan(item.textSpan),
containerName: item.containerName,
containerKind: item.containerKind
}))
})
).filter((info, index, array) => {
return array.slice(index + 1).every(info1 => (
info1.fileName !== info.fileName ||
info1.textSpan.start !== info.textSpan.start
));
});
});
}
//--------------------------------------------------------------------------
// getNavigationBarItems
//--------------------------------------------------------------------------
/**
* Represent a Nigation bar item
*/
export type NavigationBarItem = {
text: string;
kind: string;
kindModifiers: string;
spans: { start: number; length: number }[];
childItems: NavigationBarItem[];
indent: number;
bolded: boolean;
grayed: boolean;
}
/**
* Convert a typescript navigation bar item to raw json format.
*/
function tsNavigationBarItemToNavigationBarItem(item: ts.NavigationBarItem) : NavigationBarItem {
return {
text: item.text,
kind: item.kind,
kindModifiers: item.kindModifiers,
indent: item.indent,
bolded: item.bolded,
grayed: item.grayed,
spans: item.spans && item.spans.map(tsSpanToTextSpan),
childItems: item.childItems && item.childItems.map(tsNavigationBarItemToNavigationBarItem)
}
}
/**
* Retrieve navigation bar for the givent file
*
* @param fileName the absolute file name.
*/
export function getNavigationBarItems(fileName: string): promise.Promise<NavigationBarItem[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
return languageService.getNavigationBarItems(fileName).map(tsNavigationBarItemToNavigationBarItem);
});
}
//--------------------------------------------------------------------------
// getFormattingEditsForRange
//--------------------------------------------------------------------------
/**
* Represent a change to apply in the document for formatting.
*/
export type TextChange = {
/**
* The text span to replace.
*/
span: TextSpan;
/**
* The new text to insert.
*/
newText: string;
}
/**
* Retrieve formating information for a file or range in a file.
*
* @param fileName the absolute file name.
* @param options formatting options.
* @param start if start and end are provided the formatting will only be applied on that range.
* @param end if start and end are provided the formatting will only be applied on that range.
*/
export function getFormattingEditsForFile(fileName: string, options: ts.FormatCodeOptions, start?: number, end?: number): promise.Promise<TextChange[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
if(typeof start === 'number' && typeof end === 'number') {
return languageService.getFormattingEditsForRange(fileName, start, end, options)
.map(edit =>({
span: tsSpanToTextSpan(edit.span),
newText: edit.newText
}))
} else {
return languageService.getFormattingEditsForDocument(fileName, options)
.map(edit =>({
span: tsSpanToTextSpan(edit.span),
newText: edit.newText
}))
}
});
}
//--------------------------------------------------------------------------
// getFormattingEditsForRange
//--------------------------------------------------------------------------
/**
* Retrieve formating information after a key stroke (use for auto formating)
*
* @param fileName the absolute file name.
* @param options formatting options.
* @param position the position where the key stroke occured.
* @param key the key.
*/
export function getFormattingEditsAfterKeyStroke(
fileName: string,
options: ts.FormatCodeOptions,
position: number,
key: string): promise.Promise<TextChange[]> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
return languageService.getFormattingEditsAfterKeystroke(fileName, position, key, options)
.map(edit =>({
span: tsSpanToTextSpan(edit.span),
newText: edit.newText
}))
});
}
//--------------------------------------------------------------------------
// getEmitOutput
//--------------------------------------------------------------------------
/**
* Retrieve emit output for a file name
*
* @param fileName the absolute file name.
*/
export function getEmitOutput(fileName: string): promise.Promise<ts.EmitOutput> {
return ProjectManager.getProjectForFile(fileName).then(project => {
var languageService = project.getLanguageService();
return languageService.getEmitOutput(fileName)
});
}