Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an LSP to be able communicate with editors #94

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
336 changes: 324 additions & 12 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@
"lz-string": "^1.5.0",
"prettier": "^2.8.8",
"ts-dedent": "^2.2.0",
"ts-node": "^10.9.2",
"vscode-languageclient": "^8.1.0",
"vscode-languageserver": "^9.0.1",
"vscode-languageserver-textdocument": "^1.0.11",
"vscode-languageserver-types": "^3.17.3",
"vscode-uri": "^3.0.7"
}
Expand Down
15 changes: 13 additions & 2 deletions src/components/codeBlock.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Output } from "../types";
import { d } from "../utils";
import { miniLine } from "./miniLine";
import { spanBreak } from "./spanBreak";
Expand All @@ -19,8 +20,18 @@ const codeBlock = (code: string, language: string) =>
</span>
`);

export const inlineCodeBlock = (code: string, language: string) =>
codeBlock(` ${code} `, language);
export const inlineCodeBlock = (
code: string,
language: string,
output: Output = "html"
) => {
switch (output) {
case "html":
return codeBlock(` ${code} `, language);
case "plaintext":
return code;
}
};

export const multiLineCodeBlock = (code: string, language: string) => {
const codeLines = code.split("\n");
Expand Down
46 changes: 30 additions & 16 deletions src/components/title.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,35 @@ import { Diagnostic } from "vscode-languageserver-types";
import { compressToEncodedURIComponent, d } from "../utils";
import { KNOWN_ERROR_NUMBERS } from "./consts/knownErrorNumbers";
import { miniLine } from "./miniLine";
import { Output } from "../types";

export const title = (diagnostic: Diagnostic) => d/*html*/ `
<span style="color:#f96363;">⚠ Error </span>${
typeof diagnostic.code === "number"
? d/*html*/ `
<span style="color:#5f5f5f;">
(TS${diagnostic.code})
${errorCodeExplanationLink(diagnostic.code)} |
${errorMessageTranslationLink(diagnostic.message)}
</span>
`
: ""
}
<br>
${miniLine}
export const title = (diagnostic: Diagnostic, output: Output = "html") => {
switch (output) {
case "html":
return d/*html*/ `
<span style="color:#f96363;">⚠ Error </span>${
typeof diagnostic.code === "number"
? d/*html*/ `
<span style="color:#5f5f5f;">
(TS${diagnostic.code})
${errorCodeExplanationLink(diagnostic.code, output)} |
${errorMessageTranslationLink(diagnostic.message, output)}
</span>
`
: ""
}
<br>
${miniLine}
`;
case "plaintext":
return d`${diagnostic.message}`;
}
};

export const errorCodeExplanationLink = (errorCode: Diagnostic["code"]) =>
export const errorCodeExplanationLink = (
errorCode: Diagnostic["code"],
output: Output = "html"
) =>
KNOWN_ERROR_NUMBERS.has(errorCode)
? d/*html*/ `
<a title="See detailed explanation" href="https://typescript.tv/errors/#ts${errorCode}">
Expand All @@ -28,7 +39,10 @@ export const errorCodeExplanationLink = (errorCode: Diagnostic["code"]) =>
</a>`
: "";

