prettier_server.js

  1const { Buffer } = require("buffer");
  2const fs = require("fs");
  3const path = require("path");
  4const { once } = require("events");
  5
  6const prettierContainerPath = process.argv[2];
  7if (prettierContainerPath == null || prettierContainerPath.length == 0) {
  8  process.stderr.write(
  9    `Prettier path argument was not specified or empty.\nUsage: ${process.argv[0]} ${process.argv[1]} prettier/path\n`,
 10  );
 11  process.exit(1);
 12}
 13fs.stat(prettierContainerPath, (err, stats) => {
 14  if (err) {
 15    process.stderr.write(`Path '${prettierContainerPath}' does not exist\n`);
 16    process.exit(1);
 17  }
 18
 19  if (!stats.isDirectory()) {
 20    process.stderr.write(`Path '${prettierContainerPath}' exists but is not a directory\n`);
 21    process.exit(1);
 22  }
 23});
 24const prettierPath = path.join(prettierContainerPath, "node_modules/prettier");
 25
 26class Prettier {
 27  constructor(path, prettier, config) {
 28    this.path = path;
 29    this.prettier = prettier;
 30    this.config = config;
 31  }
 32}
 33
 34(async () => {
 35  let prettier;
 36  let config;
 37  try {
 38    prettier = await loadPrettier(prettierPath);
 39    config = (await prettier.resolveConfig(prettierPath)) || {};
 40  } catch (e) {
 41    process.stderr.write(`Failed to load prettier: ${e}\n`);
 42    process.exit(1);
 43  }
 44  process.stderr.write(`Prettier at path '${prettierPath}' loaded successfully, config: ${JSON.stringify(config)}\n`);
 45  process.stdin.resume();
 46  handleBuffer(new Prettier(prettierPath, prettier, config));
 47})();
 48
 49async function handleBuffer(prettier) {
 50  for await (const messageText of readStdin()) {
 51    let message;
 52    try {
 53      message = JSON.parse(messageText);
 54    } catch (e) {
 55      sendResponse(makeError(`Parse error in request message: ${e}\nMessage: ${messageText}`));
 56      continue;
 57    }
 58    // allow concurrent request handling by not `await`ing the message handling promise (async function)
 59    handleMessage(message, prettier).catch((e) => {
 60      if ((message.params || {}).text !== undefined) {
 61        message.params.text = "..snip..";
 62      }
 63      sendResponse({
 64        id: message.id,
 65        ...makeError(`${e}\nWhile handling prettier request: ${JSON.stringify(message)}`),
 66      });
 67    });
 68  }
 69}
 70
 71const headerSeparator = "\r\n";
 72const contentLengthHeaderName = "Content-Length";
 73
 74async function* readStdin() {
 75  let buffer = Buffer.alloc(0);
 76  let streamEnded = false;
 77  process.stdin.on("end", () => {
 78    streamEnded = true;
 79  });
 80  process.stdin.on("data", (data) => {
 81    buffer = Buffer.concat([buffer, data]);
 82  });
 83
 84  async function handleStreamEnded(errorMessage) {
 85    sendResponse(makeError(errorMessage));
 86    buffer = Buffer.alloc(0);
 87    messageLength = null;
 88    await once(process.stdin, "readable");
 89    streamEnded = false;
 90  }
 91
 92  try {
 93    let headersLength = null;
 94    let messageLength = null;
 95    main_loop: while (true) {
 96      if (messageLength === null) {
 97        while (buffer.indexOf(`${headerSeparator}${headerSeparator}`) === -1) {
 98          if (streamEnded) {
 99            await handleStreamEnded("Unexpected end of stream: headers not found");
100            continue main_loop;
101          } else if (buffer.length > contentLengthHeaderName.length * 10) {
102            await handleStreamEnded(
103              `Unexpected stream of bytes: no headers end found after ${buffer.length} bytes of input`,
104            );
105            continue main_loop;
106          }
107          await once(process.stdin, "readable");
108        }
109        const headers = buffer.subarray(0, buffer.indexOf(`${headerSeparator}${headerSeparator}`)).toString("ascii");
110        const contentLengthHeader = headers
111          .split(headerSeparator)
112          .map((header) => header.split(":"))
113          .filter((header) => header[2] === undefined)
114          .filter((header) => (header[1] || "").length > 0)
115          .find((header) => (header[0] || "").trim() === contentLengthHeaderName);
116        const contentLength = (contentLengthHeader || [])[1];
117        if (contentLength === undefined) {
118          await handleStreamEnded(`Missing or incorrect ${contentLengthHeaderName} header: ${headers}`);
119          continue main_loop;
120        }
121        headersLength = headers.length + headerSeparator.length * 2;
122        messageLength = parseInt(contentLength, 10);
123      }
124
125      while (buffer.length < headersLength + messageLength) {
126        if (streamEnded) {
127          await handleStreamEnded(
128            `Unexpected end of stream: buffer length ${buffer.length} does not match expected header length ${headersLength} + body length ${messageLength}`,
129          );
130          continue main_loop;
131        }
132        await once(process.stdin, "readable");
133      }
134
135      const messageEnd = headersLength + messageLength;
136      const message = buffer.subarray(headersLength, messageEnd);
137      buffer = buffer.subarray(messageEnd);
138      headersLength = null;
139      messageLength = null;
140      yield message.toString("utf8");
141    }
142  } catch (e) {
143    sendResponse(makeError(`Error reading stdin: ${e}`));
144  } finally {
145    process.stdin.off("data", () => {});
146  }
147}
148
149async function handleMessage(message, prettier) {
150  const { method, id, params } = message;
151  if (method === undefined) {
152    throw new Error(`Message method is undefined: ${JSON.stringify(message)}`);
153  } else if (method == "initialized") {
154    return;
155  }
156
157  if (id === undefined) {
158    throw new Error(`Message id is undefined: ${JSON.stringify(message)}`);
159  }
160
161  if (method === "prettier/format") {
162    if (params === undefined || params.text === undefined) {
163      throw new Error(`Message params.text is undefined: ${JSON.stringify(message)}`);
164    }
165    if (params.options === undefined) {
166      throw new Error(`Message params.options is undefined: ${JSON.stringify(message)}`);
167    }
168
169    let resolvedConfig = {};
170    if (params.options.filepath) {
171      resolvedConfig = (await prettier.prettier.resolveConfig(params.options.filepath)) || {};
172
173      if (params.options.ignorePath) {
174        const fileInfo = await prettier.prettier.getFileInfo(params.options.filepath, {
175          ignorePath: params.options.ignorePath,
176        });
177        if (fileInfo.ignored) {
178          process.stderr.write(
179            `Ignoring file '${params.options.filepath}' based on rules in '${params.options.ignorePath}'\n`,
180          );
181          sendResponse({ id, result: { text: params.text } });
182          return;
183        }
184      }
185    }
186
187    // Marking the params.options.filepath as undefined makes
188    // prettier.format() work even if no filepath is set.
189    if (params.options.filepath === null) {
190      params.options.filepath = undefined;
191    }
192
193    const plugins =
194      Array.isArray(resolvedConfig?.plugins) && resolvedConfig.plugins.length > 0
195        ? resolvedConfig.plugins
196        : params.options.plugins;
197
198    const options = {
199      ...(params.options.prettierOptions || prettier.config),
200      ...resolvedConfig,
201      plugins,
202      parser: params.options.parser,
203      filepath: params.options.filepath,
204    };
205    process.stderr.write(
206      `Resolved config: ${JSON.stringify(resolvedConfig)}, will format file '${
207        params.options.filepath || ""
208      }' with options: ${JSON.stringify(options)}\n`,
209    );
210    const formattedText = await prettier.prettier.format(params.text, options);
211    sendResponse({ id, result: { text: formattedText } });
212  } else if (method === "prettier/clear_cache") {
213    prettier.prettier.clearConfigCache();
214    prettier.config = (await prettier.prettier.resolveConfig(prettier.path)) || {};
215    sendResponse({ id, result: null });
216  } else if (method === "initialize") {
217    sendResponse({
218      id,
219      result: {
220        capabilities: {},
221      },
222    });
223  } else {
224    throw new Error(`Unknown method: ${method}`);
225  }
226}
227
228function makeError(message) {
229  return {
230    error: {
231      code: -32600, // invalid request code
232      message,
233    },
234  };
235}
236
237function sendResponse(response) {
238  const responsePayloadString = JSON.stringify({
239    jsonrpc: "2.0",
240    ...response,
241  });
242  const headers = `${contentLengthHeaderName}: ${Buffer.byteLength(
243    responsePayloadString,
244  )}${headerSeparator}${headerSeparator}`;
245  process.stdout.write(headers + responsePayloadString);
246}
247
248function loadPrettier(prettierPath) {
249  return new Promise((resolve, reject) => {
250    fs.access(prettierPath, fs.constants.F_OK, (err) => {
251      if (err) {
252        reject(`Path '${prettierPath}' does not exist.Error: ${err}`);
253      } else {
254        try {
255          resolve(require(prettierPath));
256        } catch (err) {
257          reject(`Error requiring prettier module from path '${prettierPath}'.Error: ${err}`);
258        }
259      }
260    });
261  });
262}