forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.ts
199 lines (174 loc) · 6.44 KB
/
extension.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
import { ResolveModuleHost } from "@typespec/compiler/module-resolver";
import { readFile, realpath, stat } from "fs/promises";
import { join } from "path";
import vscode, { ExtensionContext, commands, workspace } from "vscode";
import {
Executable,
ExecutableOptions,
LanguageClient,
LanguageClientOptions,
} from "vscode-languageclient/node.js";
let client: LanguageClient | undefined;
export async function activate(context: ExtensionContext) {
context.subscriptions.push(
commands.registerCommand("typespec.restartServer", restartTypeSpecServer)
);
return await vscode.window.withProgress(
{
title: "Launching TypeSpec language service...",
location: vscode.ProgressLocation.Notification,
},
async () => launchLanguageClient(context)
);
}
async function restartTypeSpecServer(): Promise<void> {
if (client) {
await client.stop();
await client.start();
}
}
async function launchLanguageClient(context: ExtensionContext) {
const exe = await resolveTypeSpecServer(context);
const options: LanguageClientOptions = {
synchronize: {
// Synchronize the setting section 'typespec' to the server
configurationSection: "typespec",
fileEvents: [
workspace.createFileSystemWatcher("**/*.cadl"),
workspace.createFileSystemWatcher("**/cadl-project.yaml"),
workspace.createFileSystemWatcher("**/*.tsp"),
workspace.createFileSystemWatcher("**/tspconfig.yaml"),
workspace.createFileSystemWatcher("**/package.json"),
],
},
documentSelector: [
{ scheme: "file", language: "typespec" },
{ scheme: "untitled", language: "typespec" },
],
};
const name = "TypeSpec";
const id = "typespecLanguageServer";
try {
client = new LanguageClient(id, name, { run: exe, debug: exe }, options);
await client.start();
} catch (e) {
if (typeof e === "string" && e.startsWith("Launching server using command")) {
const workspaceFolder = workspace.workspaceFolders?.[0]?.uri?.fsPath ?? "";
client?.error(
[
`TypeSpec server executable was not found: '${exe.command}' is not found. Make sure either:`,
` - typespec is installed locally at the root of this workspace ("${workspaceFolder}") or in a parent directory.`,
" - typespec is installed globally with `npm install -g @typespec/compiler'.",
" - typespec server path is configured with https://github.com/microsoft/typespec#installing-vs-code-extension.",
].join("\n"),
undefined,
false
);
throw `TypeSpec server executable was not found: '${exe.command}' is not found.`;
} else {
throw e;
}
}
}
async function resolveTypeSpecServer(context: ExtensionContext): Promise<Executable> {
const nodeOptions = process.env.TYPESPEC_SERVER_NODE_OPTIONS;
const args = ["--stdio"];
// In development mode (F5 launch from source), resolve to locally built server.js.
if (process.env.TYPESPEC_DEVELOPMENT_MODE) {
const script = context.asAbsolutePath("../compiler/entrypoints/server.js");
// we use CLI instead of NODE_OPTIONS environment variable in this case
// because --nolazy is not supported by NODE_OPTIONS.
const options = nodeOptions?.split(" ").filter((o) => o) ?? [];
return { command: "node", args: [...options, script, ...args] };
}
const options: ExecutableOptions = {
env: { ...process.env },
};
if (nodeOptions) {
options.env.NODE_OPTIONS = nodeOptions;
}
// In production, first try VS Code configuration, which allows a global machine
// location that is not on PATH, or a workspace-specific installation.
let serverPath: string | undefined = workspace.getConfiguration().get("typespec.tsp-server.path");
if (serverPath && typeof serverPath !== "string") {
throw new Error("VS Code configuration option 'typespec.tsp-server.path' must be a string");
}
const workspaceFolder = workspace.workspaceFolders?.[0]?.uri?.fsPath ?? "";
// Default to tsp-server on PATH, which would come from `npm install -g
// @typespec/compiler` in a vanilla setup.
if (!serverPath) {
serverPath = await resolveLocalCompiler(workspaceFolder);
}
if (!serverPath) {
const executable = process.platform === "win32" ? "tsp-server.cmd" : "tsp-server";
return { command: executable, args, options };
}
const variableResolver = new VSCodeVariableResolver({
workspaceFolder,
workspaceRoot: workspaceFolder, // workspaceRoot is deprecated but we still support it for backwards compatibility.
});
serverPath = variableResolver.resolve(serverPath);
if (!serverPath.endsWith(".js")) {
// Allow path to tsp-server.cmd to be passed.
if (await isFile(serverPath)) {
const command =
process.platform === "win32" && !serverPath.endsWith(".cmd")
? `${serverPath}.cmd`
: "tsp-server";
return { command, args, options };
} else {
serverPath = join(serverPath, "cmd/tsp-server.js");
}
}
options.env["TYPESPEC_SKIP_COMPILER_RESOLVE"] = "1";
return { command: "node", args: [serverPath, ...args], options };
}
async function resolveLocalCompiler(baseDir: string): Promise<string | undefined> {
// dynamic import required when unbundled as this module is CommonJS for
// VS Code and the module-resolver is an ES module.
const { resolveModule } = await import("@typespec/compiler/module-resolver");
const host: ResolveModuleHost = {
realpath,
readFile: (path: string) => readFile(path, "utf-8"),
stat,
};
try {
const executable = await resolveModule(host, "@typespec/compiler", {
baseDir,
});
if (executable.type === "module") {
return executable.path;
}
} catch (e) {
// Couldn't find the module
}
return undefined;
}
async function isFile(path: string) {
try {
const stats = await stat(path);
return stats.isFile();
} catch {
return false;
}
}
export async function deactivate() {
await client?.stop();
}
/**
* Resolve some of the VSCode variables.
* Simpler aLternative until https://github.com/microsoft/vscode/issues/46471 is supported.
*/
class VSCodeVariableResolver {
static readonly VARIABLE_REGEXP = /\$\{(.*?)\}/g;
public constructor(private variables: Record<string, string>) {}
public resolve(value: string): string {
const replaced = value.replace(
VSCodeVariableResolver.VARIABLE_REGEXP,
(match: string, variable: string) => {
return this.variables[variable] ?? match;
}
);
return replaced;
}
}