Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/build/lib/typeScriptLanguageServiceHost.ts
4770 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import ts from 'typescript';
7
import fs from 'node:fs';
8
import { normalize } from 'node:path';
9
10
export type IFileMap = Map</*fileName*/ string, string>;
11
12
function normalizePath(filePath: string): string {
13
return normalize(filePath);
14
}
15
16
/**
17
* A TypeScript language service host
18
*/
19
export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
20
21
private readonly ts: typeof import('typescript');
22
private readonly topLevelFiles: IFileMap;
23
private readonly compilerOptions: ts.CompilerOptions;
24
25
constructor(
26
ts: typeof import('typescript'),
27
topLevelFiles: IFileMap,
28
compilerOptions: ts.CompilerOptions,
29
) {
30
this.ts = ts;
31
this.topLevelFiles = topLevelFiles;
32
this.compilerOptions = compilerOptions;
33
}
34
35
// --- language service host ---------------
36
getCompilationSettings(): ts.CompilerOptions {
37
return this.compilerOptions;
38
}
39
getScriptFileNames(): string[] {
40
return [
41
...this.topLevelFiles.keys(),
42
this.ts.getDefaultLibFilePath(this.compilerOptions)
43
];
44
}
45
getScriptVersion(_fileName: string): string {
46
return '1';
47
}
48
getProjectVersion(): string {
49
return '1';
50
}
51
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
52
fileName = normalizePath(fileName);
53
54
if (this.topLevelFiles.has(fileName)) {
55
return this.ts.ScriptSnapshot.fromString(this.topLevelFiles.get(fileName)!);
56
} else {
57
return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString());
58
}
59
}
60
getScriptKind(_fileName: string): ts.ScriptKind {
61
return this.ts.ScriptKind.TS;
62
}
63
getCurrentDirectory(): string {
64
return '';
65
}
66
getDefaultLibFileName(options: ts.CompilerOptions): string {
67
return this.ts.getDefaultLibFilePath(options);
68
}
69
readFile(path: string, encoding?: string): string | undefined {
70
path = normalizePath(path);
71
72
if (this.topLevelFiles.get(path)) {
73
return this.topLevelFiles.get(path);
74
}
75
return ts.sys.readFile(path, encoding);
76
}
77
fileExists(path: string): boolean {
78
path = normalizePath(path);
79
80
if (this.topLevelFiles.has(path)) {
81
return true;
82
}
83
return ts.sys.fileExists(path);
84
}
85
}
86
87