export const errorMessageTranslationLink = (message: Diagnostic["message"]) => {
export const errorMessageTranslationLink = (
message: Diagnostic["message"],
output: Output = "html"
) => {
const encodedMessage = compressToEncodedURIComponent(message);

return d/*html*/ `
Expand Down
14 changes: 11 additions & 3 deletions src/components/unStyledCodeBlock.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { inlineCodeBlock, multiLineCodeBlock } from "./codeBlock";
import { d } from "../utils";
import { Output } from "../types";

/**
* Code block without syntax highlighting like.
* For syntax highlighting, use {@link inlineCodeBlock} or {@link multiLineCodeBlock}
*/
export const unStyledCodeBlock = (content: string) => d/*html*/ `
<code>${content}</code>
`;
export const unStyledCodeBlock = (content: string, output: Output = "html") => {
switch (output) {
case "plaintext":
return d`'${content}'`;
case "html":
return d/*html*/ `
<code> ${content} </code>
`;
}
};
31 changes: 24 additions & 7 deletions src/format/formatDiagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,34 @@ import { d } from "../utils";
import { embedSymbolLinks } from "./embedSymbolLinks";
import { formatDiagnosticMessage } from "./formatDiagnosticMessage";
import { identSentences } from "./identSentences";
import { Output } from "../types";

export function formatDiagnostic(
diagnostic: Diagnostic,
format: (type: string) => string
format: (type: string) => string,
output: Output
) {
const newDiagnostic = embedSymbolLinks(diagnostic);

return d/*html*/ `
${title(diagnostic)}
<span>
${formatDiagnosticMessage(identSentences(newDiagnostic.message), format)}
</span>
`;
switch (output) {
case "html":
return d/*html*/ `
${title(diagnostic, output)}
<span>
${formatDiagnosticMessage(
identSentences(newDiagnostic.message),
format
)}
</span>
`;
case "plaintext":
return d`
${formatDiagnosticMessage(
identSentences(newDiagnostic.message),
format,
output
)}

`;
}
}
16 changes: 11 additions & 5 deletions src/format/formatDiagnosticMessage.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { inlineCodeBlock, unStyledCodeBlock } from "../components";
import { Output } from "../types";
import { formatTypeBlock } from "./formatTypeBlock";

const formatTypeScriptBlock = (_: string, code: string) =>
inlineCodeBlock(code, "typescript");
const formatTypeScriptBlock = (
_: string,
code: string,
output: Output = "html"
) => inlineCodeBlock(code, "typescript", output);

const formatSimpleTypeBlock = (_: string, code: string) =>
inlineCodeBlock(code, "type");

export const formatDiagnosticMessage = (
message: string,
format: (type: string) => string
format: (type: string) => string,
output: Output = "html"
) =>
message
.replaceAll(/(?:\s)'"(.*?)(?<!\\)"'(?:\s|\:|.|$)/g, (_, p1: string) =>
Expand Down Expand Up @@ -92,10 +97,11 @@ export const formatDiagnosticMessage = (
// Format return values
.replaceAll(
/(return|operator) ['“](.*?)['”]/gi,
(_, p1: string, p2: string) => `${p1} ${formatTypeScriptBlock("", p2)}`
(_, p1: string, p2: string) =>
`${p1} ${formatTypeScriptBlock("", p2, output)}`
)
// Format regular code blocks
.replaceAll(
/(?<!.*?")(?:^|\s)['“]((?:(?!:\s*}).)*?)['“](?!\s*:)(?!.*?")/g,
(_: string, p1: string) => ` ${unStyledCodeBlock(p1)} `
(_: string, p1: string) => `${unStyledCodeBlock(p1, output)}`
);
107 changes: 107 additions & 0 deletions src/lsp/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import {
createConnection,
InitializeResult,
TextDocumentSyncKind,
TextDocuments,
ProposedFeatures,
Diagnostic,
} from "vscode-languageserver/node";
import { TextDocument } from "vscode-languageserver-textdocument";
import * as fs from "fs";
import { formatDiagnostic } from "../format/formatDiagnostic";
import { prettify } from "../format/prettify";

const logStream = fs.createWriteStream("/tmp/lsp.log");
logStream.write("\n");

// Just for initial debugging purposes, will be removed when we have a proper release
const log = {
write: (message: object | unknown) => {
let finalMessage;
if (typeof message === "object") {
finalMessage = `${new Date().toISOString()} ${JSON.stringify(
message,
null,
4
)}`;
} else {
finalMessage = `${new Date().toISOString()} ${message}`;
}
finalMessage += "\n";

logStream.write(finalMessage);
console.log(finalMessage);
},
};

log.write(`started`);

const connection = createConnection(ProposedFeatures.all);

const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);

connection.onInitialize(() => {
log.write("initialize");

const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Incremental,
diagnosticProvider: {
identifier: "pretty-ts-errors",
interFileDependencies: false,
workspaceDiagnostics: false,
},
},
serverInfo: {
name: "pretty-ts-errors",
version: "0.5.3",
},
};

return result;
});

type FormatDiagnosticsParams = {
diagnostics: Diagnostic[];
uri: string;
};

const cache = new Map<string, string>();

connection.onRequest(
"pretty-ts-errors/formatDiagnostics",
({ diagnostics, uri }: FormatDiagnosticsParams) => {
const formattedDiagnostics = diagnostics
.filter((diagnostic) => !cache.has(diagnostic.message))
.map((diagnostic) => {
return {
...diagnostic,
message: formatDiagnostic(diagnostic, prettify, "plaintext"),
source: "pretty-ts-errors",
};
});

if (formattedDiagnostics.length === 0) {
return;
}

log.write(
"formattedDiagnostics: " + JSON.stringify(formattedDiagnostics, null, 2)
);

log.write("params: " + JSON.stringify(diagnostics, null, 2));

// connection.sendDiagnostics({
// uri,
// diagnostics: formattedDiagnostics,
// });

return {
uri,
diagnostics: formattedDiagnostics,
};
}
);

documents.listen(connection);
connection.listen();
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type Output = "html" | "plaintext";