@volar/typescript 2.4.30 → 2.4.32-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@ const language_core_1 = require("@volar/language-core");
6
6
  const common_1 = require("../common");
7
7
  const resolveModuleName_1 = require("../resolveModuleName");
8
8
  const decorateProgram_1 = require("./decorateProgram");
9
+ const transformEmittedFile_1 = require("./transformEmittedFile");
9
10
  const utils_1 = require("./utils");
10
11
  const arrayEqual = (a, b) => {
11
12
  if (a.length !== b.length) {
@@ -207,6 +208,19 @@ function proxyCreateProgram(ts, original, create) {
207
208
  }
208
209
  const program = Reflect.apply(target, thisArg, args);
209
210
  (0, decorateProgram_1.decorateProgram)(language, program);
211
+ // Every emitted file is written through the callback given to `emit` or, without one, the host's
212
+ // `writeFile`; the source maps of plugin files are mapped back to them on the way.
213
+ const emit = program.emit;
214
+ const host = options.host;
215
+ program.emit = (targetSourceFile, writeFile, ...rest) => emit(targetSourceFile, (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => {
216
+ text = (0, transformEmittedFile_1.transformEmittedFile)(ts, language, fileName, text, sourceFiles);
217
+ if (writeFile) {
218
+ writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
219
+ }
220
+ else {
221
+ host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
222
+ }
223
+ }, ...rest);
210
224
  return program;
211
225
  },
212
226
  });
@@ -52,7 +52,7 @@ function createProxyLanguageService(languageService) {
52
52
  case 'getSignatureHelpItems':
53
53
  return getSignatureHelpItems(language, target[p]);
54
54
  case 'getDocumentHighlights':
55
- return getDocumentHighlights(language, target[p]);
55
+ return getDocumentHighlights(language, languageService, target[p]);
56
56
  case 'getApplicableRefactors':
57
57
  return getApplicableRefactors(language, target[p]);
58
58
  case 'getEditsForRefactor':
@@ -72,19 +72,19 @@ function createProxyLanguageService(languageService) {
72
72
  case 'getSuggestionDiagnostics':
73
73
  return getSuggestionDiagnostics(language, languageService, target[p]);
74
74
  case 'getDefinitionAndBoundSpan':
75
- return getDefinitionAndBoundSpan(language, target[p]);
75
+ return getDefinitionAndBoundSpan(language, languageService, target[p]);
76
76
  case 'findReferences':
77
- return findReferences(language, target[p]);
77
+ return findReferences(language, languageService, target[p]);
78
78
  case 'getDefinitionAtPosition':
79
- return getDefinitionAtPosition(language, target[p]);
79
+ return getDefinitionAtPosition(language, languageService, target[p]);
80
80
  case 'getTypeDefinitionAtPosition':
81
- return getTypeDefinitionAtPosition(language, target[p]);
81
+ return getTypeDefinitionAtPosition(language, languageService, target[p]);
82
82
  case 'getImplementationAtPosition':
83
- return getImplementationAtPosition(language, target[p]);
83
+ return getImplementationAtPosition(language, languageService, target[p]);
84
84
  case 'findRenameLocations':
85
- return findRenameLocations(language, target[p]);
85
+ return findRenameLocations(language, languageService, target[p]);
86
86
  case 'getReferencesAtPosition':
87
- return getReferencesAtPosition(language, target[p]);
87
+ return getReferencesAtPosition(language, languageService, target[p]);
88
88
  case 'getCompletionsAtPosition':
89
89
  return getCompletionsAtPosition(language, target[p]);
90
90
  case 'getCompletionEntryDetails':
@@ -112,6 +112,7 @@ function createProxyLanguageService(languageService) {
112
112
  return Reflect.get(target, p, receiver);
113
113
  },
114
114
  set(target, p, value, receiver) {
115
+ proxyCache.delete(p);
115
116
  return Reflect.set(target, p, value, receiver);
116
117
  },
117
118
  }),
@@ -431,10 +432,10 @@ function getSignatureHelpItems(language, getSignatureHelpItems) {
431
432
  }
432
433
  };
433
434
  }
