Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(codemirror): cover the TypeScript extensions to 100%
Elian Doran84c475d2c391
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex 9315e61a53..c6cc10a731 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -665,6 +665,33 @@ describe("CodeMirror", () => {await editor.setMimeType("text/css");expect(buildMock).toHaveBeenCalledTimes(3);});++ it("keeps a newer build when an older one fails after it", async () => {+ const buildMock = vi.mocked(buildTypeCompletion);+ let failOlder: (error: Error) => void = () => {};+ buildMock.mockReturnValueOnce(new Promise((_resolve, reject) => { failOlder = reject; }));+ buildMock.mockResolvedValue({ extensions: [], complete: null });+ editor = build();++ const older = editor.setMimeType("text/jsx");+ await editor.setMimeType("text/css");+ failOlder(new Error("no language service"));+ await expect(older).rejects.toThrow("no language service");++ await editor.setMimeType("text/css");+ expect(buildMock).toHaveBeenCalledTimes(2);+ });++ it("builds the completion again after a build failed", async () => {+ const buildMock = vi.mocked(buildTypeCompletion);+ buildMock.mockRejectedValueOnce(new Error("no language service"));+ buildMock.mockResolvedValue({ extensions: [], complete: null });+ editor = build();++ await expect(editor.setMimeType("text/jsx")).rejects.toThrow("no language service");+ await editor.setMimeType("text/jsx");+ expect(buildMock).toHaveBeenCalledTimes(2);+ });});describe("concurrent MIME changes", () => {diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.tsnew file mode 100644index 0000000000..67193d5dff--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.spec.ts@@ -0,0 +1,48 @@+import type { VirtualTypeScriptEnvironment } from "@typescript/vfs";+import type ts from "typescript";+import { describe, expect, it } from "vitest";++import { getAutocompletion } from "./autocomplete.js";++/** An environment whose language service answers every position with `info`. */+function answering(info: Partial<ts.CompletionInfo> | undefined) {+ return {+ languageService: { getCompletionsAtPosition: () => info }+ } as unknown as VirtualTypeScriptEnvironment;+}++function entry(name: string, kind: string, sortText: string, kindModifiers?: string) {+ return { name, kind, sortText, kindModifiers } as ts.CompletionEntry;+}++describe("getAutocompletion", () => {+ it("maps the language service's entries to completions, leaving out warnings and deprecated ones", async () => {+ const completions = await getAutocompletion({+ env: answering({+ entries: [+ entry("getNote", "method", "11", ""),+ entry("noteId", "member", "11", ""),+ entry("Note", "alias", "15", ""),+ entry("untyped", "", "15", ""),+ entry("unranked", "var", "not a number"),+ entry("typo", "warning", "15", ""),+ entry("escape", "function", "15", "deprecated,declare")+ ]+ }),+ path: "/script.js",+ pos: 0+ });++ expect(completions).toEqual([+ { label: "getNote", type: "method", boost: -11 },+ { label: "noteId", type: "property", boost: -11 },+ { label: "Note", type: undefined, boost: -15 },+ { label: "untyped", type: undefined, boost: -15 },+ { label: "unranked", type: undefined, boost: 0 }+ ]);+ });++ it("offers nothing where the language service has nothing", async () => {+ expect(await getAutocompletion({ env: answering(undefined), path: "/script.js", pos: 0 })).toBe(null);+ });+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.tsindex 9c0edcde74..73d01d5ff2 100644--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts@@ -18,9 +18,7 @@ export async function getAutocompletion({env: VirtualTypeScriptEnvironment;path: string;pos: number;-}): Promise<Completion[] | null> {- if (!env.getSourceFile(path)) return null;-+}): Promise<(Completion & { boost: number })[] | null> {const completionInfo = env.languageService.getCompletionsAtPosition(path,pos,@@ -36,7 +34,7 @@ export async function getAutocompletion({!TS_COMPLETE_BLOCKLIST.includes(entry.kind) &&!entry.kindModifiers?.split(",").includes(ts.ScriptElementKindModifier.deprecatedModifier),)- .map((entry): Completion => {+ .map((entry): Completion & { boost: number } => {const boost = -Number(entry.sortText) || 0;let type = entry.kind ? String(entry.kind) : undefined;diff --git a/packages/codemirror/src/type_completion/codemirror-ts/environment.ts b/packages/codemirror/src/type_completion/codemirror-ts/environment.tsdeleted file mode 100644index ca14268694..0000000000--- a/packages/codemirror/src/type_completion/codemirror-ts/environment.ts+++ /dev/null@@ -1,70 +0,0 @@-import { combineConfig, type EditorState, Facet } from "@codemirror/state";-import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";-import type ts from "@typescript/vfs";-import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";--/**- * This is how the ts-related extensions are- * configured: this facet sets the path of the file- * and the environment to use, and the rest of- * the extensions, tsSync, tsLinter and tsHover,- * pull those settings automatically from editor state.- */-export const tsFacet = Facet.define<- {- path: string;- env: ts.VirtualTypeScriptEnvironment;- },- {- path: string;- env: ts.VirtualTypeScriptEnvironment;- } | null->({- combine(configs) {- return combineConfig(configs, {});- },-});--/**- * Sync updates from CodeMirror to the TypeScript- * virtual environment. Note that this updates a file - it isn't- * responsible (yet) for deleting or renaming files if they- * do get deleted or renamed.- */-export function tsSync() {- // The plugin is constructed whenever it joins an editor, at creation or through a- // reconfiguration, so the document the editor already holds is synced then.- return ViewPlugin.fromClass(class {- constructor(view: EditorView) {- syncDocument(view.state);- }-- update(update: ViewUpdate) {- if (update.docChanged) syncDocument(update.state);- }- });-}--function syncDocument(state: EditorState) {- const config = state.facet(tsFacet);- if (!config) return;- createOrUpdateFile(config.env, config.path, state.doc.toString() || ' ');-}--/**- * In TypeScript, updates are not like PUTs, you- * need to create a file before updating it.- *- * This method lets us treat the two as the same.- */-export function createOrUpdateFile(- env: VirtualTypeScriptEnvironment,- path: string,- code: string,-): void {- if (!env.getSourceFile(path)) {- env.createFile(path, code);- } else {- env.updateFile(path, code);- }-}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover.spec.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover.spec.tsnew file mode 100644index 0000000000..e9ed37b63a--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover.spec.ts@@ -0,0 +1,49 @@+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { describe, expect, it, vi } from "vitest";++import { createEnv, SCRIPT_MIME_BACKEND, scriptPath } from "../index.js";+import { getHover, hoverSource } from "./hover.js";++// Loading TypeScript and the bundled lib.*.d.ts the first time is not instant.+const TIMEOUT = 30_000;++/** A backend script's language service holding `code`. */+async function scriptHolding(code: string) {+ const env = await createEnv(SCRIPT_MIME_BACKEND);+ const path = scriptPath(SCRIPT_MIME_BACKEND);+ env.updateFile(path, code);+ return { env, path };+}++describe("getHover", () => {+ it("returns the quick info under the position, with no definition lookups", async () => {+ const { env, path } = await scriptHolding("api.log(\"x\");");+ const typeDefinition = vi.spyOn(env.languageService, "getTypeDefinitionAtPosition");+ const definition = vi.spyOn(env.languageService, "getDefinitionAtPosition");++ const hover = getHover({ env, path, pos: 5 });+ expect(hover).toMatchObject({ start: 4, end: 7 });+ expect(hover?.quickInfo?.displayParts?.map((part) => part.text).join("")).toContain("log");+ expect(typeDefinition).not.toHaveBeenCalled();+ expect(definition).not.toHaveBeenCalled();+ }, TIMEOUT);+});++describe("hoverSource", () => {+ it("shows what the renderer builds over the symbol, and nothing where there is none", async () => {+ const { env, path } = await scriptHolding("api.log(\"x\");\n\n");+ const dom = document.createElement("div");+ const renderTooltip = vi.fn(() => ({ dom }));+ const view = new EditorView({ state: EditorState.create({ doc: "api.log(\"x\");\n\n" }) });+ const source = hoverSource({ env, path, renderTooltip });++ const tooltip = source(view, 5);+ expect(tooltip).toMatchObject({ pos: 4, end: 7 });+ expect(tooltip?.create(view)).toEqual({ dom });+ expect(renderTooltip).toHaveBeenCalledWith(expect.objectContaining({ start: 4, end: 7 }), view);++ expect(source(view, 14)).toBe(null);+ view.destroy();+ }, TIMEOUT);+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover.tsindex 82ad985935..3314b9076e 100644--- a/packages/codemirror/src/type_completion/codemirror-ts/hover.ts+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover.ts@@ -1,26 +1,26 @@import { EditorView, hoverTooltip, Tooltip, TooltipView } from "@codemirror/view";import type ts from "typescript";import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";-import { tsFacet } from "./environment.js";++interface HoverOptions {+ env: VirtualTypeScriptEnvironment;+ path: string;+ renderTooltip: TooltipRenderer;+}/*** This binds the CodeMirror `hoverTooltip` method* with a code that pulls types and documentation* from the TypeScript environment.*/-export function tsHover({- renderTooltip = defaultRenderer,-}: {- renderTooltip?: TooltipRenderer;-} = {}) {- return hoverTooltip(async (view, pos): Promise<Tooltip | null> => {- const config = view.state.facet(tsFacet);- if (!config) return null;+export function tsHover(options: HoverOptions) {+ return hoverTooltip(hoverSource(options));+}- const hoverData = getHover({- ...config,- pos,- });+/** The tooltip `tsHover()` shows at a position, or `null` where the language service has none. */+export function hoverSource({ env, path, renderTooltip }: HoverOptions) {+ return (view: EditorView, pos: number): Tooltip | null => {+ const hoverData = getHover({ env, path, pos });if (!hoverData) return null;@@ -29,7 +29,7 @@ export function tsHover({end: hoverData.end,create: () => renderTooltip(hoverData, view),};- });+ };}/**@@ -67,21 +67,3 @@ export type TooltipRenderer = (arg0: HoverInfo,editorView: EditorView,) => TooltipView;--/**- * Default, barebones tooltip renderer. Generates- * structure of a div, containing a series of- * span elements with the typescript `kind` as- * classes.- */-export const defaultRenderer: TooltipRenderer = (info: HoverInfo) => {- const div = document.createElement("div");- if (info.quickInfo?.displayParts) {- for (let part of info.quickInfo.displayParts) {- const span = div.appendChild(document.createElement("span"));- span.className = `quick-info-${part.kind}`;- span.innerText = part.text;- }- }- return { dom: div };-};diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint.spec.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint.spec.tsnew file mode 100644index 0000000000..4b1aaed860--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint.spec.ts@@ -0,0 +1,44 @@+import { diagnosticCount, forceLinting, forEachDiagnostic } from "@codemirror/lint";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import ts from "typescript";+import { describe, expect, it } from "vitest";++import { createEnv, SCRIPT_MIME_BACKEND, scriptPath } from "../index.js";+import { tsCategoryToSeverity, tsLinter } from "./lint.js";++// Loading TypeScript and the bundled lib.*.d.ts the first time is not instant.+const TIMEOUT = 30_000;++describe("tsLinter", () => {+ it("underlines the script's diagnostics in the editor, minus the ignored codes", async () => {+ const env = await createEnv(SCRIPT_MIME_BACKEND);+ const path = scriptPath(SCRIPT_MIME_BACKEND);+ const doc = "const count = 1;\ncount.toUpperCase();\nreturn;";+ env.updateFile(path, doc);+ // TS1108, a top-level `return`, is valid in a script note's function wrapper.+ const view = new EditorView({+ state: EditorState.create({ doc, extensions: tsLinter({ env, path, diagnosticCodesToIgnore: [ 1108 ] }) })+ });++ forceLinting(view);+ await expect.poll(() => diagnosticCount(view.state)).toBe(1);+ forEachDiagnostic(view.state, (diagnostic, from, to) => {+ expect(doc.slice(from, to)).toBe("toUpperCase");+ expect(diagnostic.severity).toBe("error");+ });+ view.destroy();+ }, TIMEOUT);+});++describe("tsCategoryToSeverity", () => {+ it("maps TypeScript's categories to CodeMirror's, and unreachable code to a warning", () => {+ const severity = (category: ts.DiagnosticCategory, code = 2322) => tsCategoryToSeverity({ category, code });++ expect(severity(ts.DiagnosticCategory.Error)).toBe("error");+ expect(severity(ts.DiagnosticCategory.Warning)).toBe("warning");+ expect(severity(ts.DiagnosticCategory.Message)).toBe("info");+ expect(severity(ts.DiagnosticCategory.Suggestion)).toBe("info");+ expect(severity(ts.DiagnosticCategory.Error, 7027)).toBe("warning");+ });+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint.tsindex 535020b8d2..925521cf40 100644--- a/packages/codemirror/src/type_completion/codemirror-ts/lint.ts+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint.ts@@ -2,7 +2,6 @@ import { linter, Diagnostic } from "@codemirror/lint";import ts from "typescript";import type { DiagnosticWithLocation } from "typescript";import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";-import { tsFacet } from "./environment.js";/*** Binds the TypeScript `lint()` method with TypeScript's@@ -10,18 +9,12 @@ import { tsFacet } from "./environment.js";* the `getLints` method for a lower-level interface* to the same data.*/-export function tsLinter({- diagnosticCodesToIgnore,-}: { diagnosticCodesToIgnore?: number[] } = {}) {- return linter(async (view): Promise<readonly Diagnostic[]> => {- const config = view.state.facet(tsFacet);- return config- ? getLints({- ...config,- diagnosticCodesToIgnore: diagnosticCodesToIgnore || [],- })- : [];- });+export function tsLinter(options: {+ env: VirtualTypeScriptEnvironment;+ path: string;+ diagnosticCodesToIgnore: number[];+}) {+ return linter(() => getLints(options));}/**@@ -40,10 +33,6 @@ export function getLints({path: string;diagnosticCodesToIgnore: number[];}) {- // Don't crash if the relevant file isn't created yet.- const exists = env.getSourceFile(path);- if (!exists) return [];-const syntaticDiagnostics = env.languageService.getSyntacticDiagnostics(path);const semanticDiagnostics = env.languageService.getSemanticDiagnostics(path);diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.tsindex 3153f8d346..3c5b199ede 100644--- a/packages/codemirror/src/type_completion/index.spec.ts+++ b/packages/codemirror/src/type_completion/index.spec.ts@@ -1,11 +1,10 @@import { Compartment, EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";-import { createOrUpdateFile, tsFacet } from "./codemirror-ts/environment.js";-import { getHover } from "./codemirror-ts/hover.js";import {buildTypeCompletion,+ createEnv,getScriptCompletions,getScriptDiagnosticCodes,getScriptLints,@@ -13,7 +12,9 @@ import {SCRIPT_MIME_BACKEND,SCRIPT_MIME_FRONTEND,SCRIPT_MIME_JSX,- type ScriptApiContext+ type ScriptApiContext,+ scriptPath,+ tsSync} from "./index.js";/** Returns completions at the `|` marker in `source` (the marker is stripped). */@@ -33,11 +34,11 @@ async function completeAtMarker(mime: string, source: string) {const offset = source.indexOf("|");const code = source.slice(0, offset) + source.slice(offset + 1);const { extensions, complete } = await buildTypeCompletion(mime);- // No editor view syncs the document here, so the test writes it into the environment.- const config = EditorState.create({ extensions }).facet(tsFacet);- expect(config).toBeTruthy();- if (config) createOrUpdateFile(config.env, config.path, code);- return (await complete?.(offset))?.map((entry) => entry.label) ?? [];+ // The editor's `tsSync()` puts the document in the language service, as in the app.+ const view = new EditorView({ state: EditorState.create({ doc: code, extensions }) });+ const labels = (await complete?.(offset))?.map((entry) => entry.label) ?? [];+ view.destroy();+ return labels;}/** "Property 'x' does not exist on type 'y'." */@@ -551,6 +552,13 @@ describe("buildTypeCompletion", () => {expect(labels).toEqual(expect.arrayContaining([ "api", "console", "const", "return" ]));}, TIMEOUT);+ it("offers nothing inside a comment", async () => {+ const { extensions, complete } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);+ const view = new EditorView({ state: EditorState.create({ doc: "// api", extensions }) });+ expect(await complete?.(6)).toBe(null);+ view.destroy();+ }, TIMEOUT);+it("leaves deprecated names out", async () => {const labels = await completeAtMarker(SCRIPT_MIME_FRONTEND, "e|");expect(labels).toContain("encodeURI");@@ -560,44 +568,28 @@ describe("buildTypeCompletion", () => {});describe("tsSync", () => {- /** The text the language service holds for the editor's script. */- function synced(view: EditorView) {- const config = view.state.facet(tsFacet);- return config?.env.getSourceFile(config.path)?.text;- }+ it("syncs the document from the moment the editor has the plugin, then every change", async () => {+ const env = await createEnv(SCRIPT_MIME_BACKEND);+ const path = scriptPath(SCRIPT_MIME_BACKEND);+ const synced = () => env.getSourceFile(path)?.text;- it("syncs the document from the moment the editor has the extensions, then every change", async () => {- const { extensions } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);-- const created = new EditorView({ state: EditorState.create({ doc: "const a = 1;", extensions }) });- expect(synced(created)).toBe("const a = 1;");+ const created = new EditorView({ state: EditorState.create({ doc: "const a = 1;", extensions: tsSync(env, path) }) });+ expect(synced()).toBe("const a = 1;");created.dispatch({ changes: { from: 0, insert: "// note\n" } });- expect(synced(created)).toBe("// note\nconst a = 1;");+ expect(synced()).toBe("// note\nconst a = 1;");created.destroy();- // As the editor adds them: to a document it already holds, through a compartment.+ // As the editor adds it: to a document it already holds, through a compartment.const compartment = new Compartment();const added = new EditorView({ state: EditorState.create({ doc: "let b;", extensions: compartment.of([]) }) });- added.dispatch({ effects: compartment.reconfigure(extensions) });- expect(synced(added)).toBe("let b;");+ added.dispatch({ effects: compartment.reconfigure(tsSync(env, path)) });+ expect(synced()).toBe("let b;");added.destroy();- }, TIMEOUT);-});-describe("getHover", () => {- it("returns the quick info under the position, with no definition lookups", async () => {- const { extensions } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);- const config = EditorState.create({ extensions }).facet(tsFacet);- if (!config) throw new Error("expected the TypeScript facet");- createOrUpdateFile(config.env, config.path, "api.log(\"x\");");- const typeDefinition = vi.spyOn(config.env.languageService, "getTypeDefinitionAtPosition");- const definition = vi.spyOn(config.env.languageService, "getDefinitionAtPosition");-- const hover = getHover({ ...config, pos: 5 });- expect(hover).toMatchObject({ start: 4, end: 7 });- expect(hover?.quickInfo?.displayParts?.map((part) => part.text).join("")).toContain("log");- expect(typeDefinition).not.toHaveBeenCalled();- expect(definition).not.toHaveBeenCalled();+ // An empty document leaves a space, which the language service still reads as a script.+ const empty = new EditorView({ state: EditorState.create({ extensions: tsSync(env, path) }) });+ expect(synced()).toBe(" ");+ empty.destroy();}, TIMEOUT);});@@ -660,5 +652,6 @@ describe("empty script notes", () => {// space so TypeScript still gets a valid file to parse.expect(await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND, "")).toEqual([]);expect(await getScriptCompletions(SCRIPT_MIME_BACKEND, "", 0)).toEqual(expect.any(Array));+ expect(await getScriptLints(SCRIPT_MIME_BACKEND, "")).toEqual([]);}, TIMEOUT);});diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex 6daf0294d3..88698e5f41 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -1,5 +1,6 @@-import type { Extension } from "@codemirror/state";-import { EditorView } from "@codemirror/view";+import type { EditorState, Extension } from "@codemirror/state";+import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";+import type { VirtualTypeScriptEnvironment } from "@typescript/vfs";/*** Full IntelliSense for backend/frontend script notes.@@ -73,7 +74,7 @@ const BACKEND_GLOBALS_DTS_PATH = "/backend-globals.d.ts";const TRILIUM_MODULES_DTS_PATH = "/trilium-modules.d.ts";/** The virtual source-file path used for a given script MIME type. */-function scriptPath(mime: string): string {+export function scriptPath(mime: string): string {return mime === SCRIPT_MIME_JSX ? JSX_SCRIPT_PATH : SCRIPT_PATH;}@@ -99,7 +100,7 @@ const COMPILER_OPTIONS = {/** Cached lib.*.d.ts map; built once (see `createEnv`) and cloned per editor. */let cachedLibFilesMap: Map<string, string> | null = null;-async function createEnv(mime: string, context: ScriptApiContext = {}) {+export async function createEnv(mime: string, context: ScriptApiContext = {}) {const tsModule = await import("typescript");/* v8 ignore next -- typescript ships as CJS, so the interop namespace always carries`default`; the fallback only covers a future ESM-native build. */@@ -233,8 +234,7 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContex}const env = await createEnv(mime, context);- const [ environment, { getAutocompletion }, { tsLinter }, { tsHover } ] = await Promise.all([- import("./codemirror-ts/environment.js"),+ const [ { getAutocompletion }, { tsLinter }, { tsHover } ] = await Promise.all([import("./codemirror-ts/autocomplete.js"),import("./codemirror-ts/lint.js"),import("./codemirror-ts/hover.js")@@ -246,10 +246,9 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContexreturn {extensions: [- environment.tsFacet.of({ env, path }),- environment.tsSync(),- tsLinter({ diagnosticCodesToIgnore: ignoredDiagnosticCodes(mime) }),- tsHover({ renderTooltip: renderHoverTooltip }),+ tsSync(env, path),+ tsLinter({ env, path, diagnosticCodesToIgnore: ignoredDiagnosticCodes(mime) }),+ tsHover({ env, path, renderTooltip: renderHoverTooltip }),lintGutter(),hoverTheme],@@ -258,12 +257,31 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContexif (!options) return null;return options- .sort((a, b) => (b.boost ?? 0) - (a.boost ?? 0))+ .sort((a, b) => b.boost - a.boost).map(({ label, type }) => ({ label, type }));}};}+/**+ * Writes the editor's document into the script at `path`: when the plugin joins an editor, at its+ * creation or through a reconfiguration, and on every change after that.+ */+export function tsSync(env: VirtualTypeScriptEnvironment, path: string) {+ // An empty script reads as missing to `@typescript/vfs` (see `createEnv()`).+ const sync = (state: EditorState) => env.updateFile(path, state.doc.toString() || " ");++ return ViewPlugin.fromClass(class {+ constructor(view: EditorView) {+ sync(view.state);+ }++ update(update: ViewUpdate) {+ if (update.docChanged) sync(update.state);+ }+ });+}+/** Separates the JSDoc body/tags from the signature in the hover tooltip. */const hoverTheme = EditorView.baseTheme({".cm-ts-hover-doc": {