-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathindex.ts
More file actions
226 lines (210 loc) · 7.43 KB
/
Copy pathindex.ts
File metadata and controls
226 lines (210 loc) · 7.43 KB
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
import * as path from 'node:path';
import {
type CodeMapping,
forEachEmbeddedCode,
type LanguagePlugin,
type VirtualCode,
} from '@volar/language-core';
import type { TypeScriptExtraServiceScript } from '@volar/typescript';
import type ts from 'typescript';
import type { HTMLDocument } from 'vscode-html-languageservice';
import type { URI } from 'vscode-uri';
import type { PackageInfo } from '../importPackage.js';
import { getLanguageServerTypesDir } from '../utils.js';
import type { AstroDiagnostic } from '@astrojs/astro2tsx';
import { astro2tsx } from './astro2tsx.js';
import type { AstroMetadata } from './parseAstro.js';
import { getFrontmatterStatus } from './parseAstro.js';
import { extractStylesheets } from './parseCSS.js';
import { parseHTML } from './parseHTML.js';
import { extractScriptTags } from './parseJS.js';
const decoratedHosts = new WeakSet<ts.LanguageServiceHost>();
// Extensions that TypeScript doesn't recognize. When a referenced project contains
// files with these extensions, TypeScript tries to compute a declaration output path
// via changeExtension but doesn't know how to replace the extension, so it returns the
// input path unchanged (e.g. Hello.vue → Hello.vue). This creates a self-referencing
// entry in the redirect map, which causes infinite recursion in findSourceFile.
const nonTsExtensions = ['.vue', '.svelte', '.astro'];
export function addAstroTypes(
astroInstall: PackageInfo | undefined,
ts: typeof import('typescript'),
host: ts.LanguageServiceHost,
) {
if (decoratedHosts.has(host)) {
return;
}
decoratedHosts.add(host);
const getScriptFileNames = host.getScriptFileNames.bind(host);
const getCompilationSettings = host.getCompilationSettings.bind(host);
host.getScriptFileNames = () => {
const languageServerTypesDirectory = getLanguageServerTypesDir(ts);
const fileNames = getScriptFileNames();
const addedFileNames = [];
if (astroInstall) {
addedFileNames.push(
...['./env.d.ts', './astro-jsx.d.ts'].map((filePath) =>
ts.sys.resolvePath(path.resolve(astroInstall.directory, filePath)),
),
);
// If Astro version is < 4.0.8, add jsx-runtime-augment.d.ts to the files to fake `JSX` being available from "astro/jsx-runtime".
// TODO: Remove this once a majority of users are on Astro 4.0.8+, erika - 2023-12-28
if (
astroInstall.version.major < 4 ||
(astroInstall.version.major === 4 &&
astroInstall.version.minor === 0 &&
astroInstall.version.patch < 8)
) {
addedFileNames.push(
...['./jsx-runtime-augment.d.ts'].map((filePath) =>
ts.sys.resolvePath(path.resolve(languageServerTypesDirectory, filePath)),
),
);
}
} else {
// If we don't have an Astro installation, add the fallback types from the language server.
// See the README in packages/language-server/types for more information.
addedFileNames.push(
...['./env.d.ts', './astro-jsx.d.ts', './jsx-runtime-fallback.d.ts'].map((f) =>
ts.sys.resolvePath(path.resolve(languageServerTypesDirectory, f)),
),
);
}
return [...fileNames, ...addedFileNames];
};
host.getCompilationSettings = () => {
const baseCompilationSettings = getCompilationSettings();
return {
...baseCompilationSettings,
module: ts.ModuleKind.ESNext ?? 99,
target: ts.ScriptTarget.ESNext ?? 99,
jsx: ts.JsxEmit.Preserve ?? 1,
resolveJsonModule: true,
allowJs: true, // Needed for inline scripts, which are virtual .js files
isolatedModules: true,
moduleResolution:
baseCompilationSettings.moduleResolution === ts.ModuleResolutionKind.Classic ||
!baseCompilationSettings.moduleResolution
? ts.ModuleResolutionKind.Node10
: baseCompilationSettings.moduleResolution,
};
};
// Provide getParsedCommandLine to filter non-TS files from referenced project
// configs. Without this, TypeScript builds redirect maps where non-TS files
// (like .vue) map to themselves, causing infinite recursion in findSourceFile.
if (host.getProjectReferences && !host.getParsedCommandLine) {
host.getParsedCommandLine = (fileName: string) => {
const readFile = host.readFile?.bind(host) ?? ts.sys.readFile;
const configFile = ts.readJsonConfigFile(fileName, readFile);
const basePath = path.dirname(fileName);
const parsed = ts.parseJsonSourceFileConfigFileContent(
configFile,
ts.sys,
basePath,
undefined,
fileName,
);
parsed.fileNames = parsed.fileNames.filter(
(f) => !nonTsExtensions.some((ext) => f.endsWith(ext)),
);
return parsed;
};
}
}
export function getAstroLanguagePlugin(): LanguagePlugin<URI, AstroVirtualCode> {
return {
getLanguageId(uri) {
if (uri.path.endsWith('.astro')) {
return 'astro';
}
},
createVirtualCode(uri, languageId, snapshot) {
if (languageId === 'astro') {
const fileName = uri.fsPath.replace(/\\/g, '/');
return new AstroVirtualCode(fileName, snapshot);
}
},
typescript: {
extraFileExtensions: [{ extension: 'astro', isMixedContent: true, scriptKind: 7 }],
getServiceScript(astroCode) {
for (const code of forEachEmbeddedCode(astroCode)) {
if (code.id === 'tsx') {
return {
code,
extension: '.tsx',
scriptKind: 4 satisfies ts.ScriptKind.TSX,
};
}
}
return undefined;
},
getExtraServiceScripts(fileName, astroCode) {
const result: TypeScriptExtraServiceScript[] = [];
for (const code of forEachEmbeddedCode(astroCode)) {
if (code.id.endsWith('.mjs') || code.id.endsWith('.mts')) {
const fileExtension = code.id.endsWith('.mjs') ? '.mjs' : '.mts';
result.push({
fileName: fileName + '.' + code.id,
code,
extension: fileExtension,
scriptKind:
fileExtension === '.mjs'
? (1 satisfies ts.ScriptKind.JS)
: (3 satisfies ts.ScriptKind.TS),
});
}
}
return result;
},
},
};
}
export class AstroVirtualCode implements VirtualCode {
id = 'root';
languageId = 'astro';
mappings!: CodeMapping[];
embeddedCodes!: VirtualCode[];
astroMeta!: AstroMetadata;
compilerDiagnostics!: AstroDiagnostic[];
/// Conversion recovers from most syntax errors, so a file with diagnostics
/// still type-checks; only an outright failure leaves nothing to check.
hasUsableTSX!: boolean;
htmlDocument!: HTMLDocument;
codegenStacks = [];
public fileName: string;
public snapshot: ts.IScriptSnapshot;
constructor(fileName: string, snapshot: ts.IScriptSnapshot) {
this.fileName = fileName;
this.snapshot = snapshot;
this.mappings = [
{
sourceOffsets: [0],
generatedOffsets: [0],
lengths: [this.snapshot.getLength()],
data: {
verification: true,
completion: true,
semantic: true,
navigation: true,
structure: true,
format: true,
},
},
];
const input = this.snapshot.getText(0, this.snapshot.getLength());
const tsx = astro2tsx(input, this.fileName);
const frontmatter = getFrontmatterStatus(tsx.frontmatterStatus, tsx.frontmatterSource, input);
const { htmlDocument, virtualCode: htmlVirtualCode } = parseHTML(
this.snapshot,
frontmatter.status === 'closed' ? frontmatter.position.end.offset : 0,
);
this.htmlDocument = htmlDocument;
htmlVirtualCode.embeddedCodes = [
...extractStylesheets(tsx.ranges.styles),
...extractScriptTags(tsx.ranges.scripts),
];
this.astroMeta = { frontmatter, tsxRanges: tsx.ranges };
this.compilerDiagnostics = tsx.diagnostics;
this.hasUsableTSX = tsx.virtualCode.snapshot.getLength() > 0;
this.embeddedCodes = [htmlVirtualCode, tsx.virtualCode];
}
}