/
index.ts
279 lines (257 loc) · 9.78 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
import * as vue from '@volar/vue-typescript';
import * as path from 'path';
import * as apis from './apis';
import { tsShared } from '@volar/vue-typescript';
const init: ts.server.PluginModuleFactory = (modules) => {
const { typescript: ts } = modules;
const vueFilesGetter = new WeakMap<ts.server.Project, () => string[]>();
const pluginModule: ts.server.PluginModule = {
create(info) {
// fix: https://github.com/johnsoncodehk/volar/issues/205
info.project.getScriptKind = fileName => {
switch (path.extname(fileName)) {
case '.vue': return ts.ScriptKind.TSX; // can't use External, Unknown
case '.js': return ts.ScriptKind.JS;
case '.jsx': return ts.ScriptKind.JSX;
case '.ts': return ts.ScriptKind.TS;
case '.tsx': return ts.ScriptKind.TSX;
case '.json': return ts.ScriptKind.JSON;
default: return ts.ScriptKind.Unknown;
}
};
const proxyHost = createProxyHost(ts, info);
const vueCompilerOptions = proxyHost.host.getVueCompilationSettings?.() ?? {};
const tsRuntime = vue.createTypeScriptRuntime({
typescript: ts,
vueCompilerOptions,
baseCssModuleType: 'any',
getCssClasses: () => ({}),
vueLsHost: proxyHost.host,
isTsPlugin: true
});
const _tsPluginApis = apis.register(tsRuntime);
const tsPluginProxy: Partial<ts.LanguageService> = {
getSemanticDiagnostics: apiHook(tsRuntime.getTsLs().getSemanticDiagnostics),
getEncodedSemanticClassifications: apiHook(tsRuntime.getTsLs().getEncodedSemanticClassifications),
getCompletionsAtPosition: apiHook(_tsPluginApis.getCompletionsAtPosition),
getCompletionEntryDetails: apiHook(tsRuntime.getTsLs().getCompletionEntryDetails),
getCompletionEntrySymbol: apiHook(tsRuntime.getTsLs().getCompletionEntrySymbol),
getQuickInfoAtPosition: apiHook(tsRuntime.getTsLs().getQuickInfoAtPosition),
getSignatureHelpItems: apiHook(tsRuntime.getTsLs().getSignatureHelpItems),
getRenameInfo: apiHook(tsRuntime.getTsLs().getRenameInfo),
findRenameLocations: apiHook(_tsPluginApis.findRenameLocations),
getDefinitionAtPosition: apiHook(_tsPluginApis.getDefinitionAtPosition),
getDefinitionAndBoundSpan: apiHook(_tsPluginApis.getDefinitionAndBoundSpan),
getTypeDefinitionAtPosition: apiHook(_tsPluginApis.getTypeDefinitionAtPosition),
getImplementationAtPosition: apiHook(_tsPluginApis.getImplementationAtPosition),
getReferencesAtPosition: apiHook(_tsPluginApis.getReferencesAtPosition),
findReferences: apiHook(_tsPluginApis.findReferences),
// TODO: now is handle by vue server
// prepareCallHierarchy: apiHook(tsLanguageService.rawLs.prepareCallHierarchy, false),
// provideCallHierarchyIncomingCalls: apiHook(tsLanguageService.rawLs.provideCallHierarchyIncomingCalls, false),
// provideCallHierarchyOutgoingCalls: apiHook(tsLanguageService.rawLs.provideCallHierarchyOutgoingCalls, false),
// getEditsForFileRename: apiHook(tsLanguageService.rawLs.getEditsForFileRename, false),
// TODO
// getCodeFixesAtPosition: apiHook(tsLanguageService.rawLs.getCodeFixesAtPosition, false),
// getCombinedCodeFix: apiHook(tsLanguageService.rawLs.getCombinedCodeFix, false),
// applyCodeActionCommand: apiHook(tsLanguageService.rawLs.applyCodeActionCommand, false),
// getApplicableRefactors: apiHook(tsLanguageService.rawLs.getApplicableRefactors, false),
// getEditsForRefactor: apiHook(tsLanguageService.rawLs.getEditsForRefactor, false),
};
vueFilesGetter.set(info.project, proxyHost.getVueFiles);
return new Proxy(info.languageService, {
get: (target: any, property: keyof ts.LanguageService) => {
return tsPluginProxy[property] || target[property];
},
});
function apiHook<T extends (...args: any) => any>(
api: T,
) {
const handler = {
apply(target: (...args: any) => any, thisArg: any, argumentsList: Parameters<T>) {
tsRuntime.update();
return target.apply(thisArg, argumentsList);
}
};
return new Proxy<T>(api, handler);
}
},
getExternalFiles(project) {
const getVueFiles = vueFilesGetter.get(project);
if (!getVueFiles) {
return [];
}
return getVueFiles().filter(fileName => project.fileExists(fileName));
},
}
return pluginModule;
};
export = init;
function createProxyHost(ts: typeof import('typescript/lib/tsserverlibrary'), info: ts.server.PluginCreateInfo) {
let projectVersion = 0;
let reloadVueFilesSeq = 0;
let sendDiagSeq = 0;
let disposed = false;
const vueFiles = new Map<string, {
fileWatcher: ts.FileWatcher,
version: number,
snapshots: ts.IScriptSnapshot | undefined,
snapshotsVersion: string | undefined,
}>();
const host: vue.LanguageServiceHost = {
getNewLine: () => info.project.getNewLine(),
useCaseSensitiveFileNames: () => info.project.useCaseSensitiveFileNames(),
readFile: path => info.project.readFile(path),
writeFile: (path, content) => info.project.writeFile(path, content),
fileExists: path => info.project.fileExists(path),
directoryExists: path => info.project.directoryExists(path),
getDirectories: path => info.project.getDirectories(path),
readDirectory: (path, extensions, exclude, include, depth) => info.project.readDirectory(path, extensions, exclude, include, depth),
realpath: info.project.realpath ? path => info.project.realpath!(path) : undefined,
getCompilationSettings: () => info.project.getCompilationSettings(),
getVueCompilationSettings: () => parsedCommandLine?.vueOptions ?? {},
getCurrentDirectory: () => info.project.getCurrentDirectory(),
getDefaultLibFileName: () => info.project.getDefaultLibFileName(),
getProjectVersion: () => info.project.getProjectVersion(),
getVueProjectVersion: () => projectVersion.toString(),
getProjectReferences: () => info.project.getProjectReferences(),
getScriptFileNames,
getScriptVersion,
getScriptSnapshot,
};
update();
const directoryWatcher = info.serverHost.watchDirectory(info.project.getCurrentDirectory(), onAnyDriveFileUpdated, true);
const projectName = info.project.projectName;
let tsconfigWatcher = info.project.fileExists(projectName)
? info.serverHost.watchFile(projectName, () => {
onConfigUpdated();
onProjectUpdated();
parsedCommandLine = tsShared.createParsedCommandLine(ts, ts.sys, projectName);
})
: undefined;
let parsedCommandLine = tsconfigWatcher // reuse fileExists result
? tsShared.createParsedCommandLine(ts, ts.sys, projectName)
: undefined;
return {
host,
getVueFiles: () => [...vueFiles.keys()],
dispose,
};
async function onAnyDriveFileUpdated(fileName: string) {
if (fileName.endsWith('.vue') && info.project.fileExists(fileName) && !vueFiles.has(fileName)) {
onConfigUpdated();
}
}
async function onConfigUpdated() {
const seq = ++reloadVueFilesSeq;
await sleep(100);
if (seq === reloadVueFilesSeq && !disposed) {
update();
}
}
function getScriptFileNames() {
return info.project.getScriptFileNames().concat([...vueFiles.keys()]);
}
function getScriptVersion(fileName: string) {
if (vueFiles.has(fileName)) {
return vueFiles.get(fileName)!.version.toString();
}
return info.project.getScriptVersion(fileName);
}
function getScriptSnapshot(fileName: string) {
if (vueFiles.has(fileName)) {
const version = getScriptVersion(fileName);
const file = vueFiles.get(fileName)!;
if (file.snapshotsVersion !== version) {
const text = getScriptText(fileName);
if (text === undefined) return;
file.snapshots = ts.ScriptSnapshot.fromString(text);
file.snapshotsVersion = version;
return file.snapshots;
}
return file.snapshots;
}
return info.project.getScriptSnapshot(fileName);
}
function getScriptText(fileName: string) {
if (info.project.fileExists(fileName)) {
return info.project.readFile(fileName);
}
}
function getVueFiles() {
const parseConfigHost: ts.ParseConfigHost = {
useCaseSensitiveFileNames: info.project.useCaseSensitiveFileNames(),
readDirectory: (path, extensions, exclude, include, depth) => {
return info.project.readDirectory(path, ['.vue'], exclude, include, depth);
},
fileExists: fileName => info.project.fileExists(fileName),
readFile: fileName => info.project.readFile(fileName),
};
const { fileNames } = ts.parseJsonConfigFileContent({}, parseConfigHost, info.project.getCurrentDirectory(), info.project.getCompilerOptions());
return fileNames;
}
function update() {
const newVueFiles = new Set(getVueFiles());
let changed = false;
for (const fileName of vueFiles.keys()) {
if (!newVueFiles.has(fileName)) {
vueFiles.get(fileName)?.fileWatcher.close();
vueFiles.delete(fileName);
changed = true;
}
}
for (const fileName of newVueFiles) {
if (!vueFiles.has(fileName)) {
const fileWatcher = info.serverHost.watchFile(fileName, (_, eventKind) => {
if (eventKind === ts.FileWatcherEventKind.Changed) {
onFileChanged(fileName);
}
else if (eventKind === ts.FileWatcherEventKind.Deleted) {
vueFiles.get(fileName)?.fileWatcher.close();
vueFiles.delete(fileName);
onProjectUpdated();
}
});
vueFiles.set(fileName, {
fileWatcher,
version: 0,
snapshots: undefined,
snapshotsVersion: undefined,
});
changed = true;
}
}
if (changed) {
onProjectUpdated();
}
}
function onFileChanged(fileName: string) {
fileName = path.resolve(fileName);
const file = vueFiles.get(fileName);
if (file) {
file.version++;
}
onProjectUpdated();
}
async function onProjectUpdated() {
projectVersion++;
const seq = ++sendDiagSeq;
await sleep(100);
if (seq === sendDiagSeq) {
info.project.refreshDiagnostics();
}
}
function dispose() {
directoryWatcher.close();
if (tsconfigWatcher) {
tsconfigWatcher.close();
}
for (const [_, file] of vueFiles) {
file.fileWatcher.close();
}
disposed = true;
}
}
function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}