Skip to content

Build your personal knowledge base with Trilium Notes

fix(codemirror): type backend scripts without the DOM

Elian Doran3358caf327cd
diff --git a/packages/codemirror/src/type_completion/backend_globals.ts b/packages/codemirror/src/type_completion/backend_globals.ts
new file mode 100644
index 0000000000..4baf1b9871
--- /dev/null
+++ b/packages/codemirror/src/type_completion/backend_globals.ts
@@ -0,0 +1,152 @@
+// Global declarations for BACKEND script notes, which run in Node on the server and desktop and in
+// a Web Worker in standalone and mobile. Their vfs gets `lib: ["es2020"]` without `dom`, so this
+// declares what both runtimes have: the console, timers, URL, text encoding, `fetch()`,
+// `AbortController`, `structuredClone()`, base64 and `crypto`. Editor-only typing, not a runtime
+// contract: add a global here only once both runtimes provide it.
+export const backendGlobals = `
+interface Console {
+ log(...data: unknown[]): void;
+ info(...data: unknown[]): void;
+ warn(...data: unknown[]): void;
+ error(...data: unknown[]): void;
+ debug(...data: unknown[]): void;
+ trace(...data: unknown[]): void;
+ table(data: unknown): void;
+ time(label?: string): void;
+ timeEnd(label?: string): void;
+}
+declare var console: Console;
+
+/** A number in a Web Worker and a \`Timeout\` object in Node; only pass it back to \`clear…()\`. */
+type TimerHandle = unknown;
+declare function setTimeout(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): TimerHandle;
+declare function clearTimeout(handle: TimerHandle | undefined): void;
+declare function setInterval(handler: (...args: any[]) => void, timeout?: number, ...args: any[]): TimerHandle;
+declare function clearInterval(handle: TimerHandle | undefined): void;
+declare function queueMicrotask(callback: () => void): void;
+
+declare function structuredClone<T>(value: T): T;
+declare function atob(data: string): string;
+declare function btoa(data: string): string;
+
+interface URLSearchParams {
+ append(name: string, value: string): void;
+ delete(name: string): void;
+ get(name: string): string | null;
+ getAll(name: string): string[];
+ has(name: string): boolean;
+ set(name: string, value: string): void;
+ forEach(callback: (value: string, key: string) => void): void;
+ entries(): IterableIterator<[string, string]>;
+ keys(): IterableIterator<string>;
+ values(): IterableIterator<string>;
+ [Symbol.iterator](): IterableIterator<[string, string]>;
+ toString(): string;
+}
+declare var URLSearchParams: {
+ prototype: URLSearchParams;
+ new (init?: string | Record<string, string> | [string, string][]): URLSearchParams;
+};
+
+interface URL {
+ hash: string;
+ host: string;
+ hostname: string;
+ href: string;
+ readonly origin: string;
+ password: string;
+ pathname: string;
+ port: string;
+ protocol: string;
+ search: string;
+ readonly searchParams: URLSearchParams;
+ username: string;
+ toString(): string;
+ toJSON(): string;
+}
+declare var URL: {
+ prototype: URL;
+ new (url: string | URL, base?: string | URL): URL;
+};
+
+interface TextEncoder {
+ readonly encoding: string;
+ encode(input?: string): Uint8Array;
+}
+declare var TextEncoder: {
+ prototype: TextEncoder;
+ new (): TextEncoder;
+};
+
+interface TextDecoder {
+ readonly encoding: string;
+ decode(input?: ArrayBuffer | ArrayBufferView, options?: { stream?: boolean }): string;
+}
+declare var TextDecoder: {
+ prototype: TextDecoder;
+ new (label?: string, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder;
+};
+
+interface AbortSignal {
+ readonly aborted: boolean;
+ readonly reason: unknown;
+ throwIfAborted(): void;
+}
+declare var AbortSignal: {
+ prototype: AbortSignal;
+ abort(reason?: unknown): AbortSignal;
+ timeout(milliseconds: number): AbortSignal;
+};
+
+interface AbortController {
+ readonly signal: AbortSignal;
+ abort(reason?: unknown): void;
+}
+declare var AbortController: {
+ prototype: AbortController;
+ new (): AbortController;
+};
+
+interface Headers {
+ append(name: string, value: string): void;
+ delete(name: string): void;
+ get(name: string): string | null;
+ has(name: string): boolean;
+ set(name: string, value: string): void;
+ forEach(callback: (value: string, key: string) => void): void;
+ entries(): IterableIterator<[string, string]>;
+ [Symbol.iterator](): IterableIterator<[string, string]>;
+}
+type HeadersInit = Headers | Record<string, string> | [string, string][];
+declare var Headers: {
+ prototype: Headers;
+ new (init?: HeadersInit): Headers;
+};
+
+interface RequestInit {
+ method?: string;
+ headers?: HeadersInit;
+ body?: string | ArrayBuffer | ArrayBufferView | URLSearchParams | null;
+ signal?: AbortSignal | null;
+ redirect?: "follow" | "error" | "manual";
+}
+
+interface Response {
+ readonly ok: boolean;
+ readonly status: number;
+ readonly statusText: string;
+ readonly headers: Headers;
+ readonly url: string;
+ readonly redirected: boolean;
+ json(): Promise<any>;
+ text(): Promise<string>;
+ arrayBuffer(): Promise<ArrayBuffer>;
+}
+declare function fetch(input: string | URL, init?: RequestInit): Promise<Response>;
+
+interface Crypto {
+ randomUUID(): string;
+ getRandomValues<T extends ArrayBufferView | null>(array: T): T;
+}
+declare var crypto: Crypto;
+`;
diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.ts
index 79c87466b7..3153f8d346 100644
--- a/packages/codemirror/src/type_completion/index.spec.ts
+++ b/packages/codemirror/src/type_completion/index.spec.ts
@@ -52,6 +52,8 @@ const TS_TOP_LEVEL_AWAIT = 1375;
const TS_JQUERY_NOT_FOUND = 2592;
/** "Cannot find name 'x'." */
const TS_NAME_NOT_FOUND = 2304;
+/** "Cannot find name 'document'. Do you need to change your target library?…" (a DOM name) */
+const TS_DOM_NAME_NOT_FOUND = 2584;
/** "Unreachable code detected." — the one diagnostic rendered as a warning marker. */
const TS_UNREACHABLE_CODE = 7027;
@@ -130,6 +132,29 @@ describe("script note diagnostics", () => {
expect(codes).toContain(TS_JQUERY_NOT_FOUND);
}, TIMEOUT);
+ it("does not provide the DOM to backend scripts (Node and Web Workers have none)", async () => {
+ const codes = await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND, "const title = document.title;");
+ expect(codes).toContain(TS_DOM_NAME_NOT_FOUND);
+ }, TIMEOUT);
+
+ it("provides backend scripts the globals Node and Web Workers share", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_BACKEND,
+ "console.log('start'); console.error(new Error('x'));\n"
+ + "const timer = setTimeout(() => {}, 10); clearTimeout(timer);\n"
+ + "const ticker = setInterval(() => {}, 10); clearInterval(ticker);\n"
+ + "queueMicrotask(() => {});\n"
+ + "const url = new URL('https://example.com/?q=1'); url.searchParams.get('q');\n"
+ + "new URLSearchParams('a=1').toString();\n"
+ + "const bytes = new TextEncoder().encode('x'); new TextDecoder().decode(bytes);\n"
+ + "const controller = new AbortController();\n"
+ + "fetch('https://example.com', { method: 'POST', headers: { a: 'b' }, body: '{}', signal: controller.signal })\n"
+ + " .then((response) => response.ok ? response.json() : response.text());\n"
+ + "structuredClone({ a: 1 }); atob(btoa('x')); crypto.randomUUID();"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
it("provides the glob global to frontend scripts (member + note typing)", async () => {
const codes = await getScriptDiagnosticCodes(
SCRIPT_MIME_FRONTEND,
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index bf0a617d96..6daf0294d3 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -69,6 +69,7 @@ const API_GLOBALS_PATH = "/trilium-api.d.ts";
const API_TYPES_PATH = "/trilium-script-api.ts";
const JQUERY_DTS_PATH = "/jquery-globals.d.ts";
const GLOB_DTS_PATH = "/trilium-glob.d.ts";
+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. */
@@ -152,7 +153,8 @@ async function createEnv(mime: string, context: ScriptApiContext = {}) {
rootFiles.push(GLOB_DTS_PATH);
} else {
// Backend `api` types come from the same shared public surface in commons
- // (single source of truth, drift-guarded). No jQuery/DOM server-side.
+ // (single source of truth, drift-guarded). No jQuery or DOM: backend scripts run in Node
+ // and in a Web Worker, whose shared globals ./backend_globals declares.
const apiTypes = (await import("../../../commons/src/lib/script_api.ts?raw")).default;
fsMap.set(API_TYPES_PATH, apiTypes);
// `req`/`res`/`pathParams` only exist at runtime for custom request handlers,
@@ -163,6 +165,10 @@ async function createEnv(mime: string, context: ScriptApiContext = {}) {
const noteGlobal = context.bulkActionNote ? " var note: ScriptBNote;\n" : "";
fsMap.set(API_GLOBALS_PATH, `import type { BackendApi, ScriptBNote } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: ${apiType};\n${noteGlobal}}\n`);
rootFiles.push(API_TYPES_PATH);
+
+ const { backendGlobals } = await import("./backend_globals.js");
+ fsMap.set(BACKEND_GLOBALS_DTS_PATH, backendGlobals);
+ rootFiles.push(BACKEND_GLOBALS_DTS_PATH);
}
if (mime === SCRIPT_MIME_JSX) {
@@ -180,7 +186,7 @@ async function createEnv(mime: string, context: ScriptApiContext = {}) {
const compilerOptions = {
...COMPILER_OPTIONS,
target: ts.ScriptTarget.ES2020,
- lib: ["es2020", "dom"],
+ lib: isFrontendMime(mime) ? [ "es2020", "dom" ] : [ "es2020" ],
// The runtime uses the classic `h` transform, but we only type-check (never
// emit), so the automatic runtime is cleaner: it pulls `JSX.IntrinsicElements`
// from `preact/jsx-runtime`, giving real element/attribute typing without a