434
- function getDocumentHighlights(language, getDocumentHighlights) {
435
+ function getDocumentHighlights(language, languageService, getDocumentHighlights) {
435
436
  return (filePath, position, filesToSearch) => {
436
437
  const fileName = filePath.replace(windowsPathReg, '/');
437
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isHighlightEnabled, (fileName, position) => getDocumentHighlights(fileName, position, filesToSearch), function* (result) {
438
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isHighlightEnabled, (fileName, position) => getDocumentHighlights(fileName, position, filesToSearch), function* (result) {
438
439
  for (const ref of result) {
439
440
  for (const reference of ref.highlightSpans) {
440
441
  yield [reference.fileName ?? ref.fileName, reference.textSpan.start];
@@ -673,10 +674,10 @@ function getSuggestionDiagnostics(language, languageService, getSuggestionDiagno
673
674
  .filter(d => !serviceScript || !d.file || language.scripts.get(d.file.fileName) === sourceScript);
674
675
  };
675
676
  }
676
- function getDefinitionAndBoundSpan(language, getDefinitionAndBoundSpan) {
677
+ function getDefinitionAndBoundSpan(language, languageService, getDefinitionAndBoundSpan) {
677
678
  return (filePath, position) => {
678
679
  const fileName = filePath.replace(windowsPathReg, '/');
679
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isDefinitionEnabled, (fileName, position) => getDefinitionAndBoundSpan(fileName, position), function* (result) {
680
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isDefinitionEnabled, (fileName, position) => getDefinitionAndBoundSpan(fileName, position), function* (result) {
680
681
  for (const ref of result.definitions ?? []) {
681
682
  yield [ref.fileName, ref.textSpan.start];
682
683
  }
@@ -699,10 +700,10 @@ function getDefinitionAndBoundSpan(language, getDefinitionAndBoundSpan) {
699
700
  };
700
701
  };
701
702
  }
702
- function findReferences(language, findReferences) {
703
+ function findReferences(language, languageService, findReferences) {
703
704
  return (filePath, position) => {
704
705
  const fileName = filePath.replace(windowsPathReg, '/');
705
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isReferencesEnabled, (fileName, position) => findReferences(fileName, position), function* (result) {
706
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isReferencesEnabled, (fileName, position) => findReferences(fileName, position), function* (result) {
706
707
  for (const ref of result) {
707
708
  for (const reference of ref.references) {
708
709
  yield [reference.fileName, reference.textSpan.start];
@@ -723,10 +724,10 @@ function findReferences(language, findReferences) {
723
724
  return resolved;
724
725
  };
725
726
  }
726
- function getDefinitionAtPosition(language, getDefinitionAtPosition) {
727
+ function getDefinitionAtPosition(language, languageService, getDefinitionAtPosition) {
727
728
  return (filePath, position) => {
728
729
  const fileName = filePath.replace(windowsPathReg, '/');
729
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isDefinitionEnabled, (fileName, position) => getDefinitionAtPosition(fileName, position), function* (result) {
730
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isDefinitionEnabled, (fileName, position) => getDefinitionAtPosition(fileName, position), function* (result) {
730
731
  for (const ref of result) {
731
732
  yield [ref.fileName, ref.textSpan.start];
732
733
  }
@@ -738,10 +739,10 @@ function getDefinitionAtPosition(language, getDefinitionAtPosition) {
738
739
  return (0, dedupe_1.dedupeDocumentSpans)(resolved);
739
740
  };
740
741
  }
741
- function getTypeDefinitionAtPosition(language, getTypeDefinitionAtPosition) {
742
+ function getTypeDefinitionAtPosition(language, languageService, getTypeDefinitionAtPosition) {
742
743
  return (filePath, position) => {
743
744
  const fileName = filePath.replace(windowsPathReg, '/');
744
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isTypeDefinitionEnabled, (fileName, position) => getTypeDefinitionAtPosition(fileName, position), function* (result) {
745
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isTypeDefinitionEnabled, (fileName, position) => getTypeDefinitionAtPosition(fileName, position), function* (result) {
745
746
  for (const ref of result) {
746
747
  yield [ref.fileName, ref.textSpan.start];
747
748
  }
@@ -753,10 +754,10 @@ function getTypeDefinitionAtPosition(language, getTypeDefinitionAtPosition) {
753
754
  return (0, dedupe_1.dedupeDocumentSpans)(resolved);
754
755
  };
755
756
  }
756
- function getImplementationAtPosition(language, getImplementationAtPosition) {
757
+ function getImplementationAtPosition(language, languageService, getImplementationAtPosition) {
757
758
  return (filePath, position) => {
758
759
  const fileName = filePath.replace(windowsPathReg, '/');
759
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isImplementationEnabled, (fileName, position) => getImplementationAtPosition(fileName, position), function* (result) {
760
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isImplementationEnabled, (fileName, position) => getImplementationAtPosition(fileName, position), function* (result) {
760
761
  for (const ref of result) {
761
762
  yield [ref.fileName, ref.textSpan.start];
762
763
  }
@@ -768,10 +769,10 @@ function getImplementationAtPosition(language, getImplementationAtPosition) {
768
769
  return (0, dedupe_1.dedupeDocumentSpans)(resolved);
769
770
  };
770
771
  }
771
- function findRenameLocations(language, findRenameLocations) {
772
+ function findRenameLocations(language, languageService, findRenameLocations) {
772
773
  return (filePath, position, findInStrings, findInComments, preferences) => {
773
774
  const fileName = filePath.replace(windowsPathReg, '/');
774
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isRenameEnabled, (fileName, position) => findRenameLocations(fileName, position, findInStrings, findInComments, preferences), function* (result) {
775
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isRenameEnabled, (fileName, position) => findRenameLocations(fileName, position, findInStrings, findInComments, preferences), function* (result) {
775
776
  for (const ref of result) {
776
777
  yield [ref.fileName, ref.textSpan.start];
777
778
  }
@@ -783,10 +784,10 @@ function findRenameLocations(language, findRenameLocations) {
783
784
  return (0, dedupe_1.dedupeDocumentSpans)(resolved);
784
785
  };
785
786
  }
786
- function getReferencesAtPosition(language, getReferencesAtPosition) {
787
+ function getReferencesAtPosition(language, languageService, getReferencesAtPosition) {
787
788
  return (filePath, position) => {
788
789
  const fileName = filePath.replace(windowsPathReg, '/');
789
- const unresolved = linkedCodeFeatureWorker(language, fileName, position, language_core_1.isReferencesEnabled, (fileName, position) => getReferencesAtPosition(fileName, position), function* (result) {
790
+ const unresolved = linkedCodeFeatureWorker(language, languageService, fileName, position, language_core_1.isReferencesEnabled, (fileName, position) => getReferencesAtPosition(fileName, position), function* (result) {
790
791
  for (const ref of result) {
791
792
  yield [ref.fileName, ref.textSpan.start];
792
793
  }
@@ -929,13 +930,15 @@ function getNavigateToItems(language, getNavigateToItems) {
929
930
  return (0, dedupe_1.dedupeDocumentSpans)(resolved);
930
931
  };
931
932
  }
932
- function linkedCodeFeatureWorker(language, fileName, position, filter, worker, getLinkedCodes) {
933
+ function linkedCodeFeatureWorker(language, languageService, fileName, position, filter, worker, getLinkedCodes) {
933
934
  const results = [];
934
935
  const processedFilePositions = new Set();
935
936
  const [serviceScript, targetScript, sourceScript] = (0, utils_1.getServiceScript)(language, fileName);
936
937
  if (serviceScript) {
937
- for (const [generatedOffset] of (0, transform_1.toGeneratedOffsets)(language, serviceScript, sourceScript, position, filter)) {
938
- process(targetScript.id, generatedOffset);
938
+ for (const [generatedOffset, mapping] of (0, transform_1.toGeneratedOffsets)(language, serviceScript, sourceScript, position, filter)) {
939
+ if (isNameInMappedCode(language, languageService, serviceScript, targetScript.id, generatedOffset, mapping)) {
940
+ process(targetScript.id, generatedOffset);
941
+ }
939
942
  }
940
943
  }
941
944
  else {
@@ -969,6 +972,42 @@ function linkedCodeFeatureWorker(language, fileName, position, filter, worker, g
969
972
  }
970
973
  }
971
974
  }
975
+ /**
976
+ * Whether the name TypeScript acts on at `generatedOffset` (the name or dotted
977
+ * name touching it) lies in the generated code of `mapping`, which put the
978
+ * position there.
979
+ *
980
+ * Mappings are closed intervals: where two mapped chunks meet in the source,
981
+ * the end of one and the start of the other both claim the offset between them.
982
+ * When generated code without a mapping sits between the two chunks, the claims
983
+ * land on two generated positions, and at each one TypeScript may take the name
984
+ * on the far side, in code that does not come from the source. A mapping
985
+ * vouches only for its own code, so only a position in its interior, or a name
986
+ * that reaches into its code, is the source position's.
987
+ */
988
+ function isNameInMappedCode(language, languageService, serviceScript, fileName, generatedOffset, mapping) {
989
+ const mappingOffset = (0, transform_1.getMappingOffset)(language, serviceScript);
990
+ const offset = generatedOffset - mappingOffset;
991
+ const lengths = mapping.generatedLengths ?? mapping.lengths;
992
+ const edges = [];
993
+ for (let i = 0; i < mapping.generatedOffsets.length; i++) {
994
+ const start = mapping.generatedOffsets[i];
995
+ const end = start + lengths[i];
996
+ if (start < offset && offset < end) {
997
+ return true;
998
+ }
999
+ if (offset === start || offset === end) {
1000
+ edges.push([start, end]);
1001
+ }
1002
+ }
1003
+ const name = languageService.getNameOrDottedNameSpan(fileName, generatedOffset, generatedOffset);
1004
+ if (!name) {
1005
+ return true;
1006
+ }
1007
+ const nameStart = name.start - mappingOffset;
1008
+ const nameEnd = nameStart + name.length;
1009
+ return edges.some(([start, end]) => start === end || Math.max(start, nameStart) < Math.min(end, nameEnd));
1010
+ }
972
1011
  function displayPartsToString(displayParts) {
973
1012
  if (displayParts) {
974
1013
  return displayParts.map(displayPart => displayPart.text).join('');
@@ -0,0 +1,9 @@
1
+ import { type Language } from '@volar/language-core';
2
+ import type * as ts from 'typescript';
3
+ /**
4
+ * tsc prints the code generated for a plugin file, so the source maps it emits for one hold positions in that
5
+ * code and, with `inlineSources`, its text. Moves each of their entries to the position in the plugin file that
6
+ * the plugin's mappings give, leaves it without a source position where they give none, and puts in the text of
7
+ * the plugin file. Output that no plugin file contributes to is returned as it is.
8
+ */
9
+ export declare function transformEmittedFile(ts: typeof import('typescript'), language: Language<string>, fileName: string, text: string, sourceFiles: readonly ts.SourceFile[] | undefined): string;
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.transformEmittedFile = transformEmittedFile;
4
+ const language_core_1 = require("@volar/language-core");
5
+ const transform_1 = require("./transform");
6
+ const utils_1 = require("./utils");
7
+ const inlineSourceMapPrefix = '//# sourceMappingURL=data:application/json;base64,';
8
+ const inlineSourceMapRegex = /\/\/# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]*)(\s*)$/;
9
+ /**
10
+ * tsc prints the code generated for a plugin file, so the source maps it emits for one hold positions in that
11
+ * code and, with `inlineSources`, its text. Moves each of their entries to the position in the plugin file that
12
+ * the plugin's mappings give, leaves it without a source position where they give none, and puts in the text of
13
+ * the plugin file. Output that no plugin file contributes to is returned as it is.
14
+ */
15
+ function transformEmittedFile(ts, language, fileName, text, sourceFiles) {
16
+ const pluginFiles = sourceFiles?.filter(sourceFile => (0, utils_1.getServiceScript)(language, sourceFile.fileName)[0]) ?? [];
17
+ if (!pluginFiles.length) {
18
+ return text;
19
+ }
20
+ if (fileName.endsWith('.map')) {
21
+ return transformSourceMap(ts, language, text, pluginFiles);
22
+ }
23
+ const inlineSourceMap = inlineSourceMapRegex.exec(text);
24
+ if (inlineSourceMap) {
25
+ const { base64encode, base64decode } = ts.sys;
26
+ if (!base64encode || !base64decode) {
27
+ throw new Error(`Cannot map the inline source map of ${fileName}: ts.sys has no base64 encoder.`);
28
+ }
29
+ const sourceMap = transformSourceMap(ts, language, base64decode(inlineSourceMap[1]), pluginFiles);
30
+ return text.slice(0, inlineSourceMap.index) + inlineSourceMapPrefix + base64encode(sourceMap) + inlineSourceMap[2];
31
+ }
32
+ return text;
33
+ }
34
+ function transformSourceMap(ts, language, text, pluginFiles) {
35
+ const sourceMap = JSON.parse(text);
36
+ const sources = sourceMap.sources.map(source => {
37
+ const matches = pluginFiles.filter(pluginFile => isSourceOf(source, pluginFile.fileName));
38
+ if (matches.length > 1) {
39
+ throw new Error(`Source map source ${source} matches more than one file: ${matches.map(f => f.fileName).join(', ')}`);
40
+ }
41
+ if (!matches.length) {
42
+ return;
43
+ }
44
+ const [serviceScript, , sourceScript] = (0, utils_1.getServiceScript)(language, matches[0].fileName);
45
+ return {
46
+ virtualFile: matches[0],
47
+ serviceScript: serviceScript,
48
+ sourceScript: sourceScript,
49
+ // tsc's `getLineAndCharacterOfPosition` reads only `text`; the other member is the language service's.
50
+ sourceFileLike: {
51
+ text: sourceScript.snapshot.getText(0, sourceScript.snapshot.getLength()),
52
+ },
53
+ };
54
+ });
55
+ if (sources.every(source => !source)) {
56
+ return text;
57
+ }
58
+ const lines = decodeMappings(sourceMap.mappings);
59
+ for (const segments of lines) {
60
+ for (let i = 0; i < segments.length; i++) {
61
+ const segment = segments[i];
62
+ const source = segment.length >= 4 ? sources[segment[1]] : undefined;
63
+ if (!source) {
64
+ continue;
65
+ }
66
+ const virtualOffset = ts.getPositionOfLineAndCharacter(source.virtualFile, segment[2], segment[3]);
67
+ const sourceOffset = (0, transform_1.toSourceOffset)(source.sourceScript, language, source.serviceScript, virtualOffset, language_core_1.isDefinitionEnabled);
68
+ if (sourceOffset) {
69
+ const { line, character } = ts.getLineAndCharacterOfPosition(source.sourceFileLike, sourceOffset[1]);
70
+ segment[2] = line;
71
+ segment[3] = character;
72
+ }
73
+ else {
74
+ segments[i] = [segment[0]];
75
+ }
76
+ }
77
+ }
78
+ sourceMap.mappings = encodeMappings(lines);
79
+ if (sourceMap.sourcesContent) {
80
+ sources.forEach((source, i) => {
81
+ if (source && typeof sourceMap.sourcesContent[i] === 'string') {
82
+ sourceMap.sourcesContent[i] = source.sourceFileLike.text;
83
+ }
84
+ });
85
+ }
86
+ return JSON.stringify(sourceMap);
87
+ }
88
+ /**
89
+ * Whether a `sources` entry names the file. tsc writes it relative to a directory it computes internally (the
90
+ * output's, `mapRoot`'s or the common source directory), so it is matched as a path suffix of the file name.
91
+ */
92
+ function isSourceOf(source, fileName) {
93
+ const relativePath = source.replace(/^file:\/\/\/?/, '').replace(/^(?:\.\.?\/)+/, '');
94
+ return fileName === relativePath || fileName.endsWith('/' + relativePath);
95
+ }
96
+ // Source map v3 mappings: lines separated by `;`, segments by `,`, each a list of base64 VLQ fields relative to
97
+ // the previous segment (the generated column only within a line).
98
+ const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
99
+ function decodeMappings(mappings) {
100
+ const state = [0, 0, 0, 0, 0];
101
+ return mappings.split(';').map(line => {
102
+ state[0] = 0;
103
+ return line.split(',').filter(Boolean).map(segment => {
104
+ const fields = [];
105
+ let value = 0;
106
+ let shift = 0;
107
+ for (const char of segment) {
108
+ const digit = base64Chars.indexOf(char);
109
+ value += (digit & 31) << shift;
110
+ if (digit & 32) {
111
+ shift += 5;
112
+ }
113
+ else {
114
+ fields.push(state[fields.length] += value & 1 ? -(value >>> 1) : value >>> 1);
115
+ value = 0;
116
+ shift = 0;
117
+ }
118
+ }
119
+ return fields;
120
+ });
121
+ });
122
+ }
123
+ function encodeMappings(lines) {
124
+ const state = [0, 0, 0, 0, 0];
125
+ return lines.map(segments => {
126
+ state[0] = 0;
127
+ return segments.map(fields => fields.map((field, i) => {
128
+ let value = field - state[i];
129
+ state[i] = field;
130
+ value = value < 0 ? (-value << 1) | 1 : value << 1;
131
+ let encoded = '';
132
+ do {
133
+ const digit = value & 31;
134
+ value >>>= 5;
135
+ encoded += base64Chars[value ? digit | 32 : digit];
136
+ } while (value);
137
+ return encoded;
138
+ }).join('')).join(',');
139
+ }).join(';');
140
+ }
141
+ //# sourceMappingURL=transformEmittedFile.js.map
@@ -4,9 +4,16 @@ export declare let getLanguagePlugins: (ts: typeof import('typescript'), options
4
4
  languagePlugins: LanguagePlugin<string>[];
5
5
  setup?(language: Language<string>): void;
6
6
  };
7
+ export declare let getLanguagePluginsVersion: ((ts: typeof import('typescript'), options: ts.CompilerOptions) => string | undefined) | undefined;
7
8
  export declare function runTsc(tscPath: string, options: string[] | {
8
9
  extraSupportedExtensions: string[];
9
10
  extraExtensionsToRemove: string[];
11
+ /**
12
+ * Identifies the language plugins and the options they use for a project. Build info records it
13
+ * next to the TypeScript version, so an incremental build discards build info written with other
14
+ * plugins as it does after a TypeScript upgrade.
15
+ */
16
+ getLanguagePluginsVersion?(ts: typeof import('typescript'), options: ts.CompilerOptions): string | undefined;
10
17
  }, _getLanguagePlugins: typeof getLanguagePlugins, typescriptObject?: string): void;
11
18
  /**
12
19
  * Replaces the code of typescript to add support for additional extensions and language plugins.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLanguagePlugins = void 0;
3
+ exports.getLanguagePluginsVersion = exports.getLanguagePlugins = void 0;
4
4
  exports.runTsc = runTsc;
5
5
  exports.transformTscContent = transformTscContent;
6
6
  const fs = require("fs");
@@ -15,10 +15,12 @@ function runTsc(tscPath, options, _getLanguagePlugins, typescriptObject) {
15
15
  if (Array.isArray(options)) {
16
16
  extraSupportedExtensions = options;
17
17
  extraExtensionsToRemove = [];
18
+ exports.getLanguagePluginsVersion = undefined;
18
19
  }
19
20
  else {
20
21
  extraSupportedExtensions = options.extraSupportedExtensions;
21
22
  extraExtensionsToRemove = options.extraExtensionsToRemove;
23
+ exports.getLanguagePluginsVersion = options.getLanguagePluginsVersion;
22
24
  }
23
25
  const proxyApiPath = require.resolve('../node/proxyCreateProgram');
24
26
  // Mirror the TS v5.7+ tsc shim behavior: enable the V8/JSC bytecode cache
@@ -68,13 +70,29 @@ function runTsc(tscPath, options, _getLanguagePlugins, typescriptObject) {
68
70
  */
69
71
  function transformTscContent(tsc, proxyApiPath, extraSupportedExtensions, extraExtensionsToRemove, getLanguagePluginsFile = __filename, typescriptObject = `new Proxy({}, { get(_target, p, _receiver) { return eval(p); } } )`) {
70
72
  const neededPatchExtenstions = extraSupportedExtensions.filter(ext => !extraExtensionsToRemove.includes(ext));
71
- // Add allow extensions
72
- if (extraSupportedExtensions.length) {
73
- const extsText = extraSupportedExtensions.map(ext => `"${ext}"`).join(', ');
73
+ const strippedExtensions = extraSupportedExtensions.filter(ext => extraExtensionsToRemove.includes(ext));
74
+ // An extension stripped on emit (basename.xxx -> basename.js) is emitted like a TypeScript file, so
75
+ // TypeScript treats it as one: for example, `rewriteRelativeImportExtensions` rewrites an import of
76
+ // `./basename.xxx` to `./basename.js`.
77
+ if (strippedExtensions.length) {
78
+ const extsText = strippedExtensions.map(ext => `"${ext}"`).join(', ');
74
79
  tsc = replace(tsc, /supportedTSExtensions = .*(?=;)/, s => s + `.map((group, i) => i === 0 ? group.splice(0, 0, ${extsText}) && group : group)`);
75
80
  tsc = replace(tsc, /supportedJSExtensions = .*(?=;)/, s => s + `.map((group, i) => i === 0 ? group.splice(0, 0, ${extsText}) && group : group)`);
76
81
  tsc = replace(tsc, /allSupportedExtensions = .*(?=;)/, s => s + `.map((group, i) => i === 0 ? group.splice(0, 0, ${extsText}) && group : group)`);
77
82
  }
83
+ // An extension kept on emit (basename.xxx -> basename.xxx.d.ts) is not a TypeScript or JavaScript
84
+ // extension: the file itself stays the module that is imported at runtime, so an import of it is not
85
+ // rewritten. It is only accepted as input, the way a language service host does through
86
+ // `extraFileExtensions`; tsc passes none, so it is added where supported extensions are computed
87
+ // (root files, `include` matching, watching).
88
+ if (neededPatchExtenstions.length) {
89
+ const extsText = neededPatchExtenstions
90
+ .map(ext => `{ extension: "${ext}", isMixedContent: true, scriptKind: 7 /* ScriptKind.Deferred */ }`)
91
+ .join(', ');
92
+ tsc = replace(tsc, /function getSupportedExtensions\(options, extraFileExtensions\) {/, s => `function getSupportedExtensions(options, extraFileExtensions) {
93
+ return _getSupportedExtensions(options, [...(extraFileExtensions || []), ${extsText}]);
94
+ }\n` + s.replace('getSupportedExtensions', '_getSupportedExtensions'));
95
+ }
78
96
  // Use to emit basename.xxx to basename.d.ts instead of basename.xxx.d.ts
79
97
  if (extraExtensionsToRemove.length) {
80
98
  const extsText = extraExtensionsToRemove.map(ext => `"${ext}"`).join(', ');
@@ -112,6 +130,17 @@ function transformTscContent(tsc, proxyApiPath, extraSupportedExtensions, extraE
112
130
  // Not applying this only costs memory, so a missing match is not an error.
113
131
  tsc = tsc.replace(/mutateMapSkippingNewValues\(state\.builderPrograms, currentProjects, noopOnDelete\);/, s => s
114
132
  + `\nrequire(${JSON.stringify(proxyApiPath)}).releaseRemovedProjects?.(createProgram, configFilePath => currentProjects.has(configFilePath));`);
133
+ // Record the version of the language plugins next to the TypeScript version, where build info is
134
+ // written and where its version is compared, so that build info written with other language plugins
135
+ // or options is discarded as after a TypeScript upgrade. Like the patches above, a place that no
136
+ // longer matches throws: skipping it would bring back stale results without anyone noticing.
137
+ tsc = replace(tsc, /\bconst buildInfo = host\.getBuildInfo\(\w*\) \|\|[^;]*;/, s => s + `\nbuildInfo.version = getVersionWithLanguagePlugins(compilerOptions);`);
138
+ tsc = replace(tsc, /function readBuilderProgram\(compilerOptions, host\) \{(?:(?!\nfunction )[^])*?buildInfo\.version !== version\b/, s => s.replace(/version$/, 'getVersionWithLanguagePlugins(compilerOptions)'));
139
+ tsc = replace(tsc, /function getUpToDateStatusWorker\(state, project, resolvedPath\) \{(?:(?!\nfunction )[^])*?buildInfo\.version !== version\b/, s => s.replace(/version$/, 'getVersionWithLanguagePlugins(project.options)'));
140
+ tsc += `\nfunction getVersionWithLanguagePlugins(options) {
141
+ const languagePluginsVersion = require(${JSON.stringify(getLanguagePluginsFile)}).getLanguagePluginsVersion?.(${typescriptObject}, options);
142
+ return languagePluginsVersion ? version + "+" + languagePluginsVersion : version;
143
+ }\n`;
115
144
  return tsc;
116
145
  }
117
146
  function replace(text, search, replace) {
@@ -94,6 +94,7 @@ function createResolveModuleName(ts, getFileSize, host, languagePlugins, getSour
94
94
  }
95
95
  }
96
96
  toSourceFileInfo.clear();
97
+ addPluginFilesToFailedLookupLocations(result, languagePlugins);
97
98
  return result;
98
99
  };
99
100
  function isSamePath(a, b) {
@@ -111,4 +112,42 @@ function createResolveModuleName(ts, getFileSize, host, languagePlugins, getSour
111
112
  return false;
112
113
  }
113
114
  }
115
+ /**
116
+ * INTERIM: writes `failedLookupLocations`, a field TypeScript keeps internal (absent from typescript.d.ts in
117
+ * 5.0 to 6.0).
118
+ *
119
+ * Once a file has moved, TypeScript finds the imports to update (getEditsForFileRename) through the paths
120
+ * that their now failing resolutions tried. Volar turns the lookup of `X.vue` into one of `X.d.vue.ts`
121
+ * (`fileExists` above), so `X.vue` itself is never tried, and an import such as `@/X.vue` is not updated
122
+ * when `X.vue` moves (vuejs/language-tools#5911). This adds `X.<ext>` next to each tried `X.d.<ext>.ts`.
123
+ *
124
+ * TypeScript offers no public way to add a tried path: lookups are recorded inside its resolver, and
125
+ * getEditsForFileRename maps only paths equal to the moved file or under a moved directory. TypeScript 6
126
+ * is the last JavaScript line, so no such API will come for it. This goes away with a TypeScript version
127
+ * that gives resolution hosts a way to report the paths they look at, or with TypeScript 7, which Volar
128
+ * 2.x does not run on. tests/fileRename.spec.ts runs it against every supported TypeScript minor.
129
+ */
130
+ function addPluginFilesToFailedLookupLocations(result, languagePlugins) {
131
+ const failedLookupLocations = result.failedLookupLocations;
132
+ if (failedLookupLocations === undefined) {
133
+ // TypeScript leaves the field out when nothing failed.
134
+ return;
135
+ }
136
+ if (!Array.isArray(failedLookupLocations)) {
137
+ throw new Error('[Volar] TypeScript changed the internal `failedLookupLocations` of a module resolution: '
138
+ + 'updating imports of moved plugin files needs a new way to report the paths it looks at.');
139
+ }
140
+ const extensions = languagePlugins.flatMap(plugin => plugin.typescript?.extraFileExtensions.map(({ extension }) => extension) ?? []);
141
+ for (const location of [...failedLookupLocations]) {
142
+ for (const extension of extensions) {
143
+ if (location.endsWith(`.d.${extension}.ts`)) {
144
+ const pluginFile = location.slice(0, -`.d.${extension}.ts`.length) + `.${extension}`;
145
+ // A result can come from TypeScript's resolution cache, already with the paths added.
146
+ if (!failedLookupLocations.includes(pluginFile)) {
147
+ failedLookupLocations.push(pluginFile);
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
114
153
  //# sourceMappingURL=resolveModuleName.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volar/typescript",
3
- "version": "2.4.30",
3
+ "version": "2.4.32-alpha.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "**/*.js",
@@ -12,13 +12,24 @@
12
12
  "directory": "packages/typescript"
13
13
  },
14
14
  "dependencies": {
15
- "@volar/language-core": "2.4.30",
16
- "@volar/language-service": "2.4.30",
15
+ "@volar/language-core": "2.4.32-alpha.0",
16
+ "@volar/language-service": "2.4.32-alpha.0",
17
17
  "path-browserify": "^1.0.1",
18
18
  "vscode-uri": "^3.0.8"
19
19
  },
20
20
  "devDependencies": {
21
- "@types/path-browserify": "~1.0.3"
21
+ "@types/path-browserify": "~1.0.3",
22
+ "typescript-5.0": "npm:typescript@5.0.4",
23
+ "typescript-5.1": "npm:typescript@5.1.6",
24
+ "typescript-5.2": "npm:typescript@5.2.2",
25
+ "typescript-5.3": "npm:typescript@5.3.3",
26
+ "typescript-5.4": "npm:typescript@5.4.5",
27
+ "typescript-5.5": "npm:typescript@5.5.4",
28
+ "typescript-5.6": "npm:typescript@5.6.3",
29
+ "typescript-5.7": "npm:typescript@5.7.3",
30
+ "typescript-5.8": "npm:typescript@5.8.3",
31
+ "typescript-5.9": "npm:typescript@5.9.3",
32
+ "typescript-6.0": "npm:typescript@6.0.3"
22
33
  },
23
34
  "peerDependencies": {
24
35
  "typescript": "<7"