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
fix(scripting): address PR review feedback
Elian Doran3567de5f1a45
diff --git a/apps/client/src/services/bundle.spec.ts b/apps/client/src/services/bundle.spec.tsindex 7c7c627ddd..5bf30c459b 100644--- a/apps/client/src/services/bundle.spec.ts+++ b/apps/client/src/services/bundle.spec.ts@@ -2,7 +2,7 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { buildNote } from "../test/easy-froca";import { ReactWrappedWidget } from "../widgets/basic_widget.js";-import bundleService, { Bundle, executeBundle, executeBundleWithoutErrorHandling, WidgetsByParent } from "./bundle";+import bundleService, { Bundle, executeBundle, executeBundleWithoutErrorHandling, isBackendScriptingDisabled, WidgetsByParent } from "./bundle";import server from "./server.js";import * as toast from "./toast";import ws from "./ws.js";@@ -59,6 +59,14 @@ describe("executeBundle / executeBundleWithoutErrorHandling", () => {spy.mockRestore();});+ it("isBackendScriptingDisabled detects the error anywhere in the cause chain", async () => {+ const { BackendScriptingDisabledError } = await import("./frontend_script_api.js");+ // The bundler nests the real error as a cause under its "Load of script note …" wrapper.+ const wrapped = new Error(`Load of script note "X" (id) failed with: disabled`, { cause: new BackendScriptingDisabledError() });+ expect(isBackendScriptingDisabled(wrapped)).toBe(true);+ expect(isBackendScriptingDisabled(new Error("some other failure"))).toBe(false);+ });+it("executeBundle rethrows after reporting when opts.rethrow is set", async () => {const id = buildNote({ title: "Throwing note" }).noteId;const spy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);diff --git a/apps/client/src/services/bundle.ts b/apps/client/src/services/bundle.tsindex 133ceb4ee7..73798eeadf 100644--- a/apps/client/src/services/bundle.ts+++ b/apps/client/src/services/bundle.ts@@ -4,13 +4,13 @@ import { h, VNode } from "preact";import FNote from "../entities/fnote.js";import BasicWidget, { ReactWrappedWidget } from "../widgets/basic_widget.js";import RightPanelWidget from "../widgets/right_panel_widget.js";-import type { Entity } from "./frontend_script_api.js";+import { BackendScriptingDisabledError, type Entity } from "./frontend_script_api.js";import { WidgetDefinitionWithType } from "./frontend_script_api_preact.js";import { t } from "./i18n.js";import ScriptContext from "./script_context.js";import server from "./server.js";import toastService, { showErrorForScriptNote } from "./toast.js";-import utils, { getErrorMessage, rootCauseMessage } from "./utils.js";+import utils, { causeChain, getErrorMessage, rootCauseMessage } from "./utils.js";// TODO: Deduplicate with server.export interface Bundle {@@ -59,8 +59,10 @@ export async function executeBundle(bundle: Bundle, originEntity?: Entity | nulltry {return await executeBundleWithoutErrorHandling(bundle, originEntity, $container);} catch (e: unknown) {- showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });- logError("Widget initialization failed: ", e);+ if (!isBackendScriptingDisabled(e)) {+ showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });+ logError("Widget initialization failed: ", e);+ }if (opts?.rethrow) {throw e;}@@ -156,10 +158,10 @@ async function getWidgetBundlesByParent() {widgetsByParent.add(widget);}} catch (e: any) {- const noteId = bundle.noteId;- showErrorForScriptNote(noteId, rootCauseMessage(e), { monospace: true });-- logError("Widget initialization failed: ", e);+ if (!isBackendScriptingDisabled(e)) {+ showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });+ logError("Widget initialization failed: ", e);+ }continue;}}@@ -181,3 +183,16 @@ export default {executeStartupBundles,getWidgetBundlesByParent};++/**+ * Whether the failure was a disabled backend script (anywhere in its cause chain). Those already+ * raise a single consolidated toast in `runOnBackend`, so the per-note toast here is redundant.+ */+export function isBackendScriptingDisabled(e: unknown): boolean {+ for (const error of causeChain(e)) {+ if (error instanceof BackendScriptingDisabledError) {+ return true;+ }+ }+ return false;+}diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex 0d80b0df7f..8d5d4b5408 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -820,6 +820,18 @@ describe("rootCauseMessage", () => {expect(rootCauseMessage(42)).toBe("42");expect(rootCauseMessage(new Error("outer", { cause: "string cause" }))).toBe("string cause");});++ it("does not loop forever on a cyclic cause chain", () => {+ const self = new Error("self-cycle");+ self.cause = self;+ expect(rootCauseMessage(self)).toBe("self-cycle");++ // A longer cycle: a -> b -> a. Walking stops once a repeat is seen.+ const a = new Error("a");+ const b = new Error("b", { cause: a });+ a.cause = b;+ expect(rootCauseMessage(b)).toBe("a");+ });});describe("handleRightToLeftPlacement", () => {diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 31318a4dc7..3a3ff3bc64 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -856,17 +856,31 @@ export function getErrorMessage(e: unknown) {* the nested errors produced when a `require()`d module fails.*/export function rootCauseMessage(e: unknown): string {- let error = e;- while (error instanceof Error && error.cause !== undefined) {- error = error.cause;+ let root: unknown = e;+ for (const error of causeChain(e)) {+ root = error;}- if (typeof error === "string") {- return error;+ if (typeof root === "string") {+ return root;}- if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {- return error.message;+ if (root && typeof root === "object" && "message" in root && typeof root.message === "string") {+ return root.message;+ }+ return String(root);+}++/**+ * Walks an error's `cause` chain, yielding each error from `e` down to the root. Guards against+ * cyclic chains (e.g. `err.cause === err`, or a longer loop) so callers can't spin forever.+ */+export function* causeChain(e: unknown): Generator<unknown> {+ const seen = new Set<unknown>();+ let error: unknown = e;+ while (error !== undefined && !seen.has(error)) {+ seen.add(error);+ yield error;+ error = error instanceof Error ? error.cause : undefined;}- return String(error);}export function replaceHtmlEscapedSlashes(str: string) {diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.tsindex 9329aca84d..a69a235e2a 100644--- a/packages/commons/src/lib/script_api.ts+++ b/packages/commons/src/lib/script_api.ts@@ -485,7 +485,7 @@ export interface FrontendApi {* @param opts creation options — e.g. `{ title, content, type, mime, activate }`* @returns the created note and its branch, resolved from the frontend cache*/- createNote(parentNotePath: string, opts?: ScriptCreateNoteOpts): Promise<{ note: ScriptFNote | null; branch: ScriptFBranch | null }>;+ createNote(parentNotePath: string, opts?: ScriptCreateNoteOpts): Promise<{ note: ScriptFNote | null; branch: ScriptFBranch | undefined }>;/*** Instance name identifies particular Trilium instance. It can be useful for scripts* if some action needs to happen on only one specific instance.