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
test(script_deployer): add deployment tests
Elian Doran1164fb7dc77b
diff --git a/apps/script-deployer/package.json b/apps/script-deployer/package.jsonindex 227649f2e3..049fb1bfea 100644--- a/apps/script-deployer/package.json+++ b/apps/script-deployer/package.json@@ -5,6 +5,7 @@"description": "Development harness for writing and deploying Trilium scripts to a local instance","scripts": {"dev": "tsx watch --clear-screen=false --ignore '../client/node_modules/.vite-temp' src/dev.ts",+ "test": "vitest run","clean": "rm -rf data"}}diff --git a/apps/script-deployer/src/deploy.spec.ts b/apps/script-deployer/src/deploy.spec.tsnew file mode 100644index 0000000000..2773c2bd56--- /dev/null+++ b/apps/script-deployer/src/deploy.spec.ts@@ -0,0 +1,303 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import becca from "@triliumnext/server/src/becca/becca";+import BBranch from "@triliumnext/server/src/becca/entities/bbranch";+import { buildNote } from "@triliumnext/server/src/test/becca_easy_mocking";+import {+ parseScriptMeta,+ transpile,+ deployScript,+ codeNoteId,+ renderNoteId,+ SCRIPTS_NOTE_ID,+ type NoteService,+} from "./deploy";++// ── Mocks — only SQL and entity_changes, becca is real ───────────────────────++vi.mock("@triliumnext/server/src/services/sql", () => ({+ default: {+ transactional: (cb: Function) => cb(),+ upsert: () => {},+ execute: () => {},+ replace: () => {},+ getMap: () => {},+ },+}));++vi.mock("@triliumnext/server/src/services/sql_init", () => ({+ dbReady: () => {},+}));++vi.mock("@triliumnext/server/src/services/entity_changes", () => ({+ default: { putEntityChange: () => {} },+ putEntityChange: () => {},+}));++// ── parseScriptMeta ──────────────────────────────────────────────────────────++describe("parseScriptMeta", () => {+ it("parses a valid @trilium-script block", () => {+ const source = `/**+ * @trilium-script+ *+ * id: my-script+ * type: render+ * title: My Script+ */+export default function() {}`;++ const meta = parseScriptMeta(source, "my-script.jsx");+ expect(meta).toEqual({+ id: "my-script",+ type: "render",+ title: "My Script",+ });+ });++ it("returns null when @trilium-script marker is missing", () => {+ const source = `/** Just a normal comment */\nexport default function() {}`;+ expect(parseScriptMeta(source, "test.jsx")).toBeNull();+ });++ it("returns null and logs error when id is missing", () => {+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ const source = `/**+ * @trilium-script+ *+ * type: render+ * title: My Script+ */`;+ expect(parseScriptMeta(source, "test.jsx")).toBeNull();+ expect(spy).toHaveBeenCalledWith(expect.stringContaining("missing required fields: id"));+ spy.mockRestore();+ });++ it("returns null when type is missing", () => {+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ const source = `/**+ * @trilium-script+ *+ * id: test+ * title: Test+ */`;+ expect(parseScriptMeta(source, "test.jsx")).toBeNull();+ expect(spy).toHaveBeenCalledWith(expect.stringContaining("missing required fields: type"));+ spy.mockRestore();+ });++ it("returns null when title is missing", () => {+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ const source = `/**+ * @trilium-script+ *+ * id: test+ * type: code+ */`;+ expect(parseScriptMeta(source, "test.jsx")).toBeNull();+ expect(spy).toHaveBeenCalledWith(expect.stringContaining("missing required fields: title"));+ spy.mockRestore();+ });++ it("preserves extra metadata fields", () => {+ const source = `/**+ * @trilium-script+ *+ * id: test+ * type: render+ * title: Test+ * icon: bx-rocket+ */`;+ const meta = parseScriptMeta(source, "test.jsx");+ expect(meta).toMatchObject({ icon: "bx-rocket" });+ });+});++// ── transpile ────────────────────────────────────────────────────────────────++describe("transpile", () => {+ it("passes .jsx files through unchanged", () => {+ const source = `const x: number = 1; return <div>{x}</div>;`;+ expect(transpile(source, "test.jsx")).toBe(source);+ });++ it("strips type annotations from .tsx but preserves JSX", () => {+ const source = `const x: number = 1;\nconst el = <div>{x}</div>;`;+ const result = transpile(source, "test.tsx");+ expect(result).not.toContain(": number");+ expect(result).toContain("<div>");+ });++ it("strips type annotations from .ts", () => {+ const source = `const x: number = 1;`;+ const result = transpile(source, "test.ts");+ expect(result).not.toContain(": number");+ expect(result).toContain("const x = 1");+ });++ it("passes .js files through unchanged", () => {+ const source = `const x = 1;`;+ expect(transpile(source, "test.js")).toBe(source);+ });+});++// ── deployScript ─────────────────────────────────────────────────────────────++describe("deployScript", () => {+ /**+ * A NoteService backed by buildNote — each createNewNote call+ * populates the real becca cache via becca_easy_mocking.+ */+ const notesService: NoteService = {+ createNewNote(params) {+ const note = buildNote({+ id: params.noteId,+ title: params.title,+ type: params.type as Parameters<typeof buildNote>[0]["type"],+ mime: params.mime ?? "text/html",+ content: params.content,+ });+ // buildNote doesn't create a branch to the parent, so add one.+ new BBranch({+ branchId: `${params.parentNoteId}_${params.noteId}`,+ noteId: params.noteId,+ parentNoteId: params.parentNoteId,+ });+ return { note: { noteId: note.noteId } };+ },+ };++ beforeEach(() => {+ becca.reset();++ // Root + Scripts folder, using buildNote for the tree structure.+ buildNote({+ id: "root",+ title: "root",+ children: [+ { id: SCRIPTS_NOTE_ID, title: "Scripts", type: "doc" },+ ],+ });+ });++ describe("render note with JSX", () => {+ const meta = { id: "xopp-importer", type: "render", title: "XOPP Importer" };+ const jsxContent = `import { h } from "trilium:preact";\nexport default function() { return <div>Hello</div>; }`;+ const mime = "text/jsx";++ it("creates a render note as parent with code note child linked via ~renderNote", () => {+ deployScript(meta, jsxContent, mime, becca, notesService);++ const renderId = renderNoteId(meta.id);+ const codeId = codeNoteId(meta.id);+ const renderNote = becca.notes[renderId];+ const codeNote = becca.notes[codeId];++ // Render note exists with correct type/title+ expect(renderNote).toBeDefined();+ expect(renderNote.type).toBe("render");+ expect(renderNote.title).toBe("XOPP Importer");++ // Code note exists with correct type/title+ expect(codeNote).toBeDefined();+ expect(codeNote.type).toBe("code");+ expect(codeNote.title).toBe("XOPP Importer");++ // Code note is a child of the render note+ expect(codeNote.getParentBranches().some((b) => b.parentNoteId === renderId)).toBe(true);++ // Render note is under scripts folder+ expect(renderNote.getParentBranches().some((b) => b.parentNoteId === SCRIPTS_NOTE_ID)).toBe(true);++ // ~renderNote relation points to the code note+ const relation = renderNote.getRelations().find((a) => a.name === "renderNote");+ expect(relation).toBeDefined();+ expect(relation!.value).toBe(codeId);+ });++ it("returns a 'created' result with both note IDs", () => {+ const result = deployScript(meta, jsxContent, mime, becca, notesService);+ expect(result).toEqual({+ action: "created",+ codeNoteId: codeNoteId(meta.id),+ renderNoteId: renderNoteId(meta.id),+ title: "XOPP Importer",+ type: "render",+ });+ });+ });++ describe("render note with TSX", () => {+ const meta = { id: "tsx-widget", type: "render", title: "TSX Widget" };+ const tsxSource = `const x: number = 1;\nexport default function() { return <div>{x}</div>; }`;+ const transpiledContent = transpile(tsxSource, "tsx-widget.tsx");+ const mime = "text/jsx";++ it("creates the same render+code structure as JSX, with types stripped but JSX preserved", () => {+ // Content was correctly transpiled+ expect(transpiledContent).not.toContain(": number");+ expect(transpiledContent).toContain("<div>");++ deployScript(meta, transpiledContent, mime, becca, notesService);++ const renderId = renderNoteId(meta.id);+ const codeId = codeNoteId(meta.id);++ expect(becca.notes[renderId]).toBeDefined();+ expect(becca.notes[renderId].type).toBe("render");+ expect(becca.notes[codeId]).toBeDefined();+ expect(becca.notes[codeId].type).toBe("code");+ });+ });++ describe("updating an existing script", () => {+ const meta = { id: "existing-script", type: "render", title: "Original" };+ const mime = "text/jsx";++ it("updates content and title of existing code note", () => {+ deployScript(meta, "old content", mime, becca, notesService);++ const codeId = codeNoteId(meta.id);+ const note = becca.notes[codeId];+ const saveSpy = vi.fn();+ const setContentSpy = vi.fn();+ note.save = saveSpy;+ note.setContent = setContentSpy;++ const result = deployScript({ ...meta, title: "New Title" }, "new content", mime, becca, notesService);+ expect(result.action).toBe("updated");+ expect(note.title).toBe("New Title");+ expect(saveSpy).toHaveBeenCalled();+ expect(setContentSpy).toHaveBeenCalledWith("new content");+ });+ });++ describe("plain code note (non-render)", () => {+ const meta = { id: "backend-helper", type: "code", title: "Backend Helper" };+ const content = "module.exports = {};";+ const mime = "application/javascript;env=backend";++ it("creates a single code note under scripts folder, no render note", () => {+ deployScript(meta, content, mime, becca, notesService);++ const codeId = codeNoteId(meta.id);+ const codeNote = becca.notes[codeId];++ expect(codeNote).toBeDefined();+ expect(codeNote.type).toBe("code");+ expect(codeNote.getParentBranches().some((b) => b.parentNoteId === SCRIPTS_NOTE_ID)).toBe(true);++ // No render note was created+ expect(becca.notes[renderNoteId(meta.id)]).toBeUndefined();+ });++ it("returns a 'created' result without renderNoteId", () => {+ const result = deployScript(meta, content, mime, becca, notesService);+ expect(result).toEqual({+ action: "created",+ codeNoteId: codeNoteId(meta.id),+ title: "Backend Helper",+ type: "code",+ });+ });+ });+});diff --git a/apps/script-deployer/src/deploy.ts b/apps/script-deployer/src/deploy.tsnew file mode 100644index 0000000000..94856c85cf--- /dev/null+++ b/apps/script-deployer/src/deploy.ts@@ -0,0 +1,210 @@+/**+ * Core deployment logic for Trilium scripts.+ *+ * Extracted from dev.ts so it can be tested without the full server lifecycle.+ */++import { extname } from "node:path";+import { transformSync } from "esbuild";+// ── Public constants ─────────────────────────────────────────────────────────++export const SCRIPTS_NOTE_ID = "_scripts";++export const MIME_BY_EXT: Record<string, string> = {+ ".jsx": "text/jsx",+ ".tsx": "text/jsx",+ ".js": "application/javascript;env=frontend",+ ".ts": "application/javascript;env=backend",+ ".html": "text/html",+ ".css": "text/css",+};++// ── Front-matter parsing ─────────────────────────────────────────────────────++export interface ScriptMeta {+ id: string;+ type: string;+ title: string;+ [key: string]: string;+}++/**+ * Parses the `@trilium-script` YAML front matter from a JSDoc comment block.+ *+ * ```+ * /**+ * * @trilium-script+ * *+ * * id: my-script+ * * type: render+ * * title: My Script+ * *\/+ * ```+ *+ * Returns `null` (with a console error) when the marker is missing or+ * required fields (`id`, `type`, `title`) are absent.+ */+export function parseScriptMeta(source: string, filePath: string): ScriptMeta | null {+ const match = source.match(/\/\*\*[\s\S]*?@trilium-script\s*([\s\S]*?)\*\//);+ if (!match) return null;++ const block = match[1];+ const meta: Record<string, string> = {};++ for (const line of block.split("\n")) {+ const cleaned = line.replace(/^\s*\*\s?/, "").trim();+ if (!cleaned) continue;++ const colon = cleaned.indexOf(":");+ if (colon === -1) continue;++ const key = cleaned.slice(0, colon).trim();+ const value = cleaned.slice(colon + 1).trim();+ if (key && value) meta[key] = value;+ }++ const missing = ["id", "type", "title"].filter((k) => !meta[k]);+ if (missing.length) {+ console.error(` SKIP ${filePath}: missing required fields: ${missing.join(", ")}`);+ return null;+ }++ return meta as ScriptMeta;+}++// ── Transpilation ────────────────────────────────────────────────────────────++/** Extensions that need esbuild transpilation before deployment. */+const TRANSPILE_EXTS = new Set([".ts", ".tsx"]);++/**+ * Strips TypeScript type annotations via esbuild, preserving JSX intact.+ * Trilium's frontend handles JSX natively, so we only strip types.+ */+export function transpile(source: string, filePath: string): string {+ const ext = extname(filePath);+ if (!TRANSPILE_EXTS.has(ext)) return source;++ const result = transformSync(source, {+ loader: ext === ".tsx" ? "tsx" : "ts",+ jsx: "preserve",+ sourcemap: false,+ });+ return result.code;+}++// ── Note ID helpers ──────────────────────────────────────────────────────────++export function codeNoteId(scriptId: string) {+ return `_sd_${scriptId}`;+}++export function renderNoteId(scriptId: string) {+ return `_sd_${scriptId}_render`;+}++// ── Deployment ───────────────────────────────────────────────────────────────++/**+ * Abstraction over the note-creation service so that tests can supply+ * a mock while the real dev server passes the actual `notesService`.+ */+export interface NoteService {+ createNewNote(params: {+ noteId: string;+ parentNoteId: string;+ title: string;+ type: string; // NoteType union at runtime, kept as string for test compatibility+ mime?: string;+ content: string;+ }): { note: { noteId: string } };+}++/** Helper to cast the real notesService (which uses NoteType) to our interface. */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function asNoteService(svc: any): NoteService {+ return svc as NoteService;+}++export interface BeccaLike {+ notes: Record<string, {+ noteId: string;+ title: string;+ save(): void;+ setContent(content: string): void;+ setRelation(name: string, targetNoteId: string): void;+ }>;+}++export interface DeployResult {+ action: "created" | "updated";+ codeNoteId: string;+ renderNoteId?: string;+ title: string;+ type: string;+}++/**+ * Deploys a single script file into the Trilium note tree.+ *+ * - For `type: render`: creates a render note with a child code note+ * linked via `~renderNote`.+ * - For other types: creates a plain code note under the scripts folder.+ * - If the code note already exists, only its content and title are updated.+ */+export function deployScript(+ meta: ScriptMeta,+ content: string,+ mime: string,+ becca: BeccaLike,+ notesService: NoteService,+ parentNoteId: string = SCRIPTS_NOTE_ID,+): DeployResult {+ const codeId = codeNoteId(meta.id);+ const existing = becca.notes[codeId];++ if (existing) {+ existing.title = meta.title;+ existing.save();+ existing.setContent(content);+ return { action: "updated", codeNoteId: codeId, title: meta.title, type: meta.type };+ }++ if (meta.type === "render") {+ const renderId = renderNoteId(meta.id);++ notesService.createNewNote({+ noteId: renderId,+ parentNoteId,+ title: meta.title,+ type: "render",+ content: "",+ });++ notesService.createNewNote({+ noteId: codeId,+ parentNoteId: renderId,+ title: meta.title,+ type: "code",+ mime,+ content,+ });++ const renderNote = becca.notes[renderId];+ renderNote.setRelation("renderNote", codeId);++ return { action: "created", codeNoteId: codeId, renderNoteId: renderId, title: meta.title, type: meta.type };+ }++ // Plain code note.+ notesService.createNewNote({+ noteId: codeId,+ parentNoteId,+ title: meta.title,+ type: "code",+ mime,+ content,+ });++ return { action: "created", codeNoteId: codeId, title: meta.title, type: meta.type };+}diff --git a/apps/script-deployer/src/dev.ts b/apps/script-deployer/src/dev.tsindex 55a20c6b5d..4383f8a0aa 100644--- a/apps/script-deployer/src/dev.ts+++ b/apps/script-deployer/src/dev.ts@@ -7,8 +7,8 @@*/import { existsSync, mkdirSync, readdirSync, readFileSync, watch, writeFileSync } from "node:fs";-import { resolve, join, basename, extname } from "node:path";-import { transformSync } from "esbuild";+import { resolve, join, extname } from "node:path";+import { MIME_BY_EXT, SCRIPTS_NOTE_ID, codeNoteId, renderNoteId, deployScript, parseScriptMeta, transpile, asNoteService } from "./deploy";// ── Environment — must be set before any server module is imported ──────────const DATA_DIR = resolve(__dirname, "../data");@@ -25,86 +25,8 @@ process.env.TRILIUM_ENV = "dev";// ── Constants ───────────────────────────────────────────────────────────────const SCRIPTS_DIR = resolve(__dirname, "../scripts");-const SCRIPTS_NOTE_ID = "_scripts";const needsInit = !existsSync(join(DATA_DIR, "document.db"));-const MIME_BY_EXT: Record<string, string> = {- ".jsx": "text/jsx",- ".tsx": "text/jsx",- ".js": "application/javascript;env=frontend",- ".ts": "application/javascript;env=backend",- ".html": "text/html",- ".css": "text/css",-};--/** Extensions that need esbuild transpilation before deployment. */-const TRANSPILE_EXTS = new Set([".ts", ".tsx"]);--/**- * Strips TypeScript type annotations via esbuild, preserving JSX intact.- * Trilium's frontend handles JSX natively, so we only strip types.- */-function transpile(source: string, filePath: string): string {- const ext = extname(filePath);- if (!TRANSPILE_EXTS.has(ext)) return source;-- const result = transformSync(source, {- loader: ext === ".tsx" ? "tsx" : "ts",- jsx: "preserve",- sourcemap: false,- });- return result.code;-}--// ── Front matter parsing ────────────────────────────────────────────────────--interface ScriptMeta {- id: string;- type: string;- title: string;- [key: string]: string;-}--/**- * Parses the @trilium-script YAML front matter from a JSDoc comment block.- *- * /**- * * @trilium-script- * *- * * id: my-script- * * type: render- * * title: My Script- * *\/- */-function parseScriptMeta(source: string, filePath: string): ScriptMeta | null {- const match = source.match(/\/\*\*[\s\S]*?@trilium-script\s*([\s\S]*?)\*\//);- if (!match) return null;-- const block = match[1];- const meta: Record<string, string> = {};-- for (const line of block.split("\n")) {- // Strip leading ` * ` prefix and trim.- const cleaned = line.replace(/^\s*\*\s?/, "").trim();- if (!cleaned) continue;-- const colon = cleaned.indexOf(":");- if (colon === -1) continue;-- const key = cleaned.slice(0, colon).trim();- const value = cleaned.slice(colon + 1).trim();- if (key && value) meta[key] = value;- }-- const missing = ["id", "type", "title"].filter((k) => !meta[k]);- if (missing.length) {- console.error(` SKIP ${filePath}: missing required fields: ${missing.join(", ")}`);- return null;- }-- return meta as ScriptMeta;-}-async function ensureTranslations() {const i18n = await import("@triliumnext/server/src/services/i18n.js");await i18n.initializeTranslations();@@ -186,55 +108,11 @@ async function deployScripts() {if (!meta) continue;const mime = MIME_BY_EXT[extname(file)]!;- const codeNoteId = `_sd_${meta.id}`;const content = transpile(source, file);cls.init(() => {- const existing = becca.notes[codeNoteId];- if (existing) {- // Update content and title of existing note.- existing.title = meta.title;- existing.save();- existing.setContent(content);- console.log(` Updated: ${meta.title} (${codeNoteId})`);- } else if (meta.type === "render") {- // Create a render note under Scripts, with the code note- // as its child linked via ~renderNote.- const renderNoteId = `_sd_${meta.id}_render`;- notesService.createNewNote({- noteId: renderNoteId,- parentNoteId: SCRIPTS_NOTE_ID,- title: meta.title,- type: "render",- content: "",- });-- notesService.createNewNote({- noteId: codeNoteId,- parentNoteId: renderNoteId,- title: meta.title,- type: "code",- mime,- content,- });-- const renderNote = becca.notes[renderNoteId];- renderNote.setRelation("renderNote", codeNoteId);-- console.log(` Created: ${meta.title} (${meta.type})`);- } else {- // Plain code note (widget, backend script, etc.)- notesService.createNewNote({- noteId: codeNoteId,- parentNoteId: SCRIPTS_NOTE_ID,- title: meta.title,- type: "code",- mime,- content,- });-- console.log(` Created: ${meta.title} (${meta.type})`);- }+ const result = deployScript(meta, content, mime, becca, asNoteService(notesService));+ console.log(` ${result.action === "created" ? "Created" : "Updated"}: ${result.title} (${result.codeNoteId})`);});}}@@ -243,7 +121,7 @@ function watchScripts() {// Debounce per file — editors can fire multiple events on a single save.const timers = new Map<string, ReturnType<typeof setTimeout>>();- watch(SCRIPTS_DIR, (eventType, filename) => {+ watch(SCRIPTS_DIR, (_eventType, filename) => {if (!filename || !MIME_BY_EXT[extname(filename)]) return;if (timers.has(filename)) clearTimeout(timers.get(filename));@@ -261,15 +139,14 @@ function watchScripts() {const meta = parseScriptMeta(source, filename);if (!meta) return;- const codeNoteId = `_sd_${meta.id}`;+ const noteId = codeNoteId(meta.id);- // Already in memory from deployScripts(), import() returns from cache.const becca = (await import("@triliumnext/server/src/becca/becca.js")).default;const cls = (await import("@triliumnext/server/src/services/cls.js")).default;- const note = becca.notes[codeNoteId];+ const note = becca.notes[noteId];if (!note) {- console.log(` [watch] ${filename}: note ${codeNoteId} not found, restart to create.`);+ console.log(` [watch] ${filename}: note ${noteId} not found, restart to create.`);return;}@@ -279,25 +156,25 @@ function watchScripts() {note.setContent(content);});- // For render scripts, trigger a refresh of the active render note- // by injecting a small client-side script via websocket.+ // For render scripts, trigger a refresh of all contexts viewing+ // the render note by injecting a client-side script via websocket.if (meta.type === "render") {const ws = (await import("@triliumnext/server/src/services/ws.js")).default;- const renderNoteId = `_sd_${meta.id}_render`;+ const renderId = renderNoteId(meta.id);ws.sendMessageToAllClients({type: "execute-script",script: `function() {for (const ctx of api.getNoteContexts()) {- if (ctx.noteId === "${renderNoteId}") {+ if (ctx.noteId === "${renderId}") {api.triggerEvent("refreshData", { ntxId: ctx.ntxId });console.log("[script-deployer] refreshed", "${meta.title}", "in context", ctx.ntxId);}}}`,params: [],- currentNoteId: codeNoteId,+ currentNoteId: noteId,originEntityName: "notes",- originEntityId: codeNoteId,+ originEntityId: noteId,});}diff --git a/apps/script-deployer/vite.config.mts b/apps/script-deployer/vite.config.mtsnew file mode 100644index 0000000000..6477713f68--- /dev/null+++ b/apps/script-deployer/vite.config.mts@@ -0,0 +1,20 @@+/// <reference types='vitest' />+import { defineConfig } from "vite";++export default defineConfig(() => ({+ root: __dirname,+ test: {+ watch: false,+ globals: true,+ environment: "node",+ env: {+ NODE_ENV: "development",+ TRILIUM_DATA_DIR: "./data",+ TRILIUM_INTEGRATION_TEST: "memory",+ TRILIUM_RESOURCE_DIR: "../server/src",+ TRILIUM_ENV: "dev",+ },+ include: ["src/**/*.{test,spec}.ts"],+ testTimeout: 20_000,+ },+}));