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
feat(codemirror/autocomplete): filter out req and res based on customRequestHandler presence
Elian Doran021b875cee84
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex c327a63f1c..9559ac3403 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -9,7 +9,7 @@ import { CommandListenerData } from "../../../components/app_context";import FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";import utils from "../../../services/utils";-import { useColorScheme, useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteBlob, useNoteLabelInt, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import { useColorScheme, useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteBlob, useNoteLabel, useNoteLabelInt, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { refToJQuerySelector } from "../../react/react_utils";import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";import { TypeWidgetProps } from "../type_widget";@@ -99,6 +99,7 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentCconst [ noteTabWidth ] = useNoteLabelInt(note, "tabWidth");const [ noteUseTabs ] = useNoteLabelOptionalBool(note, "indentWithTabs");const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");+ const [ customRequestHandler ] = useNoteLabel(note, "customRequestHandler");const mime = useNoteProperty(note, "mime");const spacedUpdate = useEditorSpacedUpdate({note,@@ -146,6 +147,7 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentCntxId={ntxId} parentComponent={parentComponent}editorRef={combinedEditorRef} containerRef={containerRef}mime={mime ?? "text/plain"}+ customRequestHandler={customRequestHandler != null}className="note-detail-code-editor"placeholder={placeholder ?? t("editable_code.placeholder")}vimKeybindings={vimKeymapEnabled}diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex e80a0202a2..26aaf47830 100644--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@ -10,9 +10,14 @@ export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {editorRef?: Ref<VanillaCodeMirror>;containerRef?: Ref<HTMLPreElement>;onInitialized?: () => void;+ /**+ * Whether the edited note is a custom request handler (has `#customRequestHandler`).+ * Gates the `api.req`/`api.res`/`api.pathParams` completions for backend scripts.+ */+ customRequestHandler?: boolean;}-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, ...extraOpts }: CodeMirrorProps) {+export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, ...extraOpts }: CodeMirrorProps) {const parentRef = useSyncedRef(externalContainerRef);const codeEditorRef = useRef<VanillaCodeMirror>();@@ -45,6 +50,11 @@ export default function CodeMirror({ className, content, mime, editorRef: externcodeEditorRef.current?.setMimeType(mime);}, [ mime ]);+ // React to custom-request-handler status, which gates the backend api.req/res/pathParams completions.+ useEffect(() => {+ codeEditorRef.current?.setScriptApiContext({ customRequestHandler: !!customRequestHandler });+ }, [ customRequestHandler ]);+// React to line wrapping.useEffect(() => codeEditorRef.current?.setLineWrapping(!!lineWrapping), [ lineWrapping ]);diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 0f6c535c97..9071ec47f5 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -10,10 +10,10 @@ import byMimeType from "./syntax_highlighting.js";import smartIndentWithTab from "./extensions/custom_tab.js";import type { ThemeDefinition } from "./color_themes.js";import { createSearchHighlighter, SearchHighlighter, searchMatchHighlightTheme } from "./find_replace.js";-import { buildTypeCompletion } from "./type_completion/index.js";+import { buildTypeCompletion, type ScriptApiContext } from "./type_completion/index.js";export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getThemeById } from "./color_themes.js";-export { isScriptMime, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND } from "./type_completion/index.js";+export { isScriptMime, type ScriptApiContext, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND } from "./type_completion/index.js";// Custom keymap to prevent Ctrl+Enter from inserting a newline// This allows the parent application to handle the shortcut (e.g., for "Run Active Note")@@ -65,6 +65,10 @@ export default class CodeMirror extends EditorView {private completionSources = new Map<string, CompletionSource>();/** Monotonic token guarding against out-of-order async type-completion updates. */private typeCompletionToken = 0;+ /** Current MIME type, retained so the type completion can be rebuilt when only the api context changes. */+ private currentMime: string | null = null;+ /** Per-note context tuning the script `api` surface (e.g. custom-request-handler members). */+ private scriptApiContext: ScriptApiContext = {};constructor(config: EditorConfig) {const languageCompartment = new Compartment();@@ -311,6 +315,7 @@ export default class CodeMirror extends EditorView {}async setMimeType(mime: string) {+ this.currentMime = mime;let newExtension: Extension[] = [];const correspondingSyntax = byMimeType[mime];@@ -334,6 +339,19 @@ export default class CodeMirror extends EditorView {await this.#updateTypeCompletion(mime);}+ /**+ * Updates the per-note script `api` context (e.g. whether the note is a custom+ * request handler, which gates the `req`/`res`/`pathParams` members) and rebuilds+ * the type completion in place. Safe to call before a MIME type is set — it takes+ * effect on the next `setMimeType`.+ */+ async setScriptApiContext(context: ScriptApiContext) {+ this.scriptApiContext = context;+ if (this.currentMime !== null) {+ await this.#updateTypeCompletion(this.currentMime);+ }+ }+/*** Enables the TypeScript language service (full completion, hover docs and* diagnostics) for backend/frontend script notes, and clears it otherwise.@@ -342,7 +360,7 @@ export default class CodeMirror extends EditorView {*/async #updateTypeCompletion(mime: string) {const token = ++this.typeCompletionToken;- const { extensions, source } = await buildTypeCompletion(mime);+ const { extensions, source } = await buildTypeCompletion(mime, this.scriptApiContext);if (token !== this.typeCompletionToken) {return; // a newer setMimeType call superseded this one}diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.tsindex 0a4f173fd0..7ed73d2c4a 100644--- a/packages/codemirror/src/type_completion/index.spec.ts+++ b/packages/codemirror/src/type_completion/index.spec.ts@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";import { getScriptCompletions, getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SCRIPT_MIME_JSX } from "./index.js";/** Returns completions at the `|` marker in `source` (the marker is stripped). */-function completionsAtMarker(mime: string, source: string) {+function completionsAtMarker(mime: string, source: string, context?: { customRequestHandler?: boolean }) {const offset = source.indexOf("|");- return getScriptCompletions(mime, source.replace("|", ""), offset);+ return getScriptCompletions(mime, source.replace("|", ""), offset, context);}/** "Property 'x' does not exist on type 'y'." */@@ -189,31 +189,50 @@ describe("script note diagnostics", () => {});describe("backend custom request handler api (req/res/pathParams)", () => {- it("offers req, res and pathParams as backend api members", async () => {- const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "api.|");+ const HANDLER = { customRequestHandler: true };++ it("offers req, res and pathParams to custom request handler notes", async () => {+ const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "api.|", HANDLER);expect(names).toContain("req");expect(names).toContain("res");expect(names).toContain("pathParams");}, TIMEOUT);it("types the res object's methods (status/send/json), not unknown", async () => {- const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "api.res?.|");+ const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "api.res?.|", HANDLER);expect(names).toContain("status");expect(names).toContain("send");expect(names).toContain("json");}, TIMEOUT);- it("accepts a chained res response and req access without errors", async () => {+ it("exposes req/res/pathParams as non-optional (no null-check needed in a handler)", async () => {+ // No optional chaining: if these were typed optional, accessing them would+ // raise TS18048 ("possibly undefined"). They're guaranteed in a handler.const codes = await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND,- "const id = api.pathParams?.[0];\n"- + "api.res?.status(200).json({ id, method: api.req?.method });"+ "const id = api.pathParams[0];\n"+ + "api.res.status(200).json({ id, method: api.req.method });",+ HANDLER);expect(codes).toEqual([]);}, TIMEOUT);+ it("hides req/res/pathParams from backend notes that are not custom request handlers", async () => {+ const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "api.|");+ expect(names).not.toContain("req");+ expect(names).not.toContain("res");+ expect(names).not.toContain("pathParams");+ // The rest of the backend api stays available.+ expect(names).toContain("getNote");+ }, TIMEOUT);++ it("flags req/res access in a non-handler backend note (omitted from the api type)", async () => {+ const codes = await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND, "api.res?.send('hi');");+ expect(codes).toContain(TS_UNKNOWN_PROPERTY);+ }, TIMEOUT);+it("does not expose req/res/pathParams to frontend scripts (server-only)", async () => {- const names = await completionsAtMarker(SCRIPT_MIME_FRONTEND, "api.|");+ const names = await completionsAtMarker(SCRIPT_MIME_FRONTEND, "api.|", HANDLER);expect(names).not.toContain("req");expect(names).not.toContain("res");expect(names).not.toContain("pathParams");diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex c1de2a8ad2..e9548d4dda 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -29,6 +29,27 @@ export function isScriptMime(mime: string): boolean {return mime === SCRIPT_MIME_FRONTEND || mime === SCRIPT_MIME_BACKEND || mime === SCRIPT_MIME_JSX;}+/**+ * Per-note context that tunes the script `api` surface offered to the editor,+ * beyond what the MIME type alone implies.+ */+export interface ScriptApiContext {+ /**+ * Whether the note is a custom request handler (has the `#customRequestHandler`+ * label). Only such backend notes receive Express `req`/`res`/`pathParams` at+ * runtime, so the `api.req`/`api.res`/`api.pathParams` members are offered only+ * when this is true.+ */+ customRequestHandler?: boolean;+}++/**+ * `BackendApi` members that exist only inside custom request handlers. When the+ * note isn't a custom request handler we `Omit` these from the `api` global so+ * they don't show up as (always-undefined) completions.+ */+const CUSTOM_REQUEST_HANDLER_MEMBERS = ["req", "res", "pathParams"] as const;+/** Frontend and JSX scripts share the browser runtime (frontend `api`, jQuery). */function isFrontendMime(mime: string): boolean {return mime === SCRIPT_MIME_FRONTEND || mime === SCRIPT_MIME_JSX;@@ -64,7 +85,7 @@ const COMPILER_OPTIONS = {ignoreDeprecations: "6.0"};-async function createEnv(mime: string) {+async function createEnv(mime: string, context: ScriptApiContext = {}) {const tsModule = await import("typescript");const ts = tsModule.default ?? tsModule;const { createSystem, createVirtualTypeScriptEnvironment } = await import("@typescript/vfs");@@ -107,7 +128,12 @@ async function createEnv(mime: string) {// (single source of truth, drift-guarded). No jQuery/DOM server-side.const apiTypes = (await import("../../../commons/src/lib/script_api.ts?raw")).default;fsMap.set(API_TYPES_PATH, apiTypes);- fsMap.set(API_GLOBALS_PATH, `import type { BackendApi } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: BackendApi;\n}\n`);+ // `req`/`res`/`pathParams` only exist at runtime for custom request handlers,+ // so omit them from the `api` global for every other backend note.+ const apiType = context.customRequestHandler+ ? "BackendApi"+ : `Omit<BackendApi, ${CUSTOM_REQUEST_HANDLER_MEMBERS.map((m) => `"${m}"`).join(" | ")}>`;+ fsMap.set(API_GLOBALS_PATH, `import type { BackendApi } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: ${apiType};\n}\n`);rootFiles.push(API_TYPES_PATH);}@@ -154,13 +180,16 @@ export interface TypeCompletion {* e.g. snippet slash-commands — into the editor's single autocompletion.** Returns empty extensions and a null source for non-script MIME types.+ *+ * `context` tunes the offered `api` surface per note (e.g. exposing+ * `req`/`res`/`pathParams` only for custom request handlers).*/-export async function buildTypeCompletion(mime: string): Promise<TypeCompletion> {+export async function buildTypeCompletion(mime: string, context: ScriptApiContext = {}): Promise<TypeCompletion> {if (!isScriptMime(mime)) {return { extensions: [], source: null };}- const env = await createEnv(mime);+ const env = await createEnv(mime, context);const { tsFacet, tsSync, tsAutocomplete, tsLinter, tsHover } = await import("@valtown/codemirror-ts");return {@@ -277,8 +306,8 @@ function ignoredDiagnosticCodes(mime: string): number[] {* what the user actually sees. Intended for tests asserting which diagnostics* are (and aren't) surfaced.*/-export async function getScriptDiagnosticCodes(mime: string, code: string): Promise<number[]> {- const env = await createEnv(mime);+export async function getScriptDiagnosticCodes(mime: string, code: string, context: ScriptApiContext = {}): Promise<number[]> {+ const env = await createEnv(mime, context);const path = scriptPath(mime);env.updateFile(path, code.length ? code : " ");const diagnostics = [@@ -298,8 +327,8 @@ export async function getScriptDiagnosticCodes(mime: string, code: string): Prom* asserting which completions (api members, JSX elements/attributes, …) are* surfaced.*/-export async function getScriptCompletions(mime: string, code: string, offset: number): Promise<string[]> {- const env = await createEnv(mime);+export async function getScriptCompletions(mime: string, code: string, offset: number, context: ScriptApiContext = {}): Promise<string[]> {+ const env = await createEnv(mime, context);const path = scriptPath(mime);env.updateFile(path, code.length ? code : " ");const completions = env.languageService.getCompletionsAtPosition(path, offset, {});diff --git a/packages/commons/src/lib/attribute_names.ts b/packages/commons/src/lib/attribute_names.tsindex 704dbb8d65..b235834ee5 100644--- a/packages/commons/src/lib/attribute_names.ts+++ b/packages/commons/src/lib/attribute_names.ts@@ -27,6 +27,7 @@ type Labels = {run: string;widget: boolean;"disabled:widget": boolean;+ customRequestHandler: string;// Tree specificsubtreeHidden: boolean;diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.tsindex 2db5b54732..ec6b19280c 100644--- a/packages/commons/src/lib/script_api.ts+++ b/packages/commons/src/lib/script_api.ts@@ -612,23 +612,23 @@ export interface BackendApi {originEntity?: unknown | null;/**- * Express request object. **Only** available when the script runs as a custom- * request handler — i.e. a note with the `#customRequestHandler` label invoked- * via a `/custom/...` URL. `undefined` for every other backend script (events,- * manual runs, scheduled scripts, …), so guard with `if (api.req)` before use.+ * Express request object. Available only inside custom request handlers — a note+ * with the `#customRequestHandler` label, invoked via a `/custom/...` URL. The+ * editor surfaces this member only for such notes (where the request always+ * supplies it), so it is non-optional rather than forcing a null-check.*/- req?: ScriptRequest;+ req: ScriptRequest;/*** Express response object — write the HTTP response here, e.g.- * `api.res.status(200).json({ ok: true })`. **Only** available in custom- * request handlers; `undefined` otherwise.+ * `api.res.status(200).json({ ok: true })`. Available only inside custom request+ * handlers (where it is always supplied), so it is non-optional.*/- res?: ScriptResponse;+ res: ScriptResponse;/*** The capture groups from the `#customRequestHandler` regex that matched this- * request's URL, in order. **Only** available in custom request handlers.+ * request's URL, in order. Available only inside custom request handlers.*/- pathParams?: string[];+ pathParams: string[];/*** day.js library for date manipulation. See {@link https://day.js.org} for documentationdiff --git a/packages/trilium-core/src/services/backend_script_api.ts b/packages/trilium-core/src/services/backend_script_api.tsindex 985a819f3d..a83f0a2e24 100644--- a/packages/trilium-core/src/services/backend_script_api.ts+++ b/packages/trilium-core/src/services/backend_script_api.ts@@ -79,6 +79,9 @@ export interface Api {*/originEntity?: AbstractBeccaEntity<any> | null;+ // Note: these are optional here (unlike the gated public surface in+ // `@triliumnext/commons`, where they're required) because this interface types+ // *every* backend script, and they're only populated for custom request handlers./*** Express request object. Only present when the script runs as a custom request* handler (a note with the `#customRequestHandler` label invoked via `/custom/...`);