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(share): run a shared render note's script as the app does
Elian Dorancd4c82d68dec
diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.tsindex 2a629cd669..fe4d0b772e 100644--- a/apps/client/src/services/froca-interface.ts+++ b/apps/client/src/services/froca-interface.ts@@ -10,6 +10,7 @@ import type FBranch from "../entities/fbranch.js";import type { FBranchRow } from "../entities/fbranch.js";import type FNote from "../entities/fnote.js";import type { FNoteRow } from "../entities/fnote.js";+import type { Bundle } from "./bundle.js";/** The relations a note map draws or leaves out, by name; an empty `includeRelations` draws all. */export interface NoteMapFilters {@@ -41,6 +42,8 @@ export interface FrocaSource {getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;/** The relations the relation map note `relationMapNoteId` draws between the notes `noteIds`. */getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;+ /** The frontend bundle of the script note `noteId` and its modules, or nothing if it has none. */+ getScriptBundle(noteId: string): Promise<Bundle | undefined>;}export interface Froca {@@ -63,4 +66,5 @@ export interface Froca {searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;+ getScriptBundle(noteId: string): Promise<Bundle | undefined>;}diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.tsindex 8ae2dc5c77..f326750c5a 100644--- a/apps/client/src/services/froca.ts+++ b/apps/client/src/services/froca.ts@@ -5,6 +5,7 @@ import FAttribute, { type FAttributeRow } from "../entities/fattribute.js";import FBlob, { type FBlobRow } from "../entities/fblob.js";import FBranch, { type FBranchRow } from "../entities/fbranch.js";import FNote, { type FNoteRow } from "../entities/fnote.js";+import type { Bundle } from "./bundle.js";import type { Froca, FrocaSource, NoteMapFilters, SubtreeResponse } from "./froca-interface.js";import server from "./server.js";import { isPreAuthScreen } from "./utils.js";@@ -411,6 +412,10 @@ class FrocaImpl implements Froca {return this.source.getRelationMap(relationMapNoteId, noteIds);}+ getScriptBundle(noteId: string) {+ return this.source.getScriptBundle(noteId);+ }+async getBlob(entityType: string, entityId: string): Promise<FBlob | null> {// I'm not sure why we're not using blobIds directly, it would save us this composite key ...// perhaps one benefit is that we're always requesting the latest blob, not relying on perhaps faulty/slow@@ -451,7 +456,8 @@ const SERVER_SOURCE: FrocaSource = {getNoteMap: (mapRootNoteId, mapType, filters) =>server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters),getRelationMap: (relationMapNoteId, noteIds) =>- server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId })+ server.post<RelationMapPostResponse>("relation-map", { noteIds, relationMapNoteId }),+ getScriptBundle: (noteId) => server.postWithSilentInternalServerError<Bundle>(`script/bundle/${noteId}`)};const froca = new FrocaImpl();diff --git a/apps/client/src/services/render.tsx b/apps/client/src/services/render.tsxindex b5d07abe3b..f6c068926d 100644--- a/apps/client/src/services/render.tsx+++ b/apps/client/src/services/render.tsx@@ -1,18 +1,23 @@import { Component, h, VNode } from "preact";+import type AppComponent from "../components/component.js";+import type FNote from "../entities/fnote.js";import { renderReactWidgetAtElement } from "../widgets/react/react_utils.jsx";import { type Bundle, executeBundleWithoutErrorHandling } from "./bundle.js";import froca from "./froca.js";import { keepStylesScoped, RENDER_SCOPE_CLASS } from "./render_css_scope.js";-import server from "./server.js";/*** @param noteId the render note the error is attributed to, so the caller can link back to it.*/type ErrorHandler = (e: unknown, noteId?: string) => void;-export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {+/**+ * @param parentComponent the component a JSX render note's element is mounted under, by default the+ * one of the closest `.component` element.+ */+export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: ErrorHandler, parentComponent?: AppComponent) {const relations = note.getRelations("renderNote");const renderNoteIds = relations.map((rel) => rel.value).filter((noteId) => noteId);@@ -22,7 +27,7 @@ export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: Ertry {for (const renderNoteId of renderNoteIds) {currentRenderNoteId = renderNoteId;- const bundle = await server.postWithSilentInternalServerError<Bundle>(`script/bundle/${renderNoteId}`);+ const bundle = await froca.getScriptBundle(renderNoteId);if (!bundle) {throw new Error(`Script note '${renderNoteId}' could not be loaded. It may be protected and require an active protected session.`);@@ -40,7 +45,7 @@ export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: Er.then(result => {// Render JSXif (bundle.html === "") {- renderIfJsx(bundle, result, $el, onError).catch((e) => onError?.(e, bundle.noteId));+ renderIfJsx(bundle, result, $el, onError, parentComponent).catch((e) => onError?.(e, bundle.noteId));}});}@@ -59,7 +64,7 @@ export async function render(note: FNote, $el: JQuery<HTMLElement>, onError?: Er}}-export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<HTMLElement>, onError?: ErrorHandler) {+export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<HTMLElement>, onError?: ErrorHandler, parentComponent?: AppComponent) {// Ensure the root script note is actually a JSX.const rootScriptNoteId = await froca.getNote(bundle.noteId);if (rootScriptNoteId?.mime !== "text/jsx") return;@@ -68,7 +73,7 @@ export async function renderIfJsx(bundle: Bundle, result: unknown, $el: JQuery<Hif (typeof result !== "function") return;// Obtain the parent component.- const closestComponent = glob.getComponentByEl($el.closest(".component")[0]);+ const closestComponent = parentComponent ?? glob.getComponentByEl($el.closest(".component")[0]);if (!closestComponent) return;// Render the element.diff --git a/apps/client/src/widgets/type_widgets/Render.tsx b/apps/client/src/widgets/type_widgets/Render.tsxindex abad54b060..1167ba509d 100644--- a/apps/client/src/widgets/type_widgets/Render.tsx+++ b/apps/client/src/widgets/type_widgets/Render.tsx@@ -1,6 +1,6 @@import "./Render.css";-import { useEffect, useRef, useState } from "preact/hooks";+import { useContext, useEffect, useRef, useState } from "preact/hooks";import FNote from "../../entities/fnote";import attributes from "../../services/attributes";@@ -13,7 +13,7 @@ import FormGroup from "../react/FormGroup";import { FormListItem } from "../react/FormList";import { useNoteRelation, useTriliumEvent } from "../react/hooks";import NoteAutocomplete from "../react/NoteAutocomplete";-import { refToJQuerySelector } from "../react/react_utils";+import { ParentComponent, refToJQuerySelector } from "../react/react_utils";import RenderErrorCard from "../react/RenderErrorCard";import SetupForm from "./helpers/SetupForm";import { TypeWidgetProps } from "./type_widget";@@ -49,11 +49,12 @@ export default function Render(props: TypeWidgetProps) {function RenderContent({ note, noteContext, ntxId }: TypeWidgetProps) {const contentRef = useRef<HTMLDivElement>(null);const [ error, setError ] = useState<{ error: unknown; noteId?: string } | null>(null);+ const parentComponent = useContext(ParentComponent);function refresh() {if (!contentRef) return;setError(null);- render.render(note, refToJQuerySelector(contentRef), (e, noteId) => setError({ error: e, noteId }));+ render.render(note, refToJQuerySelector(contentRef), (e, noteId) => setError({ error: e, noteId }), parentComponent ?? undefined);}useEffect(refresh, [ note ]);diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.tsindex dd33d0c02e..d7dcbbec4d 100644--- a/packages/share-theme/src/content/share_froca_source.ts+++ b/packages/share-theme/src/content/share_froca_source.ts@@ -36,7 +36,8 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSour},// The share reads the notes from the map's own content, so a visitor cannot name others.getRelationMap: (relationMapNoteId) =>- getJson(`api/relation-map/${encodeURIComponent(relationMapNoteId)}`)+ getJson(`api/relation-map/${encodeURIComponent(relationMapNoteId)}`),+ getScriptBundle: (noteId) => getJson(`api/script/bundle/${encodeURIComponent(noteId)}`)};}diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex aa7e843af5..7575f0bf88 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -512,7 +512,7 @@ export function getContent(note: SNote | BNote, options: ShareRenderOptions = {}result.isEmpty = true;} else if (note.type === "webView") {renderWebView(note, result);- } else if (note.type === "noteMap" || note.type === "relationMap") {+ } else if ([ "noteMap", "relationMap", "render" ].includes(note.type)) {result.content = "";hostNoteView(result, note);} else if (note.type === "spreadsheet") {diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsindex 8713e86284..4f8a752ab5 100644--- a/packages/trilium-core/src/share/handlers.ts+++ b/packages/trilium-core/src/share/handlers.ts@@ -6,6 +6,7 @@ import becca from "../becca/becca.js";import { buildLinkMap, buildTreeMap } from "../routes/api/note_map.js";import { buildRelationMap } from "../routes/api/relation-map.js";import { getCrypto } from "../services/encryption/crypto.js";+import scriptService from "../services/script.js";import searchService from "../services/search/services/search.js";import SearchContext from "../services/search/search_context.js";import { decodeBase64, decodeUtf8, encodeUtf8 } from "../services/utils/binary.js";@@ -96,6 +97,7 @@ const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {"/share/api/tree": loadTree,"/share/api/note-map/:noteId/:mapType": getNoteMap,"/share/api/relation-map/:noteId": getRelationMap,+ "/share/api/script/bundle/:noteId": getScriptBundle,"/share/": getShareRoot,"/share/:shareId": getShareNote};@@ -238,6 +240,38 @@ function getRelationMap(req: ShareRequest): ShareReply {return jsonReply(200, buildRelationMap(becca.getNote(mapNote.noteId), noteIds));}+/**+ * Answers the frontend bundle of a shared script note, which a shared render note runs, only when+ * every note it is built from is one a visitor of the share can read, as the bundle carries the+ * source of each. A backend script has no frontend bundle.+ */+function getScriptBundle(req: ShareRequest): ShareReply {+ const scriptNote = checkNoteContentAccess(req.params.noteId ?? "", req);+ const note = becca.getNote(scriptNote.noteId);+ const notFound = jsonReply(404, { message: `Note '${scriptNote.noteId}' has no script to run.` });+ if (!note || (note.isJavaScript() && note.getScriptEnv() === "backend")) {+ return notFound;+ }++ let bundle;+ try {+ bundle = scriptService.getScriptBundleForFrontend(note);+ } catch {+ // A protected module cannot be read.+ return notFound;+ }++ const isReadable = (noteId: string) => {+ const module = shaca.getNote(noteId);+ return !!module && !module.isProtected && hasCredentialAccess(module, req);+ };+ if (!bundle || !(bundle.allNoteIds ?? []).every(isReadable)) {+ return notFound;+ }++ return jsonReply(200, bundle);+}+/** Returns the IDs of the notes a relation map's content places on the map. */function readPlacedNoteIds(content: string | Uint8Array | null | undefined) {try {diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.tsindex 3748e4a07f..be27d4ec28 100644--- a/packages/trilium-core/src/share/route_paths.ts+++ b/packages/trilium-core/src/share/route_paths.ts@@ -22,6 +22,7 @@ export const SHARE_ROUTE_PATHS = ["/share/api/tree","/share/api/note-map/:noteId/:mapType","/share/api/relation-map/:noteId",+ "/share/api/script/bundle/:noteId","/share/","/share/:shareId"] as const;