/
typescriptRuntime.ts
385 lines (353 loc) · 15.7 KB
/
typescriptRuntime.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
import type { TextRange } from '@volar/vue-code-gen';
import type * as ts from 'typescript/lib/tsserverlibrary';
import * as path from 'path';
import useHtmlPlugin from './plugins/html';
import usePugPlugin from './plugins/pug';
import { LanguageServiceHost, VueCompilerOptions } from './types';
import * as localTypes from './utils/localTypes';
import { injectCacheLogicToLanguageServiceHost } from './utils/ts';
import { createVueFile, EmbeddedFile } from './vueFile';
import { createVueFiles } from './vueFiles';
export interface VueLanguagePlugin {
compileTemplate?(tmplate: string, lang: string): {
result: string,
mapping(htmlStart: number, htmlEnd: number): { start: number, end: number } | undefined,
} | undefined
}
export type TypeScriptRuntime = ReturnType<typeof createTypeScriptRuntime>;
export function createTypeScriptRuntime(options: {
typescript: typeof import('typescript/lib/tsserverlibrary'),
vueCompilerOptions: VueCompilerOptions,
getCssVBindRanges: (cssEmbeddeFile: EmbeddedFile) => TextRange[],
getCssClasses: (cssEmbeddeFile: EmbeddedFile) => Record<string, TextRange[]>,
vueLsHost: LanguageServiceHost,
isTsPlugin?: boolean,
isVueTsc?: boolean,
}) {
const { typescript: ts } = options;
const isVue2 = options.vueLsHost.getVueCompilationSettings?.().experimentalCompatMode === 2;
let vueProjectVersion: string | undefined;
let scriptContentVersion = 0; // only update by `<script>` / `<script setup>` / *.ts content
let scriptProjectVersion = 0; // update by script LS virtual files / *.ts
let templateProjectVersion = 0;
let lastScriptProjectVersionWhenTemplateProjectVersionUpdate = -1;
const vueFiles = createVueFiles();
const templateScriptUpdateFileNames = new Set<string>();
const initProgressCallback: ((p: number) => void)[] = [];
const plugins = [
useHtmlPlugin(),
usePugPlugin(),
];
const templateTsHost = options.vueCompilerOptions.experimentalDisableTemplateSupport ? undefined : createTsLsHost('template');
const scriptTsHost = createTsLsHost('script');
const templateTsLsRaw = templateTsHost ? ts.createLanguageService(templateTsHost) : undefined;
const scriptTsLsRaw = ts.createLanguageService(scriptTsHost);
if (templateTsHost && templateTsLsRaw) {
injectCacheLogicToLanguageServiceHost(ts, templateTsHost, templateTsLsRaw);
}
injectCacheLogicToLanguageServiceHost(ts, scriptTsHost, scriptTsLsRaw);
const localTypesScript = ts.ScriptSnapshot.fromString(localTypes.getTypesCode(isVue2));
return {
vueLsHost: options.vueLsHost,
vueFiles,
getTsLs: (lsType: 'template' | 'script') => lsType === 'template' ? templateTsLsRaw! : scriptTsLsRaw,
getTsLsHost: (lsType: 'template' | 'script') => lsType === 'template' ? templateTsHost! : scriptTsHost,
update,
getScriptContentVersion: () => scriptContentVersion,
dispose: () => {
scriptTsLsRaw.dispose();
templateTsLsRaw?.dispose();
},
onInitProgress(cb: (p: number) => void) {
initProgressCallback.push(cb);
},
getLocalTypesFiles: (lsType: 'script' | 'template') => {
const fileNames = getLocalTypesFiles(lsType);
const code = localTypes.getTypesCode(isVue2);
return {
fileNames,
code,
};
},
};
function getLocalTypesFiles(lsType: 'script' | 'template') {
if (lsType === 'script')
return [];
return vueFiles.getDirs().map(dir => path.join(dir, localTypes.typesFileName));
}
function update(shouldUpdateTemplateScript: boolean) {
const newVueProjectVersion = options.vueLsHost.getVueProjectVersion?.();
if (newVueProjectVersion === undefined || newVueProjectVersion !== vueProjectVersion) {
vueProjectVersion = newVueProjectVersion;
const nowFileNames = new Set([...options.vueLsHost.getScriptFileNames()].filter(file => file.endsWith('.vue')));
const fileNamesToRemove: string[] = [];
const fileNamesToCreate: string[] = [];
const fileNamesToUpdate: string[] = [];
for (const vueFile of vueFiles.getAll()) {
if (!nowFileNames.has(vueFile.fileName) && !options.vueLsHost.fileExists?.(vueFile.fileName)) {
// delete
fileNamesToRemove.push(vueFile.fileName);
}
else {
// update
const newVersion = options.vueLsHost.getScriptVersion(vueFile.fileName);
if (vueFile.getVersion() !== newVersion) {
fileNamesToUpdate.push(vueFile.fileName);
}
}
}
for (const nowFileName of nowFileNames) {
if (!vueFiles.get(nowFileName)) {
// add
fileNamesToCreate.push(nowFileName);
}
}
// if (tsFileChanged) {
// scriptContentVersion++;
// scriptProjectVersion++;
// templateProjectVersion++;
// // TODO: template global properties can't update by .d.ts definition
// // wait for https://github.com/johnsoncodehk/volar/issues/455
// // updates.length = 0;
// // for (const fileName of oldFiles) {
// // if (newFiles.has(fileName)) {
// // if (fileName.endsWith('.vue')) {
// // updates.push(fileName);
// // }
// // }
// // }
// }
const finalUpdateFileNames = fileNamesToCreate.concat(fileNamesToUpdate);
if (fileNamesToRemove.length) {
unsetSourceFiles(fileNamesToRemove);
}
if (finalUpdateFileNames.length) {
updateSourceFiles(finalUpdateFileNames, shouldUpdateTemplateScript)
}
}
else if (shouldUpdateTemplateScript && templateScriptUpdateFileNames.size) {
updateSourceFiles([], shouldUpdateTemplateScript)
}
}
function createTsLsHost(lsType: 'template' | 'script') {
const scriptSnapshots = new Map<string, [string, ts.IScriptSnapshot]>();
const fileVersions = new WeakMap<EmbeddedFile, string>();
const tsHost: ts.LanguageServiceHost = {
...options.vueLsHost,
fileExists: options.vueLsHost.fileExists
? fileName => {
// .vue.js -> .vue
// .vue.ts -> .vue
// .vue.d.ts (never)
const fileNameTrim = fileName.substring(0, fileName.lastIndexOf('.'));
if (fileNameTrim.endsWith('.vue')) {
const vueFile = vueFiles.get(fileNameTrim);
if (!vueFile) {
const fileExists = !!options.vueLsHost.fileExists?.(fileNameTrim);
if (fileExists) {
updateSourceFiles([fileNameTrim], false); // create virtual files
}
}
return !!vueFiles.fromEmbeddedFileName(lsType, fileName);
}
else {
return !!options.vueLsHost.fileExists?.(fileName);
}
}
: undefined,
getProjectVersion: () => {
return options.vueLsHost.getProjectVersion?.() + '-' + (lsType === 'template' ? templateProjectVersion : scriptProjectVersion).toString();
},
getScriptFileNames,
getScriptVersion,
getScriptSnapshot,
readDirectory: (_path, extensions, exclude, include, depth) => {
const result = options.vueLsHost.readDirectory?.(_path, extensions, exclude, include, depth) ?? [];
for (const vuePath of vueFiles.getFileNames()) {
const vuePath2 = path.join(_path, path.basename(vuePath));
if (path.relative(_path.toLowerCase(), vuePath.toLowerCase()).startsWith('..')) {
continue;
}
if (!depth && vuePath.toLowerCase() === vuePath2.toLowerCase()) {
result.push(vuePath2);
}
else if (depth) {
result.push(vuePath2); // TODO: depth num
}
}
return result;
},
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;
}
},
};
if (lsType === 'template') {
tsHost.getCompilationSettings = () => ({
...options.vueLsHost.getCompilationSettings(),
jsx: ts.JsxEmit.Preserve,
});
}
return tsHost;
function getScriptFileNames() {
const tsFileNames = getLocalTypesFiles(lsType);
for (const maped of vueFiles.getEmbeddeds(lsType)) {
tsFileNames.push(maped.embedded.file.fileName); // virtual .ts
}
for (const fileName of options.vueLsHost.getScriptFileNames()) {
if (options.isTsPlugin) {
tsFileNames.push(fileName); // .vue + .ts
}
else if (!fileName.endsWith('.vue')) {
tsFileNames.push(fileName); // .ts
}
}
return tsFileNames;
}
function getScriptVersion(fileName: string) {
const basename = path.basename(fileName);
if (basename === localTypes.typesFileName) {
return '';
}
let maped = vueFiles.fromEmbeddedFileName(lsType, fileName);
if (maped) {
if (fileVersions.has(maped.embedded.file)) {
return fileVersions.get(maped.embedded.file)!;
}
else {
let version = ts.sys.createHash?.(maped.embedded.file.content) ?? maped.embedded.file.content;
if (options.isVueTsc) {
// fix https://github.com/johnsoncodehk/volar/issues/1082
version = maped.vueFile.getVersion() + ':' + version;
}
fileVersions.set(maped.embedded.file, version);
return version;
}
}
return options.vueLsHost.getScriptVersion(fileName);
}
function getScriptSnapshot(fileName: string) {
const version = getScriptVersion(fileName);
const cache = scriptSnapshots.get(fileName.toLowerCase());
if (cache && cache[0] === version) {
return cache[1];
}
const basename = path.basename(fileName);
if (basename === localTypes.typesFileName) {
return localTypesScript;
}
const maped = vueFiles.fromEmbeddedFileName(lsType, fileName);
if (maped) {
const text = maped.embedded.file.content;
const snapshot = ts.ScriptSnapshot.fromString(text);
scriptSnapshots.set(fileName.toLowerCase(), [version, snapshot]);
return snapshot;
}
let tsScript = options.vueLsHost.getScriptSnapshot(fileName);
if (tsScript) {
if (lsType === 'template' && basename === 'runtime-dom.d.ts') {
// allow arbitrary attributes
let tsScriptText = tsScript.getText(0, tsScript.getLength());
tsScriptText = tsScriptText.replace('type ReservedProps = {', 'type ReservedProps = { [name: string]: any')
tsScript = ts.ScriptSnapshot.fromString(tsScriptText);
}
scriptSnapshots.set(fileName.toLowerCase(), [version, tsScript]);
return tsScript;
}
}
}
function updateSourceFiles(fileNames: string[], shouldUpdateTemplateScript: boolean) {
let vueScriptContentsUpdate = false;
let vueScriptsUpdated = false;
let templateScriptUpdated = false;
if (shouldUpdateTemplateScript) {
for (const cb of initProgressCallback) {
cb(0);
}
}
for (const fileName of fileNames) {
const sourceFile = vueFiles.get(fileName);
const scriptSnapshot = options.vueLsHost.getScriptSnapshot(fileName);
if (!scriptSnapshot) {
continue;
}
const scriptText = scriptSnapshot.getText(0, scriptSnapshot.getLength());
const scriptVersion = options.vueLsHost.getScriptVersion(fileName);
if (!sourceFile) {
vueFiles.set(fileName, createVueFile(
fileName,
scriptText,
scriptVersion,
plugins,
options.vueCompilerOptions,
options.typescript,
options.getCssVBindRanges,
options.getCssClasses,
));
vueScriptContentsUpdate = true;
vueScriptsUpdated = true;
}
else {
const updates = sourceFile.update(scriptText, scriptVersion);
if (updates.scriptContentUpdated) {
vueScriptContentsUpdate = true;
}
if (updates.scriptUpdated) {
vueScriptsUpdated = true;
}
if (updates.templateScriptUpdated) {
templateScriptUpdated = true;
}
}
templateScriptUpdateFileNames.add(fileName);
}
if (vueScriptContentsUpdate) {
scriptContentVersion++;
}
if (vueScriptsUpdated) {
scriptProjectVersion++;
templateProjectVersion++;
}
if (shouldUpdateTemplateScript && lastScriptProjectVersionWhenTemplateProjectVersionUpdate !== scriptContentVersion) {
lastScriptProjectVersionWhenTemplateProjectVersionUpdate = scriptContentVersion;
let currentNums = 0;
for (const fileName of templateScriptUpdateFileNames) {
if (templateTsLsRaw && templateTsHost && vueFiles.get(fileName)?.updateTemplateScript(templateTsLsRaw, templateTsHost)) {
templateScriptUpdated = true;
}
currentNums++;
for (const cb of initProgressCallback) {
cb(currentNums / templateScriptUpdateFileNames.size);
}
}
templateScriptUpdateFileNames.clear();
for (const cb of initProgressCallback) {
cb(1);
}
initProgressCallback.length = 0;
}
if (templateScriptUpdated) {
templateProjectVersion++;
}
}
function unsetSourceFiles(uris: string[]) {
let updated = false;
for (const uri of uris) {
if (vueFiles.delete(uri)) {
updated = true;
}
}
if (updated) {
scriptContentVersion++;
scriptProjectVersion++;
templateProjectVersion++;
}
}
}