Skip to content
Merged
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
3 changes: 2 additions & 1 deletion packages/typescript/src/api/async/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ import type {
UnionType,
} from "./types.ts";

export { formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts";
export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts";
export { sortAndDeduplicateDiagnostics } from "../diagnosticUtils.ts";
export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts";
export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind };
export type {
Expand Down
3 changes: 2 additions & 1 deletion packages/typescript/src/api/diagnosticFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ function diagnosticPrefix(diagnostic: Diagnostic): string {
return diagnostic.source || "TS";
}

function flattenDiagnosticMessage(diagnostic: Diagnostic, newLine: string, indentLevel = 0): string {
/** Flattens a diagnostic and its message chain, indenting each nested message by two spaces. */
export function flattenDiagnosticMessage(diagnostic: Diagnostic, newLine: string, indentLevel = 0): string {
let result = "";
if (indentLevel) {
result += newLine + " ".repeat(indentLevel);
Expand Down
50 changes: 50 additions & 0 deletions packages/typescript/src/api/diagnosticUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Diagnostic } from "./proto.ts";

/**
* Returns a sorted copy, removing diagnostics with identical file names, ranges,
* codes, categories, sources, text, message chains, and related information.
* File names and localized text are compared case-sensitively. More elaborated
* message chains and related information sort first; distinct details are retained.
*/
export function sortAndDeduplicateDiagnostics<T extends Diagnostic>(diagnostics: readonly T[]): T[] {
const sorted = diagnostics.slice().sort(compareDiagnostics);
return sorted.filter((diagnostic, index) => index === 0 || compareDiagnostics(sorted[index - 1], diagnostic) !== 0);
}

function compareValues(a: string | number, b: string | number): number {
return a < b ? -1 : a > b ? 1 : 0;
}

function compareDiagnostics(a: Diagnostic, b: Diagnostic): number {
if (a === b) return 0;
return compareValues(a.fileName ?? "", b.fileName ?? "") ||
a.pos - b.pos ||
a.end - b.end ||
a.code - b.code ||
a.category - b.category ||
compareValues(a.source ?? "", b.source ?? "") ||
compareValues(a.text, b.text) ||
compareMessageChainSize(a.messageChain ?? [], b.messageChain ?? []) ||
compareDiagnosticLists(a.messageChain ?? [], b.messageChain ?? []) ||
compareDiagnosticLists(a.relatedInformation ?? [], b.relatedInformation ?? []);
}

function compareMessageChainSize(a: readonly Diagnostic[], b: readonly Diagnostic[]): number {
const result = b.length - a.length;
if (result) return result;
for (let i = 0; i < a.length; i++) {
const result = compareMessageChainSize(a[i].messageChain ?? [], b[i].messageChain ?? []);
if (result) return result;
}
return 0;
}

function compareDiagnosticLists(a: readonly Diagnostic[], b: readonly Diagnostic[]): number {
const result = b.length - a.length;
if (result) return result;
for (let i = 0; i < a.length; i++) {
const result = compareDiagnostics(a[i], b[i]);
if (result) return result;
}
return 0;
}
3 changes: 2 additions & 1 deletion packages/typescript/src/api/sync/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,8 @@ import type {
UnionType,
} from "./types.ts";

export { formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts";
export { flattenDiagnosticMessage, formatDiagnostics, formatDiagnosticsWithColorAndContext } from "../diagnosticFormatter.ts";
export { sortAndDeduplicateDiagnostics } from "../diagnosticUtils.ts";
export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts";
export { CheckFlags, CompletionItemKind, DiagnosticCategory, ElementFlags, EmitOnly, IndexKind, JsxEmit, ModifierFlags, ModuleKind, ModuleResolutionKind, NodeBuilderFlags, ObjectFlags, ScriptKind, SignatureFlags, SignatureKind, SymbolFlags, SymbolOwnerKind, TypeFlags, TypeFormatFlags, TypePredicateKind };
export type {
Expand Down
89 changes: 89 additions & 0 deletions packages/typescript/test/diagnosticFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,109 @@
import {
API,
type Diagnostic,
flattenDiagnosticMessage,
formatDiagnostics,
type FormatDiagnosticsHost,
formatDiagnosticsWithColorAndContext,
sortAndDeduplicateDiagnostics,
} from "@typescript/typescript/async";
import {
flattenDiagnosticMessage as flattenDiagnosticMessageSync,
sortAndDeduplicateDiagnostics as sortAndDeduplicateDiagnosticsSync,
} from "@typescript/typescript/sync";
import assert from "node:assert";
import {
describe,
test,
} from "node:test";
import { toRootedFilePath } from "../src/api/path.ts";
import {
areTestsFiltered,
createVirtualFileSystem,
} from "./testUtils.ts";

describe("sortAndDeduplicateDiagnostics", () => {
const diagnostic: Diagnostic = { pos: -1, end: -1, code: 1, category: 1, text: "Error" };

test("sorts by file, location, code, category, source, and text without mutating input", () => {
const firstFile = { ...diagnostic, fileName: toRootedFilePath("/A.ts", undefined), pos: 0, end: 1 };
const expected = [
diagnostic,
firstFile,
{ ...firstFile, text: "Other error" },
{ ...firstFile, source: "plugin" },
{ ...firstFile, category: 2 },
{ ...firstFile, code: 2 },
{ ...firstFile, end: 2 },
{ ...firstFile, pos: 1, end: 2 },
{ ...firstFile, fileName: toRootedFilePath("/a.ts", undefined) },
].map((item, index) => ({ ...item, index }));
const input = Object.freeze([...expected].reverse());
for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) {
const result = sort(input);
assert.deepEqual(result.map(item => item.index), expected.map(item => item.index));
assert.ok(result.every((item, index) => item === expected[index]));
assert.deepEqual(input, [...expected].reverse());
assert.deepEqual(sort([]), []);
assert.deepEqual(sort([diagnostic, structuredClone(diagnostic)]), [diagnostic]);
}
});

test("orders message chains by shape before content without dropping distinct chains", () => {
const child = { ...diagnostic, text: "Child" };
const shallow = { ...diagnostic, messageChain: [child] };
const deep = { ...diagnostic, messageChain: [{ ...child, text: "Z", messageChain: [child] }] };
const wide = { ...diagnostic, messageChain: [child, child] };
for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) {
assert.deepEqual(sort([diagnostic, shallow, deep]), [deep, shallow, diagnostic]);
assert.deepEqual(sort([deep, wide]), [wide, deep]);
const earlierText = { ...shallow, messageChain: [{ ...child, text: "A" }] };
assert.deepEqual(sort([shallow, earlierText]), [earlierText, shallow]);
const deeperSecondChild = {
...wide,
messageChain: [child, { ...child, messageChain: [child] }],
};
assert.deepEqual(sort([wide, deeperSecondChild]), [deeperSecondChild, wide]);
assert.deepEqual(sort([deep, structuredClone(deep)]), [deep]);
assert.deepEqual(sort([diagnostic, { ...diagnostic, messageChain: [] }]), [diagnostic]);
const differentCode = { ...shallow, messageChain: [{ ...child, code: 2 }] };
assert.equal(sort([shallow, differentCode]).length, 2);
}
});

test("orders related information without dropping distinct details and stably deduplicates", () => {
const related = { ...diagnostic, text: "Related" };
const detailed = { ...diagnostic, relatedInformation: [related] };
const moreDetailed = { ...diagnostic, relatedInformation: [related, related] };
const earlierRelated = { ...detailed, relatedInformation: [{ ...related, text: "Earlier" }] };
for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) {
assert.deepEqual(sort([diagnostic, detailed, moreDetailed]), [moreDetailed, detailed, diagnostic]);
assert.deepEqual(sort([detailed, earlierRelated]), [earlierRelated, detailed]);
const duplicate = structuredClone(detailed);
assert.equal(sort([detailed, duplicate])[0], detailed);
assert.equal(sort([duplicate, detailed])[0], duplicate);
}
});
});

describe("diagnosticFormatter", { concurrency: areTestsFiltered() }, () => {
test("flattens diagnostic message chains with configurable newlines and indentation", () => {
const diagnostic: Diagnostic = {
pos: -1,
end: -1,
code: 1,
category: 1,
text: "Root",
};
const child = { ...diagnostic, text: "Child", messageChain: [{ ...diagnostic, text: "Grandchild" }] };
const chained = { ...diagnostic, messageChain: [child, { ...diagnostic, text: "Sibling" }] };
for (const flatten of [flattenDiagnosticMessage, flattenDiagnosticMessageSync]) {
assert.equal(flatten(diagnostic, "\n"), "Root");
assert.equal(flatten(chained, "\r\n"), "Root\r\n Child\r\n Grandchild\r\n Sibling");
assert.equal(flatten(chained, "\n", 1), "\n Root\n Child\n Grandchild\n Sibling");
}
});

test("formats diagnostics with a configured program host", async () => {
const source = `const x: number = "oops";\n`;
const api = spawnAPI({
Expand Down