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
chore(codemirror): vendor @valtown/codemirror-ts
Elian Dorana4fac6a60ce9
diff --git a/eslint.format.config.mjs b/eslint.format.config.mjsindex eb9c367344..5f9e133b24 100644--- a/eslint.format.config.mjs+++ b/eslint.format.config.mjs@@ -45,6 +45,8 @@ export default defineConfig(// patches by matching upstream markup."packages/pdfjs-viewer/viewer/**","packages/splitjs/test/lib/**",+ // Copied from @valtown/codemirror-ts v2.3.1.+ "packages/codemirror/src/type_completion/codemirror-ts/**",// Generated by lezer-generator from the `.grammar` next to them."packages/codemirror/src/languages/mermaid/parsers/*/parser*.ts",// A worktree here is a full second copy of the repository.diff --git a/packages/codemirror/package.json b/packages/codemirror/package.jsonindex c108551846..6a739b32f6 100644--- a/packages/codemirror/package.json+++ b/packages/codemirror/package.json@@ -28,7 +28,6 @@"@codemirror/state": "6.7.6","@codemirror/view": "6.43.14","@typescript/vfs": "1.6.5",- "@valtown/codemirror-ts": "2.3.1","typescript": "6.0.3","@fsegurai/codemirror-theme-abcdef": "6.2.7","@fsegurai/codemirror-theme-abyss": "6.2.7",diff --git a/packages/codemirror/src/type_completion/codemirror-ts/LICENSE b/packages/codemirror/src/type_completion/codemirror-ts/LICENSEnew file mode 100644index 0000000000..ae71516426--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/LICENSE@@ -0,0 +1,15 @@+ISC License++Copyright (c) 2023, Val Town++Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above+copyright notice and this permission notice appear in all copies.++THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.tsnew file mode 100644index 0000000000..66d917cff9--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.test.ts@@ -0,0 +1,9 @@+import { test, expect } from "vitest";+import { ensureAnchor } from "./ensureAnchor.js";++test("ensureAnchor", () => {+ expect(ensureAnchor(/hi/, false)).toEqual(/(?:hi)$/);+ expect(ensureAnchor(/hi$/, false)).toEqual(/hi$/);+ expect(ensureAnchor(/hi$/, true)).toEqual(/^(?:hi$)/);+ expect(ensureAnchor(/^hi$/, true)).toEqual(/^hi$/);+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.tsnew file mode 100644index 0000000000..f0d48efbb1--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/ensureAnchor.ts@@ -0,0 +1,12 @@+// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L245+// TODO: do we need this, or can use import it from codemirror?+export function ensureAnchor(expr: RegExp, start: boolean) {+ let { source } = expr;+ let addStart = start && source[0] != "^",+ addEnd = source[source.length - 1] != "$";+ if (!addStart && !addEnd) return expr;+ return new RegExp(+ `${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`,+ expr.flags ?? (expr.ignoreCase ? "i" : ""),+ );+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.tsnew file mode 100644index 0000000000..5d4f07d918--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getAutocompletion.ts@@ -0,0 +1,85 @@+import type {+ CompletionContext,+ Completion,+ CompletionResult,+} from "@codemirror/autocomplete";+import ts from "typescript";+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";+import { AUTOCOMPLETION_SYMBOLS } from "./symbols.js";+import { DEFAULT_CODEMIRROR_TYPE_ICONS } from "./icons.js";+import { matchBefore } from "./matchBefore.js";++const TS_COMPLETE_BLOCKLIST: ts.ScriptElementKind[] = [+ ts.ScriptElementKind.warning,+];++export async function getAutocompletion({+ env,+ path,+ context,+ keepLegacyLimitationForAutocompletionSymbols = true,+}: {+ env: VirtualTypeScriptEnvironment;+ path: string;+ keepLegacyLimitationForAutocompletionSymbols?: boolean;+ /**+ * Allow this to be a subset of the full CompletionContext+ * object, because the raw object isn't serializable.+ */+ context: Pick<CompletionContext, "pos" | "explicit">;+}): Promise<CompletionResult | null> {+ const { pos, explicit } = context;+ const rawContents = env.getSourceFile(path)?.getFullText();++ if (!rawContents) return null;++ // If there's space behind the cursor, don't try and autocomplete.+ // https://codemirror.net/examples/autocompletion/+ let word = matchBefore(rawContents, pos, /\w*/);+ if (!word?.text) {+ word = matchBefore(rawContents, pos, /\./);+ }++ if (!word?.text && !explicit) return null;++ const completionInfo = env.languageService.getCompletionsAtPosition(+ path,+ pos,+ {},+ {},+ );++ // TODO: build ATA support for a 'loading' state+ // while types are being fetched+ if (!completionInfo) return null;++ const options = completionInfo.entries+ .filter(+ (entry) =>+ !TS_COMPLETE_BLOCKLIST.includes(entry.kind) &&+ (entry.sortText < "15" ||+ (completionInfo.optionalReplacementSpan?.length &&+ (!keepLegacyLimitationForAutocompletionSymbols || AUTOCOMPLETION_SYMBOLS.includes(entry.name)))),+ )+ .map((entry): Completion => {+ const boost = -Number(entry.sortText) || 0;+ let type = entry.kind ? String(entry.kind) : undefined;++ if (type === "member") type = "property";++ if (type && !DEFAULT_CODEMIRROR_TYPE_ICONS.has(type)) {+ type = undefined;+ }++ return {+ label: entry.name,+ type,+ boost,+ };+ });++ return {+ from: word ? (word.text === "." ? word.to : word.from) : pos,+ options,+ };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.tsnew file mode 100644index 0000000000..ef7e34a065--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.test.ts@@ -0,0 +1,28 @@+import { test, expect } from "vitest";+import { getLineAtPosition } from "./getLineAtPosition.js";++test("getLineAtPosition", () => {+ expect(getLineAtPosition("x", 0)).toEqual({+ from: 0,+ text: "x",+ to: 1,+ });++ expect(getLineAtPosition("x", 10)).toEqual({+ from: 0,+ text: "x",+ to: 1,+ });++ expect(getLineAtPosition("x", -10)).toEqual({+ from: 0,+ text: "x",+ to: 1,+ });++ expect(getLineAtPosition("first line\nsecond line", 12)).toEqual({+ from: 11,+ text: "second line",+ to: 22,+ });+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.tsnew file mode 100644index 0000000000..5940c707b4--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/getLineAtPosition.ts@@ -0,0 +1,20 @@+/**+ * TODO: confirm that this is necessary; it may be possible+ * and more efficient to get the line from CodeMirror, though+ * that would mean it probably doesn't mix well with the approach+ * of persisting code in the TS enviroment.+ */+export function getLineAtPosition(code: string, position: number) {+ // lineStart is the index of line break or zero+ const from = code.lastIndexOf("\n", position - 1) + 1;+ let to = code.indexOf("\n", position);+ if (to === -1) {+ to = code.length;+ }+ const text = code.slice(from, to);+ return {+ from,+ to,+ text,+ };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.tsnew file mode 100644index 0000000000..b917deb0ec--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/icons.ts@@ -0,0 +1,20 @@+/**+ * There is some overlap between CodeMirror's+ * types and TypeScripts. This is all of the default+ * icons for CodeMirror: if TypeScript gives us one+ * of these, we pass it through.+ */+export const DEFAULT_CODEMIRROR_TYPE_ICONS = new Set([+ `class`,+ `constant`,+ `enum`,+ `function`,+ `interface`,+ `keyword`,+ `method`,+ `namespace`,+ `property`,+ `text`,+ `type`,+ `variable`,+]);diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.tsnew file mode 100644index 0000000000..efc868f237--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.test.ts@@ -0,0 +1,11 @@+import { expect, test } from "vitest";+import { matchBefore } from "./matchBefore.js";++test("matchBefore", () => {+ expect(matchBefore("hi.", 0, /\./)).toEqual(null);+ expect(matchBefore("hi.", 3, /\./)).toEqual({+ from: 2,+ text: ".",+ to: 3,+ });+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.tsnew file mode 100644index 0000000000..8794fbcd93--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/matchBefore.ts@@ -0,0 +1,14 @@+import { ensureAnchor } from "./ensureAnchor.js";+import { getLineAtPosition } from "./getLineAtPosition.js";++// From: https://github.com/codemirror/autocomplete/blob/53cc58393252659ac4a86162b40afef13eeb2241/src/completion.ts#L111+// TODO: do we need to vendor this?+export function matchBefore(code: string, pos: number, expr: RegExp) {+ const line = getLineAtPosition(code, pos);+ let start = Math.max(line.from, pos - 250);+ let str = line.text.slice(start - line.from, pos - line.from);+ let found = str.search(ensureAnchor(expr, false));+ return found < 0+ ? null+ : { from: start + found, to: pos, text: str.slice(found) };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/symbols.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/symbols.tsnew file mode 100644index 0000000000..ac86e32f33--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/symbols.ts@@ -0,0 +1,70 @@+/**+ * TODO: honestly I don't know why this is here.+ */+export const AUTOCOMPLETION_SYMBOLS = [+ "Object",+ "Function",+ "Array",+ "Number",+ "parseFloat",+ "parseInt",+ "Infinity",+ "NaN",+ "undefined",+ "Boolean",+ "String",+ "Symbol",+ "Date",+ "Promise",+ "RegExp",+ "Error",+ "JSON",+ "Math",+ "Intl",+ "ArrayBuffer",+ "Atomics",+ "Uint8Array",+ "Int8Array",+ "Uint16Array",+ "Int16Array",+ "Uint32Array",+ "Int32Array",+ "Float32Array",+ "Float64Array",+ "Uint8ClampedArray",+ "BigUint64Array",+ "BigInt64Array",+ "DataView",+ "Map",+ "BigInt",+ "Set",+ "WeakMap",+ "WeakSet",+ "decodeURI",+ "decodeURIComponent",+ "encodeURI",+ "encodeURIComponent",+ "escape",+ "unescape",+ "isFinite",+ "isNaN",+ "Deno",+ "Blob",+ "FormData",+ "Request",+ "Response",+ "TextDecoder",+ "TextEncoder",+ "URL",+ "URLPattern",+ "URLSearchParams",+ "atob",+ "btoa",+ "crypto",+ "fetch",+ "clearInterval",+ "clearTimeout",+ "performance",+ "setInterval",+ "setTimeout",+];diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.tsnew file mode 100644index 0000000000..a22558a539--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete/tsAutocomplete.ts@@ -0,0 +1,25 @@+import type {+ CompletionContext,+ CompletionResult,+ CompletionSource,+} from "@codemirror/autocomplete";+import { getAutocompletion } from "./getAutocompletion.js";+import { tsFacet } from "../facet/tsFacet.js";++/**+ * Create a `CompletionSource` that queries+ * the _on-thread_ TypeScript environments for autocompletions+ * at this character.+ */+export function tsAutocomplete(): CompletionSource {+ return async (+ context: CompletionContext,+ ): Promise<CompletionResult | null> => {+ const config = context.state.facet(tsFacet);+ if (!config) return null;+ return getAutocompletion({+ ...config,+ context,+ });+ };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.ts b/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.tsnew file mode 100644index 0000000000..45ea18dd3f--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/facet/tsFacet.ts@@ -0,0 +1,26 @@+import { combineConfig, Facet } from "@codemirror/state";+import type ts 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, like tsLint and tsAutocomplete,+ * pull those settings automatically from editor state.+ */+export const tsFacet = Facet.define<+ {+ path: string;+ env: ts.VirtualTypeScriptEnvironment;+ keepLegacyLimitationForAutocompletionSymbols?: boolean;+ },+ {+ path: string;+ env: ts.VirtualTypeScriptEnvironment;+ keepLegacyLimitationForAutocompletionSymbols?: boolean;+ } | null+>({+ combine(configs) {+ return combineConfig(configs, {});+ },+});diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.tsnew file mode 100644index 0000000000..d2a7bcc65b--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover/getHover.ts@@ -0,0 +1,42 @@+import type ts from "typescript";+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";++/**+ * This information is passed to the API consumer to allow+ * them to create tooltips however they wish.+ */+export interface HoverInfo {+ start: number;+ end: number;+ typeDef: readonly ts.DefinitionInfo[] | undefined;+ quickInfo: ts.QuickInfo | undefined;+}++export function getHover({+ env,+ path,+ pos,+}: {+ env: VirtualTypeScriptEnvironment;+ path: string;+ pos: number;+}): HoverInfo | null {+ const sourcePos = pos;+ if (sourcePos === null) return null;++ const quickInfo = env.languageService.getQuickInfoAtPosition(path, sourcePos);+ if (!quickInfo) return null;++ const start = quickInfo.textSpan.start;++ const typeDef =+ env.languageService.getTypeDefinitionAtPosition(path, sourcePos) ??+ env.languageService.getDefinitionAtPosition(path, sourcePos);++ return {+ start,+ end: start + quickInfo.textSpan.length,+ typeDef,+ quickInfo,+ };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.tsnew file mode 100644index 0000000000..2c5f37c5fe--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover/renderTooltip.ts@@ -0,0 +1,25 @@+import { EditorView, TooltipView } from "@codemirror/view";+import { HoverInfo } from "./getHover.js";++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/hover/tsHover.ts b/packages/codemirror/src/type_completion/codemirror-ts/hover/tsHover.tsnew file mode 100644index 0000000000..6805379cea--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/hover/tsHover.ts@@ -0,0 +1,33 @@+import { hoverTooltip, Tooltip } from "@codemirror/view";+import { getHover } from "./getHover.js";+import { defaultRenderer, TooltipRenderer } from "./renderTooltip.js";+import { tsFacet } from "../facet/tsFacet.js";++/**+ * 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;++ const hoverData = getHover({+ ...config,+ pos,+ });++ if (!hoverData) return null;++ return {+ pos: hoverData.start,+ end: hoverData.end,+ create: () => renderTooltip(hoverData, view),+ };+ });+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.tsnew file mode 100644index 0000000000..8d6b534428--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint/getLints.ts@@ -0,0 +1,35 @@+import type { DiagnosticWithLocation } from "typescript";+import { convertTSDiagnosticToCM, isDiagnosticWithLocation } from "./utils.js";+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";++/**+ * Lower-level interface to get semantic and syntactic+ * diagnostics from the TypeScript environment.+ *+ * This is used by tsLinter and tsLinterWorker,+ * but you can use it directly to power other UI.+ */+export function getLints({+ env,+ path,+ diagnosticCodesToIgnore,+}: {+ env: VirtualTypeScriptEnvironment;+ 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);++ const diagnostics = [...syntaticDiagnostics, ...semanticDiagnostics].filter(+ (diagnostic): diagnostic is DiagnosticWithLocation =>+ isDiagnosticWithLocation(diagnostic) &&+ !diagnosticCodesToIgnore.includes(diagnostic.code),+ );++ return diagnostics.map(convertTSDiagnosticToCM);+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.tsnew file mode 100644index 0000000000..58891a89dc--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint/tsLinter.ts@@ -0,0 +1,23 @@+import { linter, Diagnostic } from "@codemirror/lint";+import { getLints } from "./getLints.js";+import { tsFacet } from "../facet/tsFacet.js";++/**+ * Binds the TypeScript `lint()` method with TypeScript's+ * semantic and syntactic diagnostics. You can use+ * 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 || [],+ })+ : [];+ });+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/lint/utils.ts b/packages/codemirror/src/type_completion/codemirror-ts/lint/utils.tsnew file mode 100644index 0000000000..d168029b39--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/lint/utils.ts@@ -0,0 +1,78 @@+import ts from "typescript";+import { type Diagnostic } from "@codemirror/lint";++/**+ * TypeScript has a set of diagnostic categories,+ * which maps roughly onto CodeMirror's categories.+ * Here, we do the mapping.+ */+export function tsCategoryToSeverity(+ diagnostic: Pick<ts.DiagnosticWithLocation, "category" | "code">,+): Diagnostic["severity"] {+ if (diagnostic.code === 7027) {+ // Unreachable code detected+ return "warning";+ }+ switch (diagnostic.category) {+ case ts.DiagnosticCategory.Error:+ return "error";+ case ts.DiagnosticCategory.Message:+ return "info";+ case ts.DiagnosticCategory.Warning:+ return "warning";+ case ts.DiagnosticCategory.Suggestion:+ return "info";+ }+}++/**+ * Not all TypeScript diagnostic relate to specific+ * ranges in source code: here we filter for those that+ * do.+ */+export function isDiagnosticWithLocation(+ diagnostic: ts.Diagnostic,+): diagnostic is ts.DiagnosticWithLocation {+ return !!(+ diagnostic.file &&+ typeof diagnostic.start === "number" &&+ typeof diagnostic.length === "number"+ );+}++/**+ * Get the message for a diagnostic. TypeScript+ * is kind of weird: messageText might have the message,+ * or a pointer to the message. This follows the chain+ * to get a string, regardless of which case we're in.+ */+export function tsDiagnosticMessage(+ diagnostic: Pick<ts.Diagnostic, "messageText">,+): string {+ if (typeof diagnostic.messageText === "string") {+ return diagnostic.messageText;+ }+ // TODO: go through linked list+ return diagnostic.messageText.messageText;+}++/**+ * TypeScript and CodeMirror have slightly different+ * ways of representing diagnostics. This converts+ * from one to the other.+ */+export function convertTSDiagnosticToCM(+ d: ts.DiagnosticWithLocation,+): Diagnostic {+ // We add some code at the end of the document, but we can't have a+ // diagnostic in an invalid range+ const start = d.start;+ const message = tsDiagnosticMessage(d);++ return {+ from: start,+ to: start + d.length,+ message: message,+ severity: tsCategoryToSeverity(d),+ };+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.ts b/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.tsnew file mode 100644index 0000000000..0e99ba9ee5--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/sync/tsSync.ts@@ -0,0 +1,26 @@+import { EditorView } from "@codemirror/view";+import { createOrUpdateFile } from "./update.js";+import { tsFacet } from "../facet/tsFacet.js";++/**+ * 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() {+ // TODO: this is a weak solution to the cold start problem.+ // If you boot up a CodeMirror instance, we want the initial+ // value to get loaded into CodeMirror. We do get a change event,+ // but it surprisingly doesn't have `docChanged: true` on it,+ // so this is a rough heuristic to just accept the first event+ // regardless of whether it looks significant.+ let first = true;+ return EditorView.updateListener.of((update) => {+ const config = update.view.state.facet(tsFacet);+ if (!config) return;+ if (!update.docChanged && !first) return;+ first = false;+ createOrUpdateFile(config.env, config.path, update.state.doc.toString() || ' ');+ });+}diff --git a/packages/codemirror/src/type_completion/codemirror-ts/sync/update.ts b/packages/codemirror/src/type_completion/codemirror-ts/sync/update.tsnew file mode 100644index 0000000000..844c0efec2--- /dev/null+++ b/packages/codemirror/src/type_completion/codemirror-ts/sync/update.ts@@ -0,0 +1,19 @@+import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";++/**+ * 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/index.ts b/packages/codemirror/src/type_completion/index.tsindex a5da7c795b..f92f010ab3 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -219,7 +219,13 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContex}const env = await createEnv(mime, context);- const { tsFacet, tsSync, tsAutocomplete, tsLinter, tsHover } = await import("@valtown/codemirror-ts");+ const [ { tsFacet }, { tsSync }, { tsAutocomplete }, { tsLinter }, { tsHover } ] = await Promise.all([+ import("./codemirror-ts/facet/tsFacet.js"),+ import("./codemirror-ts/sync/tsSync.js"),+ import("./codemirror-ts/autocomplete/tsAutocomplete.js"),+ import("./codemirror-ts/lint/tsLinter.js"),+ import("./codemirror-ts/hover/tsHover.js")+ ]);// `tsLinter` only underlines diagnostics inline; `lintGutter` adds the// error/warning markers in the gutter (as the old ESLint integration did).const { lintGutter } = await import("@codemirror/lint");diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d16a0cb46f..a842c48d55 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1291,9 +1291,6 @@ importers:'@typescript/vfs':specifier: 1.6.5version: 1.6.5([email protected])([email protected])- '@valtown/codemirror-ts':- specifier: 2.3.1- version: 2.3.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])codemirror-lang-elixir:specifier: 4.0.1version: 4.0.1@@ -5449,14 +5446,6 @@ packages:'@upsetjs/[email protected]':resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}- '@valtown/[email protected]':- resolution: {integrity: sha512-v5XiI4WA+bUy0XDgkrqZksqBWgIUeyLZuC94Px/rhXBph8ASmVXaimlGDtt0vH/9t8aDdIZYdr59r9H3oKMFOg==}- peerDependencies:- '@codemirror/autocomplete': 6.20.3- '@codemirror/lint': 6.9.7- '@codemirror/state': 6.7.6- '@codemirror/view': 6.43.14-'@vercel/[email protected]':resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==}engines: {node: '>= 20'}@@ -17048,13 +17037,6 @@ snapshots:d3-selection: 3.0.0d3-transition: 3.0.1([email protected])- '@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':- dependencies:- '@codemirror/autocomplete': 6.20.3- '@codemirror/lint': 6.9.7- '@codemirror/state': 6.7.6- '@codemirror/view': 6.43.14-'@vercel/[email protected]': {}'@vitest/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':