This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
messageProcessor.ts
246 lines (229 loc) · 7.7 KB
/
messageProcessor.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
import {
MessageReader,
MessageWriter,
StdoutWriter,
} from "./communication/mod.ts";
import {
ActiveMessage,
CancelFormatMessage,
DataResponseMessage,
ErrorResponseMessage,
FormatTextMessage,
GetConfigDiagnosticsMessage,
GetLicenseTextMessage,
GetPluginInfoMessage,
GetResolvedConfigMessage,
HostFormatMessage,
Message,
RegisterConfigMessage,
ReleaseConfigMessage,
ShutdownMessage,
SuccessResponseMessage,
} from "./communication/Message.ts";
import { ConfigContainer } from "./ConfigContainer.ts";
const decoder = new TextDecoder();
export interface PluginInfo {
name: string;
version: string;
configKey: string;
fileExtensions: string[];
helpUrl: string;
configSchemaUrl: string;
updateUrl: string;
}
export type JsonObject = Record<string, string | number | boolean>;
export interface ConfigDiagnostic {
propertyName: string;
message: string;
}
export interface ResolveConfigResult<TConfig> {
config: TConfig;
diagnostics: ConfigDiagnostic[];
}
export interface FormatRequest<TConfig> {
filePath: string;
fileText: string;
config: TConfig;
/// Range to format as a JS string position.
range: [number, number] | undefined;
signal: AbortSignal;
}
export interface PluginHandler<TConfig> {
pluginInfo(): PluginInfo;
licenseText(): string;
resolveConfig(
pluginConfig: JsonObject,
globalConfig: JsonObject,
): ResolveConfigResult<TConfig>;
formatText(request: FormatRequest<TConfig>): Promise<string>;
}
export async function startMessageProcessor<TConfig>(
plugin: PluginHandler<TConfig>,
) {
const reader = new MessageReader();
const writer = new MessageWriter();
await establishSchemaVersion(reader, writer);
const stdoutWriter = new StdoutWriter(writer);
const configContainer = new ConfigContainer((pluginConfig, globalConfig) => {
return plugin.resolveConfig(pluginConfig, globalConfig);
});
const abortControllers = new Map<number, AbortController>();
function tryActionSync(originalMessageId: number, action: () => void) {
try {
action();
} catch (err) {
stdoutWriter.sendError(originalMessageId, err);
}
}
function parseJsonObject(data: Uint8Array): JsonObject {
const obj = JSON.parse(decoder.decode(data)) as JsonObject;
if (typeof obj !== "object" || obj === null) {
throw new Error("Expected JSON object");
}
return obj;
}
while (true) {
const message = await Message.read(reader);
// order these by most common to least common
if (message instanceof FormatTextMessage) {
const _ignore = (async () => {
const controller = new AbortController();
abortControllers.set(message.messageId, controller);
const signal = controller.signal;
try {
const filePath = decoder.decode(message.filePath);
const fileText = decoder.decode(message.fileText);
const overrideConfig = message.overrideConfig == null
? undefined
: parseJsonObject(message.overrideConfig);
const config = configContainer.getResolvedConfig(
message.configId,
overrideConfig,
);
const range = getFormatTextRange(message, fileText);
const text = await plugin.formatText({
filePath,
fileText,
range,
config,
signal,
});
stdoutWriter.sendFormatTextResponse(message.messageId, text);
} catch (err) {
stdoutWriter.sendError(message.messageId, err);
} finally {
abortControllers.delete(message.messageId);
}
})();
} else if (message instanceof RegisterConfigMessage) {
tryActionSync(message.messageId, () => {
const globalConfig = parseJsonObject(message.globalConfigData);
const pluginConfig = parseJsonObject(message.pluginConfigData);
configContainer.set(message.configId, globalConfig, pluginConfig);
stdoutWriter.sendSuccessResponse(message.messageId);
});
} else if (message instanceof ReleaseConfigMessage) {
tryActionSync(message.messageId, () => {
configContainer.release(message.configId);
stdoutWriter.sendSuccessResponse(message.messageId);
});
} else if (message instanceof GetConfigDiagnosticsMessage) {
tryActionSync(message.messageId, () => {
const configDiagnostics = configContainer.getDiagnostics(
message.configId,
);
stdoutWriter.sendDataResponse(
message.messageId,
JSON.stringify(configDiagnostics),
);
});
} else if (message instanceof GetResolvedConfigMessage) {
tryActionSync(message.messageId, () => {
const resolvedConfig = configContainer.getResolvedConfig(
message.configId,
undefined,
);
stdoutWriter.sendDataResponse(
message.messageId,
JSON.stringify(resolvedConfig),
);
});
} else if (message instanceof CancelFormatMessage) {
try {
const controller = abortControllers.get(message.originalMessageId);
if (controller) {
controller.abort();
abortControllers.delete(message.originalMessageId);
}
} catch (err) {
// ignore, but surface the error
console.error(err);
}
} else if (message instanceof GetPluginInfoMessage) {
const pluginInfo = plugin.pluginInfo();
stdoutWriter.sendDataResponse(
message.messageId,
JSON.stringify(pluginInfo),
);
} else if (message instanceof GetLicenseTextMessage) {
const licenseText = plugin.licenseText();
stdoutWriter.sendDataResponse(message.messageId, licenseText);
} else if (message instanceof ShutdownMessage) {
// send a success acknowledgement
stdoutWriter.sendSuccessResponse(message.messageId);
// wait for the message to finish writing
await stdoutWriter.waitNotProcessing();
return; // done
} else if (message instanceof ActiveMessage) {
stdoutWriter.sendSuccessResponse(message.messageId);
} else if (message instanceof ErrorResponseMessage) {
// ignore
} else if (message instanceof SuccessResponseMessage) {
// ignore
} else if (message instanceof DataResponseMessage) {
// ignore
} else if (message instanceof HostFormatMessage) {
stdoutWriter.sendError(
message.messageId,
new Error("Cannot host format with a plugin."),
);
} else {
console.error("Unknown message.", message);
throw new Error("Unimplemented message kind.");
}
}
}
function getFormatTextRange(
message: FormatTextMessage,
fileText: string,
): [number, number] | undefined {
if (
message.startByteIndex === 0 &&
message.endByteIndex === message.fileText.length
) {
return undefined;
}
// we need to convert utf8 byte indexes to utf16 code unit indexes,
// so we do this absolutely terrible thing for performance because I'm not
// sure how to do this otherwise
const startIndex = message.startByteIndex === 0
? 0
: decoder.decode(message.fileText.slice(0, message.startByteIndex)).length;
const endIndex = message.endByteIndex === message.fileText.length
? fileText.length
: decoder.decode(message.fileText.slice(0, message.endByteIndex)).length;
return [startIndex, endIndex];
}
async function establishSchemaVersion(
reader: MessageReader,
writer: MessageWriter,
) {
// 1. An initial `0` (4 bytes) is sent asking for the schema version.
const request = await reader.readInt();
if (request != 0) {
throw new Error("Expected a schema version request of `0`.");
}
// 2. The client responds with `0` (4 bytes) for success, then `4` (4 bytes) for the schema version.
await writer.writeInt(0);
await writer.writeInt(4);
}