forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtsserverProjectSystem.ts
3982 lines (3457 loc) · 173 KB
/
tsserverProjectSystem.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
/// <reference path="..\harness.ts" />
/// <reference path="../../server/typingsInstaller/typingsInstaller.ts" />
namespace ts.projectSystem {
import TI = server.typingsInstaller;
import protocol = server.protocol;
import CommandNames = server.CommandNames;
const safeList = {
path: <Path>"/safeList.json",
content: JSON.stringify({
commander: "commander",
express: "express",
jquery: "jquery",
lodash: "lodash",
moment: "moment"
})
};
const customSafeList = {
path: <Path>"/typeMapList.json",
content: JSON.stringify({
"quack": {
"match": "/duckquack-(\\d+)\\.min\\.js",
"types": ["duck-types"]
},
})
};
export interface PostExecAction {
readonly success: boolean;
readonly callback: TI.RequestCompletedAction;
}
export const nullLogger: server.Logger = {
close: () => void 0,
hasLevel: () => void 0,
loggingEnabled: () => false,
perftrc: () => void 0,
info: () => void 0,
startGroup: () => void 0,
endGroup: () => void 0,
msg: () => void 0,
getLogFileName: (): string => undefined
};
export const { content: libFileContent } = Harness.getDefaultLibraryFile(Harness.IO);
export const libFile: FileOrFolder = {
path: "/a/lib/lib.d.ts",
content: libFileContent
};
export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller {
protected projectService: server.ProjectService;
constructor(
readonly globalTypingsCacheLocation: string,
throttleLimit: number,
installTypingHost: server.ServerHost,
readonly typesRegistry = createMap<void>(),
log?: TI.Log) {
super(installTypingHost, globalTypingsCacheLocation, safeList.path, throttleLimit, log);
}
safeFileList = safeList.path;
protected postExecActions: PostExecAction[] = [];
executePendingCommands() {
const actionsToRun = this.postExecActions;
this.postExecActions = [];
for (const action of actionsToRun) {
action.callback(action.success);
}
}
checkPendingCommands(expectedCount: number) {
assert.equal(this.postExecActions.length, expectedCount, `Expected ${expectedCount} post install actions`);
}
onProjectClosed() {
}
attach(projectService: server.ProjectService) {
this.projectService = projectService;
}
getInstallTypingHost() {
return this.installTypingHost;
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
this.addPostExecAction("success", cb);
}
sendResponse(response: server.SetTypings | server.InvalidateCachedTypings) {
this.projectService.updateTypingsForProject(response);
}
enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation);
this.install(request);
}
addPostExecAction(stdout: string | string[], cb: TI.RequestCompletedAction) {
const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout);
const action: PostExecAction = {
success: !!out,
callback: cb
};
this.postExecActions.push(action);
}
}
function createNpmPackageJsonString(installedTypings: string[]): string {
const dependencies: MapLike<any> = {};
for (const typing of installedTypings) {
dependencies[typing] = "1.0.0";
}
return JSON.stringify({ dependencies: dependencies });
}
export function getExecutingFilePathFromLibFile(): string {
return combinePaths(getDirectoryPath(libFile.path), "tsc.js");
}
export function toExternalFile(fileName: string): protocol.ExternalFile {
return { fileName };
}
export function toExternalFiles(fileNames: string[]) {
return map(fileNames, toExternalFile);
}
export class TestServerEventManager {
public events: server.ProjectServiceEvent[] = [];
handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => {
this.events.push(event);
}
checkEventCountOfType(eventType: "context" | "configFileDiag", expectedCount: number) {
const eventsOfType = filter(this.events, e => e.eventName === eventType);
assert.equal(eventsOfType.length, expectedCount, `The actual event counts of type ${eventType} is ${eventsOfType.length}, while expected ${expectedCount}`);
}
}
export interface TestServerHostCreationParameters {
useCaseSensitiveFileNames?: boolean;
executingFilePath?: string;
currentDirectory?: string;
newLine?: string;
}
export function createServerHost(fileOrFolderList: FileOrFolder[], params?: TestServerHostCreationParameters): TestServerHost {
if (!params) {
params = {};
}
const host = new TestServerHost(
params.useCaseSensitiveFileNames !== undefined ? params.useCaseSensitiveFileNames : false,
params.executingFilePath || getExecutingFilePathFromLibFile(),
params.currentDirectory || "/",
fileOrFolderList,
params.newLine);
return host;
}
class TestSession extends server.Session {
private seq = 0;
getProjectService() {
return this.projectService;
}
public getSeq() {
return this.seq;
}
public getNextSeq() {
return this.seq + 1;
}
public executeCommandSeq<T extends server.protocol.Request>(request: Partial<T>) {
this.seq++;
request.seq = this.seq;
request.type = "request";
return this.executeCommand(<T>request);
}
}
export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller, projectServiceEventHandler?: server.ProjectServiceEventHandler, cancellationToken?: server.ServerCancellationToken, throttleWaitMilliseconds?: number) {
if (typingsInstaller === undefined) {
typingsInstaller = new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host);
}
const opts: server.SessionOptions = {
host,
cancellationToken: cancellationToken || server.nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: nullLogger,
canUseEvents: projectServiceEventHandler !== undefined,
eventHandler: projectServiceEventHandler,
throttleWaitMilliseconds
};
return new TestSession(opts);
}
export interface CreateProjectServiceParameters {
cancellationToken?: HostCancellationToken;
logger?: server.Logger;
useSingleInferredProject?: boolean;
typingsInstaller?: server.ITypingsInstaller;
eventHandler?: server.ProjectServiceEventHandler;
}
export class TestProjectService extends server.ProjectService {
constructor(host: server.ServerHost, logger: server.Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean,
typingsInstaller: server.ITypingsInstaller, eventHandler: server.ProjectServiceEventHandler) {
super({
host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler
});
}
checkNumberOfProjects(count: { inferredProjects?: number, configuredProjects?: number, externalProjects?: number }) {
checkNumberOfProjects(this, count);
}
}
export function createProjectService(host: server.ServerHost, parameters: CreateProjectServiceParameters = {}) {
const cancellationToken = parameters.cancellationToken || server.nullCancellationToken;
const logger = parameters.logger || nullLogger;
const useSingleInferredProject = parameters.useSingleInferredProject !== undefined ? parameters.useSingleInferredProject : false;
return new TestProjectService(host, logger, cancellationToken, useSingleInferredProject, parameters.typingsInstaller, parameters.eventHandler);
}
export interface FileOrFolder {
path: string;
content?: string;
fileSize?: number;
}
export interface FSEntry {
path: Path;
fullPath: string;
}
export interface File extends FSEntry {
content: string;
fileSize?: number;
}
export interface Folder extends FSEntry {
entries: FSEntry[];
}
export function isFolder(s: FSEntry): s is Folder {
return isArray((<Folder>s).entries);
}
export function isFile(s: FSEntry): s is File {
return typeof (<File>s).content === "string";
}
export function addFolder(fullPath: string, toPath: (s: string) => Path, fs: FileMap<FSEntry>): Folder {
const path = toPath(fullPath);
if (fs.contains(path)) {
Debug.assert(isFolder(fs.get(path)));
return (<Folder>fs.get(path));
}
const entry: Folder = { path, entries: [], fullPath };
fs.set(path, entry);
const baseFullPath = getDirectoryPath(fullPath);
if (fullPath !== baseFullPath) {
addFolder(baseFullPath, toPath, fs).entries.push(entry);
}
return entry;
}
export function checkMapKeys(caption: string, map: Map<any>, expectedKeys: string[]) {
assert.equal(map.size, expectedKeys.length, `${caption}: incorrect size of map`);
for (const name of expectedKeys) {
assert.isTrue(map.has(name), `${caption} is expected to contain ${name}, actual keys: ${arrayFrom(map.keys())}`);
}
}
export function checkFileNames(caption: string, actualFileNames: string[], expectedFileNames: string[]) {
assert.equal(actualFileNames.length, expectedFileNames.length, `${caption}: incorrect actual number of files, expected ${JSON.stringify(expectedFileNames)}, got ${actualFileNames}`);
for (const f of expectedFileNames) {
assert.isTrue(contains(actualFileNames, f), `${caption}: expected to find ${f} in ${JSON.stringify(actualFileNames)}`);
}
}
export function checkNumberOfConfiguredProjects(projectService: server.ProjectService, expected: number) {
assert.equal(projectService.configuredProjects.length, expected, `expected ${expected} configured project(s)`);
}
export function checkNumberOfExternalProjects(projectService: server.ProjectService, expected: number) {
assert.equal(projectService.externalProjects.length, expected, `expected ${expected} external project(s)`);
}
export function checkNumberOfInferredProjects(projectService: server.ProjectService, expected: number) {
assert.equal(projectService.inferredProjects.length, expected, `expected ${expected} inferred project(s)`);
}
export function checkNumberOfProjects(projectService: server.ProjectService, count: { inferredProjects?: number, configuredProjects?: number, externalProjects?: number }) {
checkNumberOfConfiguredProjects(projectService, count.configuredProjects || 0);
checkNumberOfExternalProjects(projectService, count.externalProjects || 0);
checkNumberOfInferredProjects(projectService, count.inferredProjects || 0);
}
export function checkWatchedFiles(host: TestServerHost, expectedFiles: string[]) {
checkMapKeys("watchedFiles", host.watchedFiles, expectedFiles);
}
export function checkWatchedDirectories(host: TestServerHost, expectedDirectories: string[]) {
checkMapKeys("watchedDirectories", host.watchedDirectories, expectedDirectories);
}
export function checkProjectActualFiles(project: server.Project, expectedFiles: string[]) {
checkFileNames(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles);
}
export function checkProjectRootFiles(project: server.Project, expectedFiles: string[]) {
checkFileNames(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles);
}
export class Callbacks {
private map: TimeOutCallback[] = [];
private nextId = 1;
register(cb: (...args: any[]) => void, args: any[]) {
const timeoutId = this.nextId;
this.nextId++;
this.map[timeoutId] = cb.bind(/*this*/ undefined, ...args);
return timeoutId;
}
unregister(id: any) {
if (typeof id === "number") {
delete this.map[id];
}
}
count() {
let n = 0;
for (const _ in this.map) {
n++;
}
return n;
}
invoke() {
// Note: invoking a callback may result in new callbacks been queued,
// so do not clear the entire callback list regardless. Only remove the
// ones we have invoked.
for (const key in this.map) {
this.map[key]();
delete this.map[key];
}
}
}
export type TimeOutCallback = () => any;
export class TestServerHost implements server.ServerHost {
args: string[] = [];
private readonly output: string[] = [];
private fs: ts.FileMap<FSEntry>;
private getCanonicalFileName: (s: string) => string;
private toPath: (f: string) => Path;
private timeoutCallbacks = new Callbacks();
private immediateCallbacks = new Callbacks();
readonly watchedDirectories = createMultiMap<{ cb: DirectoryWatcherCallback, recursive: boolean }>();
readonly watchedFiles = createMultiMap<FileWatcherCallback>();
private filesOrFolders: FileOrFolder[];
constructor(public useCaseSensitiveFileNames: boolean, private executingFilePath: string, private currentDirectory: string, fileOrFolderList: FileOrFolder[], public readonly newLine = "\n") {
this.getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames);
this.toPath = s => toPath(s, currentDirectory, this.getCanonicalFileName);
this.reloadFS(fileOrFolderList);
}
reloadFS(filesOrFolders: FileOrFolder[]) {
this.filesOrFolders = filesOrFolders;
this.fs = createFileMap<FSEntry>();
// always inject safelist file in the list of files
for (const fileOrFolder of filesOrFolders.concat(safeList)) {
const path = this.toPath(fileOrFolder.path);
const fullPath = getNormalizedAbsolutePath(fileOrFolder.path, this.currentDirectory);
if (typeof fileOrFolder.content === "string") {
const entry = { path, content: fileOrFolder.content, fullPath, fileSize: fileOrFolder.fileSize };
this.fs.set(path, entry);
addFolder(getDirectoryPath(fullPath), this.toPath, this.fs).entries.push(entry);
}
else {
addFolder(fullPath, this.toPath, this.fs);
}
}
}
fileExists(s: string) {
const path = this.toPath(s);
return this.fs.contains(path) && isFile(this.fs.get(path));
}
getFileSize(s: string) {
const path = this.toPath(s);
if (this.fs.contains(path)) {
const entry = this.fs.get(path);
if (isFile(entry)) {
return entry.fileSize ? entry.fileSize : entry.content.length;
}
}
return undefined;
}
directoryExists(s: string) {
const path = this.toPath(s);
return this.fs.contains(path) && isFolder(this.fs.get(path));
}
getDirectories(s: string) {
const path = this.toPath(s);
if (!this.fs.contains(path)) {
return [];
}
else {
const entry = this.fs.get(path);
return isFolder(entry) ? map(entry.entries, x => getBaseFileName(x.fullPath)) : [];
}
}
readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[] {
const that = this;
return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), (dir) => {
const result: FileSystemEntries = {
directories: [],
files: []
};
const dirEntry = that.fs.get(that.toPath(dir));
if (isFolder(dirEntry)) {
dirEntry.entries.forEach((entry) => {
if (isFolder(entry)) {
result.directories.push(entry.fullPath);
}
else if (isFile(entry)) {
result.files.push(entry.fullPath);
}
});
}
return result;
});
}
watchDirectory(directoryName: string, callback: DirectoryWatcherCallback, recursive: boolean): DirectoryWatcher {
const path = this.toPath(directoryName);
const cbWithRecursive = { cb: callback, recursive };
this.watchedDirectories.add(path, cbWithRecursive);
return {
referenceCount: 0,
directoryName,
close: () => this.watchedDirectories.remove(path, cbWithRecursive)
};
}
createHash(s: string): string {
return s;
}
triggerDirectoryWatcherCallback(directoryName: string, fileName: string): void {
const path = this.toPath(directoryName);
const callbacks = this.watchedDirectories.get(path);
if (callbacks) {
for (const callback of callbacks) {
callback.cb(fileName);
}
}
}
triggerFileWatcherCallback(fileName: string, removed?: boolean): void {
const path = this.toPath(fileName);
const callbacks = this.watchedFiles.get(path);
if (callbacks) {
for (const callback of callbacks) {
callback(path, removed);
}
}
}
watchFile(fileName: string, callback: FileWatcherCallback) {
const path = this.toPath(fileName);
this.watchedFiles.add(path, callback);
return { close: () => this.watchedFiles.remove(path, callback) };
}
// TOOD: record and invoke callbacks to simulate timer events
setTimeout(callback: TimeOutCallback, _time: number, ...args: any[]) {
return this.timeoutCallbacks.register(callback, args);
}
clearTimeout(timeoutId: any): void {
this.timeoutCallbacks.unregister(timeoutId);
}
checkTimeoutQueueLength(expected: number) {
const callbacksCount = this.timeoutCallbacks.count();
assert.equal(callbacksCount, expected, `expected ${expected} timeout callbacks queued but found ${callbacksCount}.`);
}
runQueuedTimeoutCallbacks() {
this.timeoutCallbacks.invoke();
}
runQueuedImmediateCallbacks() {
this.immediateCallbacks.invoke();
}
setImmediate(callback: TimeOutCallback, _time: number, ...args: any[]) {
return this.immediateCallbacks.register(callback, args);
}
clearImmediate(timeoutId: any): void {
this.immediateCallbacks.unregister(timeoutId);
}
createDirectory(directoryName: string): void {
this.createFileOrFolder({ path: directoryName });
}
writeFile(path: string, content: string): void {
this.createFileOrFolder({ path, content, fileSize: content.length });
}
createFileOrFolder(f: FileOrFolder, createParentDirectory = false): void {
const base = getDirectoryPath(f.path);
if (base !== f.path && !this.directoryExists(base)) {
if (createParentDirectory) {
// TODO: avoid reloading FS on every creation
this.createFileOrFolder({ path: base }, createParentDirectory);
}
else {
throw new Error(`directory ${base} does not exist`);
}
}
const filesOrFolders = this.filesOrFolders.slice(0);
filesOrFolders.push(f);
this.reloadFS(filesOrFolders);
}
write(message: string) {
this.output.push(message);
}
getOutput(): ReadonlyArray<string> {
return this.output;
}
clearOutput() {
this.output.length = 0;
}
readonly readFile = (s: string) => (<File>this.fs.get(this.toPath(s))).content;
readonly resolvePath = (s: string) => s;
readonly getExecutingFilePath = () => this.executingFilePath;
readonly getCurrentDirectory = () => this.currentDirectory;
readonly exit = notImplemented;
readonly getEnvironmentVariable = notImplemented;
}
/**
* Test server cancellation token used to mock host token cancellation requests.
* The cancelAfterRequest constructor param specifies how many isCancellationRequested() calls
* should be made before canceling the token. The id of the request to cancel should be set with
* setRequestToCancel();
*/
export class TestServerCancellationToken implements server.ServerCancellationToken {
private currentId = -1;
private requestToCancel = -1;
private isCancellationRequestedCount = 0;
constructor(private cancelAfterRequest = 0) {
}
setRequest(requestId: number) {
this.currentId = requestId;
}
setRequestToCancel(requestId: number) {
this.resetToken();
this.requestToCancel = requestId;
}
resetRequest(requestId: number) {
assert.equal(requestId, this.currentId, "unexpected request id in cancellation");
this.currentId = undefined;
}
isCancellationRequested() {
this.isCancellationRequestedCount++;
// If the request id is the request to cancel and isCancellationRequestedCount
// has been met then cancel the request. Ex: cancel the request if it is a
// nav bar request & isCancellationRequested() has already been called three times.
return this.requestToCancel === this.currentId && this.isCancellationRequestedCount >= this.cancelAfterRequest;
}
resetToken() {
this.currentId = -1;
this.isCancellationRequestedCount = 0;
this.requestToCancel = -1;
}
}
export function makeSessionRequest<T>(command: string, args: T) {
const newRequest: protocol.Request = {
seq: 0,
type: "request",
command,
arguments: args
};
return newRequest;
}
export function openFilesForSession(files: FileOrFolder[], session: server.Session) {
for (const file of files) {
const request = makeSessionRequest<protocol.OpenRequestArgs>(CommandNames.Open, { file: file.path });
session.executeCommand(request);
}
}
describe("tsserver-project-system", () => {
const commonFile1: FileOrFolder = {
path: "/a/b/commonFile1.ts",
content: "let x = 1"
};
const commonFile2: FileOrFolder = {
path: "/a/b/commonFile2.ts",
content: "let y = 1"
};
it("create inferred project", () => {
const appFile: FileOrFolder = {
path: "/a/b/c/app.ts",
content: `
import {f} from "./module"
console.log(f)
`
};
const moduleFile: FileOrFolder = {
path: "/a/b/c/module.d.ts",
content: `export let x: number`
};
const host = createServerHost([appFile, moduleFile, libFile]);
const projectService = createProjectService(host);
const { configFileName } = projectService.openClientFile(appFile.path);
assert(!configFileName, `should not find config, got: '${configFileName}`);
checkNumberOfConfiguredProjects(projectService, 0);
checkNumberOfInferredProjects(projectService, 1);
const project = projectService.inferredProjects[0];
checkFileNames("inferred project", project.getFileNames(), [appFile.path, libFile.path, moduleFile.path]);
checkWatchedDirectories(host, ["/a/b/c", "/a/b", "/a"]);
});
it("can handle tsconfig file name with difference casing", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({
include: []
})
};
const host = createServerHost([f1, config], { useCaseSensitiveFileNames: false });
const service = createProjectService(host);
service.openExternalProject(<protocol.ExternalProject>{
projectFileName: "/a/b/project.csproj",
rootFiles: toExternalFiles([f1.path, combinePaths(getDirectoryPath(config.path).toUpperCase(), getBaseFileName(config.path))]),
options: {}
});
service.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
service.openClientFile(f1.path);
service.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(service.configuredProjects[0], []);
checkProjectActualFiles(service.inferredProjects[0], [f1.path]);
});
it("create configured project without file list", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `
{
"compilerOptions": {},
"exclude": [
"e"
]
}`
};
const file1: FileOrFolder = {
path: "/a/b/c/f1.ts",
content: "let x = 1"
};
const file2: FileOrFolder = {
path: "/a/b/d/f2.ts",
content: "let y = 1"
};
const file3: FileOrFolder = {
path: "/a/b/e/f3.ts",
content: "let z = 1"
};
const host = createServerHost([configFile, libFile, file1, file2, file3]);
const projectService = createProjectService(host);
const { configFileName, configFileErrors } = projectService.openClientFile(file1.path);
assert(configFileName, "should find config file");
assert.isTrue(!configFileErrors, `expect no errors in config file, got ${JSON.stringify(configFileErrors)}`);
checkNumberOfInferredProjects(projectService, 0);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectActualFiles(project, [file1.path, libFile.path, file2.path]);
checkProjectRootFiles(project, [file1.path, file2.path]);
// watching all files except one that was open
checkWatchedFiles(host, [configFile.path, file2.path, libFile.path]);
checkWatchedDirectories(host, [getDirectoryPath(configFile.path)]);
});
it("add and then remove a config file in a folder with loose files", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{
"files": ["commonFile1.ts"]
}`
};
const filesWithoutConfig = [libFile, commonFile1, commonFile2];
const host = createServerHost(filesWithoutConfig);
const filesWithConfig = [libFile, commonFile1, commonFile2, configFile];
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
projectService.openClientFile(commonFile2.path);
checkNumberOfInferredProjects(projectService, 2);
checkWatchedDirectories(host, ["/a/b", "/a"]);
// Add a tsconfig file
host.reloadFS(filesWithConfig);
host.triggerDirectoryWatcherCallback("/a/b", configFile.path);
checkNumberOfInferredProjects(projectService, 1);
checkNumberOfConfiguredProjects(projectService, 1);
// watching all files except one that was open
checkWatchedFiles(host, [libFile.path, configFile.path]);
// remove the tsconfig file
host.reloadFS(filesWithoutConfig);
host.triggerFileWatcherCallback(configFile.path);
checkNumberOfInferredProjects(projectService, 2);
checkNumberOfConfiguredProjects(projectService, 0);
checkWatchedDirectories(host, ["/a/b", "/a"]);
});
it("add new files to a configured project without file list", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{}`
};
const host = createServerHost([commonFile1, libFile, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
checkWatchedDirectories(host, ["/a/b"]);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectRootFiles(project, [commonFile1.path]);
// add a new ts file
host.reloadFS([commonFile1, commonFile2, libFile, configFile]);
host.triggerDirectoryWatcherCallback("/a/b", commonFile2.path);
host.runQueuedTimeoutCallbacks();
// project service waits for 250ms to update the project structure, therefore the assertion needs to wait longer.
checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]);
});
it("should ignore non-existing files specified in the config file", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {},
"files": [
"commonFile1.ts",
"commonFile3.ts"
]
}`
};
const host = createServerHost([commonFile1, commonFile2, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
projectService.openClientFile(commonFile2.path);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectRootFiles(project, [commonFile1.path]);
checkNumberOfInferredProjects(projectService, 1);
});
it("remove not-listed external projects", () => {
const f1 = {
path: "/a/app.ts",
content: "let x = 1"
};
const f2 = {
path: "/b/app.ts",
content: "let x = 1"
};
const f3 = {
path: "/c/app.ts",
content: "let x = 1"
};
const makeProject = (f: FileOrFolder) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} });
const p1 = makeProject(f1);
const p2 = makeProject(f2);
const p3 = makeProject(f3);
const host = createServerHost([f1, f2, f3]);
const session = createSession(host);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 1,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p2] }
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p2.projectFileName);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 2,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p1, p3] }
});
checkNumberOfProjects(projectService, { externalProjects: 2 });
assert.equal(projectService.externalProjects[0].getProjectName(), p1.projectFileName);
assert.equal(projectService.externalProjects[1].getProjectName(), p3.projectFileName);
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [] }
});
checkNumberOfProjects(projectService, { externalProjects: 0 });
session.executeCommand(<protocol.OpenExternalProjectsRequest>{
seq: 3,
type: "request",
command: "openExternalProjects",
arguments: { projects: [p2] }
});
assert.equal(projectService.externalProjects[0].getProjectName(), p2.projectFileName);
});
it("handle recreated files correctly", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{}`
};
const host = createServerHost([commonFile1, commonFile2, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]);
// delete commonFile2
host.reloadFS([commonFile1, configFile]);
host.triggerDirectoryWatcherCallback("/a/b", commonFile2.path);
host.runQueuedTimeoutCallbacks();
checkProjectRootFiles(project, [commonFile1.path]);
// re-add commonFile2
host.reloadFS([commonFile1, commonFile2, configFile]);
host.triggerDirectoryWatcherCallback("/a/b", commonFile2.path);
host.runQueuedTimeoutCallbacks();
checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]);
});
it("should create new inferred projects for files excluded from a configured project", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {},
"files": ["${commonFile1.path}", "${commonFile2.path}"]
}`
};
const files = [commonFile1, commonFile2, configFile];
const host = createServerHost(files);
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
const project = projectService.configuredProjects[0];
checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]);
configFile.content = `{
"compilerOptions": {},
"files": ["${commonFile1.path}"]
}`;
host.reloadFS(files);
host.triggerFileWatcherCallback(configFile.path);
checkNumberOfConfiguredProjects(projectService, 1);
checkProjectRootFiles(project, [commonFile1.path]);
projectService.openClientFile(commonFile2.path);
checkNumberOfInferredProjects(projectService, 1);
});
it("files explicitly excluded in config file", () => {
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {},
"exclude": ["/a/c"]
}`
};
const excludedFile1: FileOrFolder = {
path: "/a/c/excluedFile1.ts",
content: `let t = 1;`
};
const host = createServerHost([commonFile1, commonFile2, excludedFile1, configFile]);
const projectService = createProjectService(host);
projectService.openClientFile(commonFile1.path);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectRootFiles(project, [commonFile1.path, commonFile2.path]);
projectService.openClientFile(excludedFile1.path);
checkNumberOfInferredProjects(projectService, 1);
});
it("should properly handle module resolution changes in config file", () => {
const file1: FileOrFolder = {
path: "/a/b/file1.ts",
content: `import { T } from "module1";`
};
const nodeModuleFile: FileOrFolder = {
path: "/a/b/node_modules/module1.ts",
content: `export interface T {}`
};
const classicModuleFile: FileOrFolder = {
path: "/a/module1.ts",
content: `export interface T {}`
};
const configFile: FileOrFolder = {
path: "/a/b/tsconfig.json",
content: `{
"compilerOptions": {
"moduleResolution": "node"
},
"files": ["${file1.path}"]
}`
};
const files = [file1, nodeModuleFile, classicModuleFile, configFile];
const host = createServerHost(files);
const projectService = createProjectService(host);
projectService.openClientFile(file1.path);
projectService.openClientFile(nodeModuleFile.path);
projectService.openClientFile(classicModuleFile.path);
checkNumberOfConfiguredProjects(projectService, 1);
const project = projectService.configuredProjects[0];
checkProjectActualFiles(project, [file1.path, nodeModuleFile.path]);
checkNumberOfInferredProjects(projectService, 1);
configFile.content = `{
"compilerOptions": {
"moduleResolution": "classic"