Skip to content

Build your personal knowledge base with Trilium Notes

test(core): add more route tests

Elian Doran6d0e0cef164f
diff --git a/packages/trilium-core/src/routes/api/app_info.spec.ts b/packages/trilium-core/src/routes/api/app_info.spec.ts
new file mode 100644
index 0000000000..6411410073
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/app_info.spec.ts
@@ -0,0 +1,47 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core app-info route through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface AppInfoResponse {
+ appVersion: string;
+ dbVersion: number;
+ syncVersion: number;
+ buildDate: string;
+ buildRevision: string;
+ clipperProtocolVersion: string;
+ utcDateTime: string;
+}
+
+describe("App info API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns the installation info object", async () => {
+ const res = await api.get<AppInfoResponse>("/api/app-info");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ appVersion: expect.any(String),
+ dbVersion: expect.any(Number),
+ syncVersion: expect.any(Number),
+ buildDate: expect.any(String),
+ buildRevision: expect.any(String),
+ clipperProtocolVersion: expect.any(String),
+ utcDateTime: expect.any(String)
+ });
+ });
+
+ it("returns a parseable ISO timestamp for utcDateTime", async () => {
+ const res = await api.get<AppInfoResponse>("/api/app-info");
+
+ expect(res.status).toBe(200);
+ expect(Number.isNaN(Date.parse(res.body.utcDateTime))).toBe(false);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
new file mode 100644
index 0000000000..4d1ec649a3
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -0,0 +1,202 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { getSql } from "../../services/sql/index";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core attachment routes through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface AttachmentPojo {
+ attachmentId: string;
+ ownerId: string;
+ role: string;
+ mime: string;
+ title?: string;
+ blobId: string;
+}
+
+interface ConvertResponse {
+ note: { noteId: string };
+ branch: { parentNoteId: string };
+}
+
+/**
+ * Saves an attachment on the given note and returns it back by reading the
+ * note's attachment list (the save route itself returns 204 with no body).
+ */
+async function saveAttachment(
+ noteId: string,
+ { title = "Saved attachment", content = "attachment body" } = {}
+): Promise<AttachmentPojo> {
+ const save = await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "file", mime: "text/plain", title, content }
+ });
+ expect(save.status).toBe(204);
+
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const attachment = list.body.find((a) => a.title === title);
+ expect(attachment).toBeTruthy();
+ return attachment as AttachmentPojo;
+}
+
+function attachmentIsDeleted(attachmentId: string): number | null {
+ const row = getSql().getRowOrNull<{ isDeleted: number }>(
+ "SELECT isDeleted FROM attachments WHERE attachmentId = ?",
+ [ attachmentId ]
+ );
+ return row ? row.isDeleted : null;
+}
+
+describe("Attachments API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("reading", () => {
+ it("returns an empty attachment list for a fresh note", async () => {
+ const { noteId } = await createTextNote(api, { title: "No attachments" });
+
+ const res = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body).toHaveLength(0);
+ });
+
+ it("404s when listing attachments of a missing note", async () => {
+ const res = await api.get("/api/notes/missingNote123/attachments");
+ expect(res.status).toBe(404);
+ });
+
+ it("returns a single attachment by id", async () => {
+ const { noteId } = await createTextNote(api, { title: "Owner" });
+ const saved = await saveAttachment(noteId, { title: "By id" });
+
+ const res = await api.get<AttachmentPojo>(`/api/attachments/${saved.attachmentId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.attachmentId).toBe(saved.attachmentId);
+ expect(res.body.ownerId).toBe(noteId);
+ expect(res.body.title).toBe("By id");
+ });
+
+ it("404s for a missing attachment", async () => {
+ const res = await api.get("/api/attachments/missingAttachment123");
+ expect(res.status).toBe(404);
+ });
+
+ it("returns all attachments of the owning note via /all", async () => {
+ const { noteId } = await createTextNote(api, { title: "Owner of two" });
+ const first = await saveAttachment(noteId, { title: "First" });
+ await saveAttachment(noteId, { title: "Second" });
+
+ const res = await api.get<AttachmentPojo[]>(
+ `/api/attachments/${first.attachmentId}/all`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.map((a) => a.title).sort()).toEqual([ "First", "Second" ]);
+ });
+
+ it("returns the attachment blob", async () => {
+ const { noteId } = await createTextNote(api, { title: "Blob owner" });
+ const saved = await saveAttachment(noteId, {
+ title: "Blob attachment",
+ content: "blob content here"
+ });
+
+ const res = await api.get<{ blobId: string; content: string }>(
+ `/api/attachments/${saved.attachmentId}/blob`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.blobId).toBeTruthy();
+ expect(res.body.content).toContain("blob content here");
+ });
+ });
+
+ describe("saving", () => {
+ it("creates an attachment that can be read back", async () => {
+ const { noteId } = await createTextNote(api, { title: "Save target" });
+ const saved = await saveAttachment(noteId, { title: "Round trip" });
+
+ expect(saved.attachmentId).toBeTruthy();
+ expect(saved.role).toBe("file");
+ expect(saved.mime).toBe("text/plain");
+ });
+
+ it("404s when saving an attachment on a missing note", async () => {
+ const res = await api.post("/api/notes/missingNote123/attachments", {
+ body: { role: "file", mime: "text/plain", title: "x", content: "y" }
+ });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("renaming", () => {
+ it("renames an attachment and returns the new title on read", async () => {
+ const { noteId } = await createTextNote(api, { title: "Rename owner" });
+ const saved = await saveAttachment(noteId, { title: "Old title" });
+
+ const rename = await api.put(`/api/attachments/${saved.attachmentId}/rename`, {
+ body: { title: "New title" }
+ });
+ expect(rename.status).toBe(204);
+
+ const res = await api.get<AttachmentPojo>(`/api/attachments/${saved.attachmentId}`);
+ expect(res.body.title).toBe("New title");
+ });
+
+ it("400s when renaming to an empty title", async () => {
+ const { noteId } = await createTextNote(api, { title: "Bad rename owner" });
+ const saved = await saveAttachment(noteId, { title: "Keep me" });
+
+ const res = await api.put(`/api/attachments/${saved.attachmentId}/rename`, {
+ body: { title: " " }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("converting to a note", () => {
+ it("converts an attachment into a child note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Convert owner" });
+ const saved = await saveAttachment(noteId, { title: "Becomes a note" });
+
+ const res = await api.post<ConvertResponse>(
+ `/api/attachments/${saved.attachmentId}/convert-to-note`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.note.noteId).toBeTruthy();
+ expect(res.body.branch.parentNoteId).toBe(noteId);
+
+ // The converted attachment is soft-deleted.
+ expect(attachmentIsDeleted(saved.attachmentId)).toBe(1);
+ });
+
+ it("404s when converting a missing attachment", async () => {
+ const res = await api.post("/api/attachments/missingAttachment123/convert-to-note");
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("deleting", () => {
+ it("soft-deletes an attachment", async () => {
+ const { noteId } = await createTextNote(api, { title: "Delete owner" });
+ const saved = await saveAttachment(noteId, { title: "To delete" });
+ expect(attachmentIsDeleted(saved.attachmentId)).toBe(0);
+
+ const del = await api.delete(`/api/attachments/${saved.attachmentId}`);
+ expect(del.status).toBe(204);
+ expect(attachmentIsDeleted(saved.attachmentId)).toBe(1);
+
+ const res = await api.get(`/api/attachments/${saved.attachmentId}`);
+ expect(res.status).toBe(404);
+ });
+
+ it("is a no-op (204) when deleting a missing attachment", async () => {
+ const res = await api.delete("/api/attachments/missingAttachment123");
+ expect(res.status).toBe(204);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/autocomplete.spec.ts b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
new file mode 100644
index 0000000000..f9f1a4779b
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/autocomplete.spec.ts
@@ -0,0 +1,79 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core autocomplete routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface AutocompleteResult {
+ notePath: string;
+ noteTitle: string;
+ notePathTitle: string;
+ highlightedNotePathTitle: string;
+ icon: string;
+}
+
+describe("Autocomplete API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("getAutocomplete", () => {
+ it("returns matching notes for a search query", async () => {
+ const title = `Autocomplete target ${Date.now()}`;
+ await createTextNote(api, { title });
+
+ const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
+ query: { query: title }
+ });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+
+ const match = res.body.find((r) => r.noteTitle === title);
+ expect(match).toBeTruthy();
+ expect(match?.notePath).toBeTruthy();
+ expect(typeof match?.highlightedNotePathTitle).toBe("string");
+ expect(match?.icon).toBeTruthy();
+ });
+
+ it("returns recent notes for an empty query", async () => {
+ const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
+ query: { query: "" }
+ });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ });
+
+ it("honours the fastSearch flag", async () => {
+ const res = await api.get<AutocompleteResult[]>("/api/autocomplete", {
+ query: { query: "root", fastSearch: "false" }
+ });
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ });
+
+ it("400s when the query param is missing", async () => {
+ const res = await api.get("/api/autocomplete");
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("getNotesCount", () => {
+ it("returns the count of non-deleted notes as a number", async () => {
+ const before = await api.get<number>("/api/autocomplete/notesCount");
+ expect(before.status).toBe(200);
+ expect(typeof before.body).toBe("number");
+ expect(before.body).toBeGreaterThan(0);
+
+ await createTextNote(api, { title: "Counts towards total" });
+
+ const after = await api.get<number>("/api/autocomplete/notesCount");
+ expect(after.status).toBe(200);
+ expect(after.body).toBeGreaterThan(before.body);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/backend_log.spec.ts b/packages/trilium-core/src/routes/api/backend_log.spec.ts
new file mode 100644
index 0000000000..d7375cb9a1
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/backend_log.spec.ts
@@ -0,0 +1,23 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core backend-log route through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+describe("Backend log API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns the backend log contents as text", async () => {
+ const res = await api.get<string>("/api/backend-log");
+ expect(res.status).toBe(200);
+ // The handler returns a plain string (the log contents, or a fallback
+ // message when no log file is available); never assert on the exact text.
+ expect(typeof res.body).toBe("string");
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/branches.spec.ts b/packages/trilium-core/src/routes/api/branches.spec.ts
new file mode 100644
index 0000000000..033de47374
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/branches.spec.ts
@@ -0,0 +1,200 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { getSql } from "../../services/sql/index";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core branch routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface BranchRow {
+ parentNoteId: string;
+ prefix: string | null;
+ isExpanded: number;
+ isDeleted: number;
+}
+
+function getBranchRow(branchId: string): BranchRow | null {
+ return getSql().getRowOrNull<BranchRow>(
+ "SELECT parentNoteId, prefix, isExpanded, isDeleted FROM branches WHERE branchId = ?",
+ [ branchId ]
+ );
+}
+
+describe("Branches API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("moving", () => {
+ it("moves a branch under a different parent and returns the new clone", async () => {
+ const parent = await createTextNote(api, { title: "Move target parent" });
+ const child = await createTextNote(api, { title: "Branch to move" });
+
+ const res = await api.put<{ success: boolean; branch?: { parentNoteId: string } }>(
+ `/api/branches/${child.branchId}/move-to/${parent.branchId}`
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.branch?.parentNoteId).toBe(parent.noteId);
+ // The original branch is replaced by a clone under the new parent.
+ expect(getBranchRow(child.branchId)?.isDeleted).toBe(1);
+ });
+
+ it("400s when moving a non-existent branch", async () => {
+ const parent = await createTextNote(api, { title: "Has a valid parent branch" });
+ const res = await api.put(`/api/branches/missingBranch123/move-to/${parent.branchId}`);
+ expect(res.status).toBe(400);
+ });
+
+ it("reorders a branch before a sibling", async () => {
+ const parent = await createTextNote(api, { title: "Reorder parent" });
+ const parentId = parent.noteId;
+ const first = await createTextNote(api, { parentNoteId: parentId, title: "First" });
+ const second = await createTextNote(api, { parentNoteId: parentId, title: "Second" });
+
+ const res = await api.put<{ success: boolean }>(
+ `/api/branches/${second.branchId}/move-before/${first.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ });
+
+ it("reorders a branch after a sibling", async () => {
+ const parent = await createTextNote(api, { title: "Reorder after parent" });
+ const parentId = parent.noteId;
+ const first = await createTextNote(api, { parentNoteId: parentId, title: "First" });
+ const second = await createTextNote(api, { parentNoteId: parentId, title: "Second" });
+
+ const res = await api.put<{ success: boolean }>(
+ `/api/branches/${first.branchId}/move-after/${second.branchId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ });
+
+ it("404s when moving before a non-existent branch", async () => {
+ const child = await createTextNote(api, { title: "Movable child" });
+ const res = await api.put(
+ `/api/branches/${child.branchId}/move-before/missingBranch123`
+ );
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("expanding", () => {
+ it("sets and clears the expanded flag on a branch", async () => {
+ const { branchId } = await createTextNote(api, { title: "Expandable" });
+
+ const expand = await api.put(`/api/branches/${branchId}/expanded/1`);
+ expect(expand.status).toBe(204);
+ expect(getBranchRow(branchId)?.isExpanded).toBe(1);
+
+ const collapse = await api.put(`/api/branches/${branchId}/expanded/0`);
+ expect(collapse.status).toBe(204);
+ expect(getBranchRow(branchId)?.isExpanded).toBe(0);
+ });
+
+ it("expands a subtree and returns the affected branch ids", async () => {
+ const parent = await createTextNote(api, { title: "Subtree root" });
+ await createTextNote(api, { parentNoteId: parent.noteId, title: "Subtree child" });
+
+ const res = await api.put<{ branchIds: string[] }>(
+ `/api/branches/${parent.branchId}/expanded-subtree/1`
+ );
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body.branchIds)).toBe(true);
+ expect(res.body.branchIds).toContain(parent.branchId);
+ });
+ });
+
+ describe("prefixes", () => {
+ it("sets a prefix on a single branch", async () => {
+ const { branchId } = await createTextNote(api, { title: "Prefixable" });
+
+ const res = await api.put(`/api/branches/${branchId}/set-prefix`, {
+ body: { prefix: "Chapter 1" }
+ });
+ expect(res.status).toBe(204);
+ expect(getBranchRow(branchId)?.prefix).toBe("Chapter 1");
+ });
+
+ it("clears the prefix when given whitespace", async () => {
+ const { branchId } = await createTextNote(api, { title: "Prefix clearable" });
+
+ await api.put(`/api/branches/${branchId}/set-prefix`, { body: { prefix: "keep" } });
+ const clear = await api.put(`/api/branches/${branchId}/set-prefix`, {
+ body: { prefix: " " }
+ });
+ expect(clear.status).toBe(204);
+ expect(getBranchRow(branchId)?.prefix).toBeNull();
+ });
+
+ it("404s when setting a prefix on a missing branch", async () => {
+ const res = await api.put("/api/branches/missingBranch123/set-prefix", {
+ body: { prefix: "nope" }
+ });
+ expect(res.status).toBe(404);
+ });
+
+ it("sets a prefix on a batch of branches and skips unknown ids", async () => {
+ const a = await createTextNote(api, { title: "Batch A" });
+ const b = await createTextNote(api, { title: "Batch B" });
+
+ const res = await api.put<{ success: boolean; count: number }>(
+ "/api/branches/set-prefix-batch",
+ {
+ body: {
+ branchIds: [ a.branchId, b.branchId, "missingBranch123" ],
+ prefix: "batch"
+ }
+ }
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.count).toBe(2);
+ expect(getBranchRow(a.branchId)?.prefix).toBe("batch");
+ expect(getBranchRow(b.branchId)?.prefix).toBe("batch");
+ });
+
+ it("400s when branchIds is not an array", async () => {
+ const res = await api.put("/api/branches/set-prefix-batch", {
+ body: { branchIds: "not-an-array", prefix: "x" }
+ });
+ expect(res.status).toBe(400);
+ });
+
+ it("400s when the prefix is not a string", async () => {
+ const { branchId } = await createTextNote(api, { title: "Bad prefix type" });
+ const res = await api.put("/api/branches/set-prefix-batch", {
+ body: { branchIds: [ branchId ], prefix: 123 }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("deleting", () => {
+ it("deletes a branch and reports whether the note was deleted", async () => {
+ const { branchId } = await createTextNote(api, { title: "To delete" });
+ expect(getBranchRow(branchId)?.isDeleted).toBe(0);
+
+ const res = await api.delete<{ noteDeleted: boolean }>(`/api/branches/${branchId}`, {
+ query: { taskId: "test-branch-delete", last: "true" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.noteDeleted).toBe(true);
+ expect(getBranchRow(branchId)?.isDeleted).toBe(1);
+ });
+
+ it("404s when deleting a non-existent branch", async () => {
+ const res = await api.delete("/api/branches/missingBranch123", {
+ query: { taskId: "test-branch-delete-missing", last: "true" }
+ });
+ expect(res.status).toBe(404);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/bulk_action.spec.ts b/packages/trilium-core/src/routes/api/bulk_action.spec.ts
new file mode 100644
index 0000000000..06b0ce7fcb
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/bulk_action.spec.ts
@@ -0,0 +1,140 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core bulk-action routes through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface AffectedCount {
+ affectedNoteCount: number;
+}
+
+interface Attribute {
+ type: string;
+ name: string;
+ value: string;
+}
+
+function getLabels(noteId: string) {
+ return api.get<Attribute[]>(`/api/notes/${noteId}/attributes`);
+}
+
+describe("Bulk action API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("affected note count", () => {
+ it("counts a single existing note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Affected single" });
+
+ const res = await api.post<AffectedCount>("/api/bulk-action/affected-notes", {
+ body: { noteIds: [ noteId ], includeDescendants: false }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.affectedNoteCount).toBe(1);
+ });
+
+ it("includes descendants when requested", async () => {
+ const { noteId: parentId } = await createTextNote(api, { title: "Affected parent" });
+ await createTextNote(api, { parentNoteId: parentId, title: "Affected child" });
+
+ const shallow = await api.post<AffectedCount>("/api/bulk-action/affected-notes", {
+ body: { noteIds: [ parentId ], includeDescendants: false }
+ });
+ const deep = await api.post<AffectedCount>("/api/bulk-action/affected-notes", {
+ body: { noteIds: [ parentId ], includeDescendants: true }
+ });
+
+ expect(shallow.body.affectedNoteCount).toBe(1);
+ expect(deep.body.affectedNoteCount).toBeGreaterThan(shallow.body.affectedNoteCount);
+ });
+
+ it("ignores note IDs that do not exist", async () => {
+ const res = await api.post<AffectedCount>("/api/bulk-action/affected-notes", {
+ body: { noteIds: [ "missingNote123" ], includeDescendants: false }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.affectedNoteCount).toBe(0);
+ });
+ });
+
+ describe("executing actions", () => {
+ it("adds a label to the targeted notes (round-trip)", async () => {
+ const { noteId } = await createTextNote(api, { title: "Label target" });
+
+ const exec = await api.post("/api/bulk-action/execute", {
+ body: {
+ noteIds: [ noteId ],
+ includeDescendants: false,
+ actions: [
+ { name: "addLabel", labelName: "bulkAdded", labelValue: "yes" }
+ ]
+ }
+ });
+ expect(exec.status).toBe(204);
+
+ const after = await getLabels(noteId);
+ const added = after.body.find((attr) => attr.name === "bulkAdded");
+ expect(added).toBeTruthy();
+ expect(added?.value).toBe("yes");
+ });
+
+ it("deletes a label from the targeted notes (round-trip)", async () => {
+ const { noteId } = await createTextNote(api, { title: "Label removal target" });
+
+ await api.post("/api/bulk-action/execute", {
+ body: {
+ noteIds: [ noteId ],
+ actions: [
+ { name: "addLabel", labelName: "toRemove", labelValue: "1" }
+ ]
+ }
+ });
+ const withLabel = await getLabels(noteId);
+ expect(withLabel.body.some((attr) => attr.name === "toRemove")).toBe(true);
+
+ const exec = await api.post("/api/bulk-action/execute", {
+ body: {
+ noteIds: [ noteId ],
+ actions: [ { name: "deleteLabel", labelName: "toRemove" } ]
+ }
+ });
+ expect(exec.status).toBe(204);
+
+ const afterDelete = await getLabels(noteId);
+ expect(afterDelete.body.some((attr) => attr.name === "toRemove")).toBe(false);
+ });
+
+ it("falls back to the _bulkAction note when no actions are provided", async () => {
+ const { noteId } = await createTextNote(api, { title: "No actions" });
+
+ const exec = await api.post("/api/bulk-action/execute", {
+ body: { noteIds: [ noteId ], actions: [] }
+ });
+ expect(exec.status).toBe(204);
+ });
+ });
+
+ describe("error handling", () => {
+ it("errors when noteIds is not an array", async () => {
+ const res = await api.post("/api/bulk-action/execute", {
+ body: { noteIds: "not-an-array", actions: [] }
+ });
+ expect(res.status).toBe(500);
+ });
+
+ it("errors when an action is missing a name", async () => {
+ const { noteId } = await createTextNote(api, { title: "Bad action" });
+
+ const res = await api.post("/api/bulk-action/execute", {
+ body: { noteIds: [ noteId ], actions: [ { labelName: "x" } ] }
+ });
+ expect(res.status).toBe(500);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/cloning.spec.ts b/packages/trilium-core/src/routes/api/cloning.spec.ts
new file mode 100644
index 0000000000..c07fcdd996
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/cloning.spec.ts
@@ -0,0 +1,210 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { getSql } from "../../services/sql/index";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core cloning routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ *
+ * The cloning service never throws for invalid input — it always returns a JSON
+ * payload with `{ success: boolean }`, so the "error" paths here assert on
+ * `res.body.success` (status stays 200) rather than on HTTP status codes.
+ */
+interface CloneResult {
+ success: boolean;
+ message?: string;
+ branchId?: string;
+ notePath?: string;
+}
+
+let api: CoreApiTester;
+
+function branchRow(branchId: string) {
+ return getSql().getRowOrNull<{
+ noteId: string;
+ parentNoteId: string;
+ prefix: string | null;
+ isDeleted: number;
+ }>(
+ "SELECT noteId, parentNoteId, prefix, isDeleted FROM branches WHERE branchId = ?",
+ [ branchId ]
+ );
+}
+
+describe("Cloning API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("clone-to-note", () => {
+ it("clones a note under another parent note and persists the branch", async () => {
+ const child = await createTextNote(api, { title: "Cloneable" });
+ const target = await createTextNote(api, { title: "Clone target" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-to-note/${target.noteId}`,
+ { body: { prefix: "myPrefix" } }
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.branchId).toBeTruthy();
+ expect(res.body.notePath).toContain(child.noteId);
+
+ const row = branchRow(res.body.branchId!);
+ expect(row).toMatchObject({
+ noteId: child.noteId,
+ parentNoteId: target.noteId,
+ prefix: "myPrefix",
+ isDeleted: 0
+ });
+ });
+
+ it("reports failure when the parent note does not exist", async () => {
+ const child = await createTextNote(api, { title: "Orphan clone" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-to-note/missingParent123`,
+ { body: {} }
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
+ });
+
+ describe("clone-to-branch", () => {
+ it("clones a note into the parent of an existing branch", async () => {
+ const child = await createTextNote(api, { title: "Branch cloneable" });
+ const target = await createTextNote(api, { title: "Branch target" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-to-branch/${target.branchId}`,
+ { body: { prefix: "branchPrefix" } }
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.branchId).toBeTruthy();
+
+ const row = branchRow(res.body.branchId!);
+ expect(row).toMatchObject({
+ noteId: child.noteId,
+ parentNoteId: target.noteId,
+ prefix: "branchPrefix",
+ isDeleted: 0
+ });
+ });
+
+ it("reports failure for a missing parent branch", async () => {
+ const child = await createTextNote(api, { title: "No branch" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-to-branch/missingBranch123`,
+ { body: {} }
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
+ });
+
+ describe("clone-after", () => {
+ it("clones a note after an existing sibling branch", async () => {
+ const host = await createTextNote(api, { title: "Clone-after host" });
+ const sibling = await createTextNote(api, {
+ parentNoteId: host.noteId,
+ title: "Existing sibling"
+ });
+ // Cloning into `host` only succeeds if the child isn't already there,
+ // so the cloned note lives elsewhere (under root).
+ const child = await createTextNote(api, { title: "After cloneable" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-after/${sibling.branchId}`
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.branchId).toBeTruthy();
+
+ const row = branchRow(res.body.branchId!);
+ expect(row).toMatchObject({
+ noteId: child.noteId,
+ parentNoteId: host.noteId,
+ isDeleted: 0
+ });
+ });
+
+ it("refuses to clone the root note", async () => {
+ const sibling = await createTextNote(api, { title: "Root guard sibling" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/root/clone-after/${sibling.branchId}`
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
+
+ it("reports failure for a missing after-branch", async () => {
+ const child = await createTextNote(api, { title: "After missing" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/clone-after/missingAfter123`
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
+ });
+
+ describe("toggle-in-parent", () => {
+ it("adds and then removes a note from a parent", async () => {
+ const child = await createTextNote(api, { title: "Toggleable" });
+ const target = await createTextNote(api, { title: "Toggle target" });
+
+ interface ToggleAddResult {
+ success: boolean;
+ branch: { branchId: string; parentNoteId: string; noteId: string } | null;
+ }
+ const add = await api.put<ToggleAddResult>(
+ `/api/notes/${child.noteId}/toggle-in-parent/${target.noteId}/true`
+ );
+ expect(add.status).toBe(200);
+ expect(add.body.success).toBe(true);
+ expect(add.body.branch).toMatchObject({
+ noteId: child.noteId,
+ parentNoteId: target.noteId
+ });
+
+ const addedBranchId = add.body.branch!.branchId;
+ expect(branchRow(addedBranchId)?.isDeleted).toBe(0);
+
+ const remove = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/toggle-in-parent/${target.noteId}/false`
+ );
+ expect(remove.status).toBe(200);
+ expect(remove.body.success).toBe(true);
+ expect(branchRow(addedBranchId)?.isDeleted).toBe(1);
+ });
+
+ it("refuses to remove the only parent of a note", async () => {
+ const child = await createTextNote(api, { title: "Single parent" });
+
+ const res = await api.put<CloneResult>(
+ `/api/notes/${child.noteId}/toggle-in-parent/root/false`
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(res.body.message).toBeTruthy();
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
new file mode 100644
index 0000000000..c54bf49760
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -0,0 +1,104 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core file/attachment download routes through
+ * {@link CoreApiTester} (no Express). These handlers write directly to the
+ * response via `res.send(...)`, so the driver captures their status, headers
+ * and (JSON round-tripped) body. The spec runs under both the node and
+ * standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface AttachmentPojo {
+ attachmentId: string;
+ title: string;
+ mime: string;
+}
+
+describe("Files API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("note download/open", () => {
+ it("downloads the content of a note with the content-type header", async () => {
+ const { noteId } = await createTextNote(api, { content: "<p>downloadable</p>" });
+
+ const res = await api.get<string>(`/api/notes/${noteId}/download`);
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("downloadable");
+ expect(res.headers["Content-Type"]).toBeTruthy();
+ expect(res.headers["Content-Disposition"]).toBeTruthy();
+ });
+
+ it("opens a note inline without a content-disposition header", async () => {
+ const { noteId } = await createTextNote(api, { content: "<p>inline view</p>" });
+
+ const res = await api.get<string>(`/api/notes/${noteId}/open`);
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("inline view");
+ expect(res.headers["Content-Disposition"]).toBeUndefined();
+ });
+
+ it("supports the legacy /api/notes/download/:noteId path", async () => {
+ const { noteId } = await createTextNote(api, { content: "<p>legacy</p>" });
+
+ const res = await api.get<string>(`/api/notes/download/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("legacy");
+ });
+
+ it("404s when downloading a missing note", async () => {
+ const res = await api.get("/api/notes/missingNote123/download");
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("attachment download/open", () => {
+ async function createAttachment(): Promise<{ noteId: string; attachmentId: string }> {
+ const { noteId } = await createTextNote(api, { title: "Has attachment" });
+
+ const save = await api.post(`/api/notes/${noteId}/attachments`, {
+ body: {
+ role: "file",
+ mime: "text/plain",
+ title: "attachment.txt",
+ content: "attachment payload"
+ }
+ });
+ expect(save.status).toBe(204);
+
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ expect(list.status).toBe(200);
+ expect(list.body.length).toBeGreaterThan(0);
+
+ return { noteId, attachmentId: list.body[0].attachmentId };
+ }
+
+ it("downloads an attachment created via the API", async () => {
+ const { attachmentId } = await createAttachment();
+
+ const res = await api.get<string>(`/api/attachments/${attachmentId}/download`);
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("attachment payload");
+ expect(res.headers["Content-Disposition"]).toBeTruthy();
+ });
+
+ it("opens an attachment inline without a content-disposition header", async () => {
+ const { attachmentId } = await createAttachment();
+
+ const res = await api.get<string>(`/api/attachments/${attachmentId}/open`);
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("attachment payload");
+ expect(res.headers["Content-Disposition"]).toBeUndefined();
+ });
+
+ it("404s when downloading a missing attachment", async () => {
+ const res = await api.get("/api/attachments/missingAttachment123/download");
+ expect(res.status).toBe(404);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/keys.spec.ts b/packages/trilium-core/src/routes/api/keys.spec.ts
new file mode 100644
index 0000000000..fab7d43db6
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/keys.spec.ts
@@ -0,0 +1,77 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core keyboard routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface KeyboardAction {
+ actionName?: string;
+ scope?: string;
+ defaultShortcuts?: string[];
+ effectiveShortcuts?: string[];
+ separator?: string;
+}
+
+interface ShortcutAttribute {
+ attributeId: string;
+ noteId: string;
+ type: string;
+ name: string;
+ value: string;
+}
+
+describe("Keys API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("keyboard actions", () => {
+ it("returns the list of keyboard actions with their definitions", async () => {
+ const res = await api.get<KeyboardAction[]>("/api/keyboard-actions");
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body.length).toBeGreaterThan(0);
+
+ const named = res.body.find((action) => action.actionName === "jumpToNote");
+ expect(named).toBeDefined();
+ expect(named?.scope).toBeTruthy();
+ // effectiveShortcuts is derived from defaultShortcuts when no option overrides it.
+ expect(Array.isArray(named?.effectiveShortcuts)).toBe(true);
+ });
+ });
+
+ describe("keyboard shortcuts for notes", () => {
+ it("returns an array of keyboardShortcut label attributes", async () => {
+ const res = await api.get<ShortcutAttribute[]>("/api/keyboard-shortcuts-for-notes");
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+
+ for (const attr of res.body) {
+ expect(attr.name).toBe("keyboardShortcut");
+ expect(attr.type).toBe("label");
+ }
+ });
+
+ it("includes a newly added keyboardShortcut label on a note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Shortcut host" });
+
+ const add = await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name: "keyboardShortcut", value: "Ctrl+Alt+Z" }
+ });
+ expect(add.status).toBe(204);
+
+ const res = await api.get<ShortcutAttribute[]>("/api/keyboard-shortcuts-for-notes");
+ expect(res.status).toBe(200);
+
+ const added = res.body.find((attr) => attr.noteId === noteId);
+ expect(added).toBeDefined();
+ expect(added?.name).toBe("keyboardShortcut");
+ expect(added?.value).toBe("Ctrl+Alt+Z");
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/others.spec.ts b/packages/trilium-core/src/routes/api/others.spec.ts
new file mode 100644
index 0000000000..365762d33f
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/others.spec.ts
@@ -0,0 +1,90 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core "other" routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+describe("Others API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("icon usage", () => {
+ it("returns a map of user-set icon classes to counts", async () => {
+ const res = await api.get<{ iconClassToCountMap: Record<string, number> }>(
+ "/api/other/icon-usage"
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.iconClassToCountMap).toBeTypeOf("object");
+ });
+
+ it("counts an iconClass label added to a user note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Icon note" });
+ const add = await api.post(`/api/notes/${noteId}/attributes`, {
+ body: { type: "label", name: "iconClass", value: "bx bx-test-icon-usage" }
+ });
+ expect(add.status).toBe(204);
+
+ const res = await api.get<{ iconClassToCountMap: Record<string, number> }>(
+ "/api/other/icon-usage"
+ );
+ expect(res.status).toBe(200);
+ // The "bx" prefix is stripped; the specific class is counted.
+ expect(res.body.iconClassToCountMap["bx-test-icon-usage"]).toBeGreaterThanOrEqual(1);
+ expect(res.body.iconClassToCountMap).not.toHaveProperty("bx");
+ });
+ });
+
+ describe("render markdown", () => {
+ it("renders markdown content to HTML", async () => {
+ const res = await api.post<{ htmlContent: string }>("/api/other/render-markdown", {
+ body: { markdownContent: "# Heading\n\nSome **bold** text." }
+ });
+ expect(res.status).toBe(200);
+ expect(typeof res.body.htmlContent).toBe("string");
+ expect(res.body.htmlContent).toContain("Heading");
+ expect(res.body.htmlContent).toContain("bold");
+ });
+
+ it("400s when markdownContent is missing", async () => {
+ const res = await api.post("/api/other/render-markdown", { body: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("400s when markdownContent is not a string", async () => {
+ const res = await api.post("/api/other/render-markdown", {
+ body: { markdownContent: 123 }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("to markdown", () => {
+ it("converts HTML content to markdown", async () => {
+ const res = await api.post<{ markdownContent: string }>("/api/other/to-markdown", {
+ body: { htmlContent: "<h1>Heading</h1><p>Some <strong>bold</strong> text.</p>" }
+ });
+ expect(res.status).toBe(200);
+ expect(typeof res.body.markdownContent).toBe("string");
+ expect(res.body.markdownContent).toContain("Heading");
+ expect(res.body.markdownContent).toContain("bold");
+ });
+
+ it("400s when htmlContent is missing", async () => {
+ const res = await api.post("/api/other/to-markdown", { body: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("400s when htmlContent is not a string", async () => {
+ const res = await api.post("/api/other/to-markdown", {
+ body: { htmlContent: 123 }
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/recent_changes.spec.ts b/packages/trilium-core/src/routes/api/recent_changes.spec.ts
new file mode 100644
index 0000000000..685e69cea7
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/recent_changes.spec.ts
@@ -0,0 +1,93 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import type { RecentChangeRow } from "@triliumnext/commons";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core recent-changes route through {@link CoreApiTester}
+ * (no Express), so this spec runs under both the node and standalone (WASM)
+ * suites against the same seeded demo DB.
+ */
+let api: CoreApiTester;
+
+describe("Recent changes API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns recent changes for the root ancestor", async () => {
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body.length).toBeGreaterThan(0);
+
+ const first = res.body[0];
+ expect(typeof first.noteId).toBe("string");
+ expect(typeof first.title).toBe("string");
+ expect(typeof first.utcDate).toBe("string");
+ });
+
+ it("is sorted by utcDate descending", async () => {
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+
+ expect(res.status).toBe(200);
+ for (let i = 1; i < res.body.length; i++) {
+ expect(res.body[i - 1].utcDate >= res.body[i].utcDate).toBe(true);
+ }
+ });
+
+ it("includes a freshly created note in the root recent changes", async () => {
+ const { noteId } = await createTextNote(api, { title: "Recent change probe" });
+
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+
+ expect(res.status).toBe(200);
+ const entry = res.body.find((change) => change.noteId === noteId);
+ expect(entry).toBeTruthy();
+ });
+
+ it("filters recent changes by a specific ancestor subtree", async () => {
+ const parent = await createTextNote(api, { title: "Ancestor parent" });
+ const child = await createTextNote(api, {
+ parentNoteId: parent.noteId,
+ title: "Descendant note"
+ });
+
+ const res = await api.get<RecentChangeRow[]>(
+ `/api/recent-changes/${parent.noteId}`
+ );
+
+ expect(res.status).toBe(200);
+ const noteIds = res.body.map((change) => change.noteId);
+ expect(noteIds).toContain(child.noteId);
+ });
+
+ it("reports canBeUndeleted for a soft-deleted note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Soon deleted" });
+
+ const del = await api.delete(`/api/notes/${noteId}`, {
+ query: { taskId: "recent-changes-delete", last: "true" }
+ });
+ expect(del.status).toBe(204);
+
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/root");
+ expect(res.status).toBe(200);
+
+ const deletedEntries = res.body.filter(
+ (change) => change.noteId === noteId && change.current_isDeleted
+ );
+ expect(deletedEntries.length).toBeGreaterThan(0);
+ expect(deletedEntries.every((change) => change.canBeUndeleted === true)).toBe(true);
+ });
+
+ it("returns an empty list for a non-existent ancestor", async () => {
+ const res = await api.get<RecentChangeRow[]>("/api/recent-changes/missingAncestor123");
+
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body.length).toBe(0);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/recent_notes.spec.ts b/packages/trilium-core/src/routes/api/recent_notes.spec.ts
new file mode 100644
index 0000000000..73e4b6ea84
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/recent_notes.spec.ts
@@ -0,0 +1,64 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { getSql } from "../../services/sql/index";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core recent-notes route through {@link CoreApiTester} (no
+ * Express), so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+function getRecentNote(noteId: string): { notePath: string; utcDateCreated: string } | null {
+ return getSql().getRowOrNull<{ notePath: string; utcDateCreated: string }>(
+ "SELECT notePath, utcDateCreated FROM recent_notes WHERE noteId = ?",
+ [ noteId ]
+ );
+}
+
+describe("Recent notes API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("records a recent note and persists it to the DB", async () => {
+ const { noteId } = await createTextNote(api, { title: "Recently visited" });
+ const notePath = `root/${noteId}`;
+
+ const res = await api.post("/api/recent-notes", {
+ body: { noteId, notePath }
+ });
+ expect(res.status).toBe(204);
+ expect(res.body).toBeUndefined();
+
+ const row = getRecentNote(noteId);
+ expect(row).not.toBeNull();
+ expect(row?.notePath).toBe(notePath);
+ expect(row?.utcDateCreated).toBeTruthy();
+ });
+
+ it("upserts on the noteId primary key when the same note is revisited", async () => {
+ const { noteId } = await createTextNote(api, { title: "Revisited" });
+
+ const first = await api.post("/api/recent-notes", {
+ body: { noteId, notePath: `root/${noteId}` }
+ });
+ expect(first.status).toBe(204);
+
+ const updatedPath = `root/otherParent/${noteId}`;
+ const second = await api.post("/api/recent-notes", {
+ body: { noteId, notePath: updatedPath }
+ });
+ expect(second.status).toBe(204);
+
+ const row = getRecentNote(noteId);
+ expect(row?.notePath).toBe(updatedPath);
+
+ const count = getSql().getValue<number>(
+ "SELECT COUNT(*) FROM recent_notes WHERE noteId = ?",
+ [ noteId ]
+ );
+ expect(count).toBe(1);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/relation-map.spec.ts b/packages/trilium-core/src/routes/api/relation-map.spec.ts
new file mode 100644
index 0000000000..c0a00f1770
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/relation-map.spec.ts
@@ -0,0 +1,111 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core relation-map route through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface RelationMapResponse {
+ noteTitles: Record<string, string>;
+ relations: Array<{
+ attributeId: string;
+ sourceNoteId: string;
+ targetNoteId: string;
+ name: string;
+ }>;
+ inverseRelations: Record<string, string>;
+}
+
+describe("Relation Map API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns the default empty response when no note ids are supplied", async () => {
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: { relationMapNoteId: "root", noteIds: [] }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.noteTitles).toEqual({});
+ expect(res.body.relations).toEqual([]);
+ expect(res.body.inverseRelations.internalLink).toBe("internalLink");
+ });
+
+ it("returns the default empty response when note ids are omitted", async () => {
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: { relationMapNoteId: "root" }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.relations).toEqual([]);
+ expect(res.body.inverseRelations.internalLink).toBe("internalLink");
+ });
+
+ it("maps titles and relations between the supplied notes", async () => {
+ const map = await createTextNote(api, { title: "Map" });
+ const source = await createTextNote(api, { title: "Source" });
+ const target = await createTextNote(api, { title: "Target" });
+
+ const rel = await api.put(
+ `/api/notes/${source.noteId}/relations/links/to/${target.noteId}`
+ );
+ expect(rel.status).toBe(200);
+
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: {
+ relationMapNoteId: map.noteId,
+ noteIds: [ source.noteId, target.noteId ]
+ }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.noteTitles[source.noteId]).toBe("Source");
+ expect(res.body.noteTitles[target.noteId]).toBe("Target");
+
+ const mapped = res.body.relations.find(
+ (relation) => relation.sourceNoteId === source.noteId
+ );
+ expect(mapped).toMatchObject({
+ sourceNoteId: source.noteId,
+ targetNoteId: target.noteId,
+ name: "links"
+ });
+ expect(mapped?.attributeId).toBeTruthy();
+ });
+
+ it("omits relations whose target is not part of the requested note ids", async () => {
+ const map = await createTextNote(api, { title: "Map" });
+ const source = await createTextNote(api, { title: "Source" });
+ const target = await createTextNote(api, { title: "Target" });
+
+ const rel = await api.put(
+ `/api/notes/${source.noteId}/relations/links/to/${target.noteId}`
+ );
+ expect(rel.status).toBe(200);
+
+ const res = await api.post<RelationMapResponse>("/api/relation-map", {
+ body: {
+ relationMapNoteId: map.noteId,
+ noteIds: [ source.noteId ]
+ }
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.relations).toEqual([]);
+ });
+
+ it("404s when the relation map note does not exist", async () => {
+ const { noteId } = await createTextNote(api, { title: "Source" });
+
+ const res = await api.post("/api/relation-map", {
+ body: { relationMapNoteId: "missingNote123", noteIds: [ noteId ] }
+ });
+
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/revisions.spec.ts b/packages/trilium-core/src/routes/api/revisions.spec.ts
new file mode 100644
index 0000000000..48c3d47365
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/revisions.spec.ts
@@ -0,0 +1,222 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { getSql } from "../../services/sql/index";
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core revision routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface ForceSaveResponse {
+ revisionId: string;
+}
+
+/**
+ * Creates a fresh note and forces a manual revision on it, returning the
+ * note id and the new revision id so tests can read/restore/erase it.
+ */
+async function createNoteWithRevision(
+ options?: { title?: string; content?: string }
+): Promise<{ noteId: string; revisionId: string }> {
+ const { noteId } = await createTextNote(api, options);
+ const res = await api.post<ForceSaveResponse>(`/api/notes/${noteId}/revision`, {
+ body: { description: "manual snapshot" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.revisionId).toBeTruthy();
+
+ return { noteId, revisionId: res.body.revisionId };
+}
+
+function revisionExists(revisionId: string): boolean {
+ const row = getSql().getRowOrNull<{ revisionId: string }>(
+ "SELECT revisionId FROM revisions WHERE revisionId = ?",
+ [ revisionId ]
+ );
+ return row !== null;
+}
+
+describe("Revisions API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("force-saving a revision", () => {
+ it("creates a revision for an existing note", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has revisions" });
+
+ const res = await api.post<ForceSaveResponse>(`/api/notes/${noteId}/revision`, {
+ body: { description: "first snapshot" }
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.revisionId).toBeTruthy();
+ });
+
+ it("404s when the note does not exist", async () => {
+ const res = await api.post("/api/notes/missingNote123/revision", {
+ body: { description: "nope" }
+ });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("reading", () => {
+ it("lists revisions for a note", async () => {
+ const { noteId, revisionId } = await createNoteWithRevision({ title: "Listed" });
+
+ const res = await api.get<Array<{ revisionId: string; noteId: string }>>(
+ `/api/notes/${noteId}/revisions`
+ );
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body.some((rev) => rev.revisionId === revisionId)).toBe(true);
+ expect(res.body[0].noteId).toBe(noteId);
+ });
+
+ it("returns an empty list for a note without revisions", async () => {
+ const { noteId } = await createTextNote(api, { title: "No revisions" });
+
+ const res = await api.get<unknown[]>(`/api/notes/${noteId}/revisions`);
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([]);
+ });
+
+ it("returns a single revision by id", async () => {
+ const { noteId, revisionId } = await createNoteWithRevision({
+ title: "Single",
+ content: "<p>snapshot body</p>"
+ });
+
+ const res = await api.get<{ revisionId: string; noteId: string; type: string }>(
+ `/api/revisions/${revisionId}`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.revisionId).toBe(revisionId);
+ expect(res.body.noteId).toBe(noteId);
+ expect(res.body.type).toBeTruthy();
+ });
+
+ it("returns the revision blob", async () => {
+ const { revisionId } = await createNoteWithRevision({ content: "<p>blob body</p>" });
+
+ const res = await api.get<{ blobId: string; content: string }>(
+ `/api/revisions/${revisionId}/blob`
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.blobId).toBeTruthy();
+ expect(typeof res.body.content).toBe("string");
+ expect(res.body.content).toContain("blob body");
+ });
+
+ it("404s for a missing revision", async () => {
+ const res = await api.get("/api/revisions/missingRevision123");
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("updating the description", () => {
+ it("updates an existing revision's description", async () => {
+ const { revisionId } = await createNoteWithRevision({ title: "Describe me" });
+
+ const res = await api.patch(`/api/revisions/${revisionId}`, {
+ body: { description: "edited description" }
+ });
+ expect(res.status).toBe(204);
+
+ const row = getSql().getRowOrNull<{ description: string }>(
+ "SELECT description FROM revisions WHERE revisionId = ?",
+ [ revisionId ]
+ );
+ expect(row?.description).toBe("edited description");
+ });
+
+ it("404s when updating a missing revision", async () => {
+ const res = await api.patch("/api/revisions/missingRevision123", {
+ body: { description: "whatever" }
+ });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("restoring", () => {
+ it("restores a revision and creates a new pre-restore snapshot", async () => {
+ const { noteId, revisionId } = await createNoteWithRevision({
+ title: "Original",
+ content: "<p>original body</p>"
+ });
+
+ // Mutate the note away from the snapshotted state.
+ const update = await api.put(`/api/notes/${noteId}/data`, {
+ body: { content: "<p>changed body</p>" }
+ });
+ expect(update.status).toBe(204);
+
+ const restore = await api.post(`/api/revisions/${revisionId}/restore`);
+ expect(restore.status).toBe(204);
+
+ const blob = await api.get<{ content: string }>(`/api/notes/${noteId}/blob`);
+ expect(blob.body.content).toContain("original body");
+
+ // Restoring snapshots the pre-restore state, so there is now more than one revision.
+ const revisions = await api.get<unknown[]>(`/api/notes/${noteId}/revisions`);
+ expect(revisions.body.length).toBeGreaterThan(1);
+ });
+
+ it("no-ops for a missing revision", async () => {
+ const res = await api.post("/api/revisions/missingRevision123/restore");
+ expect(res.status).toBe(204);
+ });
+ });
+
+ describe("erasing", () => {
+ it("erases a single revision", async () => {
+ const { revisionId } = await createNoteWithRevision({ title: "Erase one" });
+ expect(revisionExists(revisionId)).toBe(true);
+
+ const res = await api.delete(`/api/revisions/${revisionId}`);
+ expect(res.status).toBe(204);
+ expect(revisionExists(revisionId)).toBe(false);
+ });
+
+ it("erases all revisions of a note", async () => {
+ const { noteId, revisionId } = await createNoteWithRevision({ title: "Erase all" });
+ expect(revisionExists(revisionId)).toBe(true);
+
+ const res = await api.delete(`/api/notes/${noteId}/revisions`);
+ expect(res.status).toBe(204);
+ expect(revisionExists(revisionId)).toBe(false);
+
+ const list = await api.get<unknown[]>(`/api/notes/${noteId}/revisions`);
+ expect(list.body).toEqual([]);
+ });
+ });
+
+ describe("edited notes on a date", () => {
+ it("returns notes edited on the given date", async () => {
+ const { noteId } = await createTextNote(api, { title: "Edited today" });
+
+ const row = getSql().getRowOrNull<{ dateModified: string }>(
+ "SELECT dateModified FROM notes WHERE noteId = ?",
+ [ noteId ]
+ );
+ const date = (row?.dateModified ?? "").substring(0, 10);
+ expect(date).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+
+ const res = await api.get<Array<{ noteId: string; notePath: string[] | null }>>(
+ `/api/edited-notes/${date}`
+ );
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ expect(res.body.some((note) => note.noteId === noteId)).toBe(true);
+ });
+
+ it("returns an empty list for a date with no edits", async () => {
+ const res = await api.get<unknown[]>("/api/edited-notes/1970-01-01");
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([]);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/similar_notes.spec.ts b/packages/trilium-core/src/routes/api/similar_notes.spec.ts
new file mode 100644
index 0000000000..bf3c7ea6b9
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/similar_notes.spec.ts
@@ -0,0 +1,56 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core similar-notes route through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface SimilarNote {
+ score: number;
+ notePath: string[];
+ noteId: string;
+}
+
+describe("Similar Notes API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ it("returns a list of similar notes for an existing note", async () => {
+ const res = await api.get<SimilarNote[]>("/api/similar-notes/root");
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ for (const similar of res.body) {
+ expect(typeof similar.noteId).toBe("string");
+ expect(typeof similar.score).toBe("number");
+ expect(Array.isArray(similar.notePath)).toBe(true);
+ }
+ });
+
+ it("finds a freshly created note that shares content with another", async () => {
+ const shared = "alphabet bicycle continuous determination elephant fountain";
+ await createTextNote(api, {
+ title: "Similar source",
+ content: `<p>${shared}</p>`
+ });
+ const { noteId } = await createTextNote(api, {
+ title: "Similar source",
+ content: `<p>${shared}</p>`
+ });
+
+ const res = await api.get<SimilarNote[]>(`/api/similar-notes/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+ // The note never lists itself as similar.
+ expect(res.body.every((similar) => similar.noteId !== noteId)).toBe(true);
+ });
+
+ it("404s for a missing note", async () => {
+ const res = await api.get("/api/similar-notes/missingNote123");
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/special_notes.spec.ts b/packages/trilium-core/src/routes/api/special_notes.spec.ts
new file mode 100644
index 0000000000..e2bf92c76c
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/special_notes.spec.ts
@@ -0,0 +1,134 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core special-notes routes through {@link CoreApiTester}
+ * (no Express), so this spec runs under both the node and standalone (WASM)
+ * suites. Date-note GETs lazily create the calendar hierarchy, and the SQL
+ * console / search-note POSTs create disposable notes — all safe operations.
+ */
+let api: CoreApiTester;
+
+interface NotePojo {
+ noteId: string;
+ type: string;
+ title: string;
+}
+
+interface CloneResponse {
+ success: boolean;
+ branchId?: string;
+}
+
+describe("Special notes API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("date notes", () => {
+ it("returns the inbox note for a date", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/inbox/2025-01-01");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ expect(res.body.type).toBeTruthy();
+ });
+
+ it("returns (and lazily creates) the day note", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/days/2025-01-01");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ expect(res.body.type).toBeTruthy();
+ });
+
+ it("returns the first day of the week for a date", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/week-first-day/2025-01-01");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ });
+
+ it("returns the month note", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/months/2025-01");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ });
+
+ it("returns the quarter note", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/quarters/2025-Q1");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ });
+
+ it("returns the year note", async () => {
+ const res = await api.get<NotePojo>("/api/special-notes/years/2025");
+ expect(res.status).toBe(200);
+ expect(res.body.noteId).toBeTruthy();
+ });
+
+ it("returns a map of day notes for a month", async () => {
+ await api.get("/api/special-notes/days/2025-01-01");
+
+ const res = await api.get<Record<string, string>>(
+ "/api/special-notes/notes-for-month/2025-01"
+ );
+ expect(res.status).toBe(200);
+ expect(typeof res.body).toBe("object");
+ expect(res.body["2025-01-01"]).toBeTruthy();
+ });
+
+ it("404s for the day note when the calendar root does not exist", async () => {
+ const res = await api.get("/api/special-notes/days/2025-01-01", {
+ query: { calendarRootId: "missingCalendarRoot123" }
+ });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe("SQL console", () => {
+ it("creates a SQL console note and saves it (round-trip)", async () => {
+ const created = await api.post<NotePojo>("/api/special-notes/sql-console");
+ expect(created.status).toBe(200);
+ expect(created.body.noteId).toBeTruthy();
+ expect(created.body.type).toBe("code");
+
+ const saved = await api.post<CloneResponse>("/api/special-notes/save-sql-console", {
+ body: { sqlConsoleNoteId: created.body.noteId }
+ });
+ expect(saved.status).toBe(200);
+ expect(saved.body.success).toBe(true);
+ expect(saved.body.branchId).toBeTruthy();
+ });
+
+ it("500s when saving a non-existent SQL console note", async () => {
+ const res = await api.post("/api/special-notes/save-sql-console", {
+ body: { sqlConsoleNoteId: "missingSqlConsole123" }
+ });
+ expect(res.status).toBe(500);
+ });
+ });
+
+ describe("search notes", () => {
+ it("creates a search note and saves it (round-trip)", async () => {
+ const created = await api.post<NotePojo>("/api/special-notes/search-note", {
+ body: { searchString: "#someLabel" }
+ });
+ expect(created.status).toBe(200);
+ expect(created.body.noteId).toBeTruthy();
+ expect(created.body.type).toBe("search");
+
+ const saved = await api.post<CloneResponse>("/api/special-notes/save-search-note", {
+ body: { searchNoteId: created.body.noteId }
+ });
+ expect(saved.status).toBe(200);
+ expect(saved.body.success).toBe(true);
+ expect(saved.body.branchId).toBeTruthy();
+ });
+
+ it("500s when saving a non-existent search note", async () => {
+ const res = await api.post("/api/special-notes/save-search-note", {
+ body: { searchNoteId: "missingSearchNote123" }
+ });
+ expect(res.status).toBe(500);
+ });
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/sql.spec.ts b/packages/trilium-core/src/routes/api/sql.spec.ts
new file mode 100644
index 0000000000..f1df2788b3
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/sql.spec.ts
@@ -0,0 +1,89 @@
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { createTextNote } from "../../test/api_fixtures";
+import { CoreApiTester } from "../../test/api_tester";
+
+/**
+ * Drives the shared core SQL routes through {@link CoreApiTester} (no Express),
+ * so this spec runs under both the node and standalone (WASM) suites.
+ */
+let api: CoreApiTester;
+
+interface SchemaTable {
+ name: string;
+ columns: { name: string; type: string }[];
+}
+
+interface ExecuteResult {
+ success: boolean;
+ results?: unknown[];
+ error?: string;
+}
+
+describe("SQL API (core)", () => {
+ beforeAll(() => {
+ api = CoreApiTester.build();
+ });
+
+ describe("schema", () => {
+ it("returns the database table schema", async () => {
+ const res = await api.get<SchemaTable[]>("/api/sql/schema");
+ expect(res.status).toBe(200);
+ expect(Array.isArray(res.body)).toBe(true);
+
+ const notesTable = res.body.find((table) => table.name === "notes");
+ expect(notesTable).toBeTruthy();
+ expect(Array.isArray(notesTable?.columns)).toBe(true);
+
+ const noteIdColumn = notesTable?.columns.find((col) => col.name === "noteId");
+ expect(noteIdColumn).toBeTruthy();
+ });
+ });
+
+ describe("execute", () => {
+ it("runs a SELECT query from a note body and returns the rows", async () => {
+ const { noteId } = await createTextNote(api, {
+ title: "SQL console",
+ content: "SELECT noteId FROM notes WHERE noteId = 'root'"
+ });
+
+ const res = await api.post<ExecuteResult>(`/api/sql/execute/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+
+ const results = res.body.results;
+ expect(Array.isArray(results)).toBe(true);
+ const firstQueryRows = results?.[0] as { noteId: string }[];
+ expect(firstQueryRows[0].noteId).toBe("root");
+ });
+
+ it("runs multiple statements separated by the query delimiter", async () => {
+ const { noteId } = await createTextNote(api, {
+ title: "SQL console multi",
+ content: "SELECT 1 AS one\n---\nSELECT 2 AS two"
+ });
+
+ const res = await api.post<ExecuteResult>(`/api/sql/execute/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(true);
+ expect(res.body.results).toHaveLength(2);
+ });
+
+ it("reports success=false with an error message for an invalid query", async () => {
+ const { noteId } = await createTextNote(api, {
+ title: "SQL console broken",
+ content: "SELECT * FROM this_table_does_not_exist"
+ });
+
+ const res = await api.post<ExecuteResult>(`/api/sql/execute/${noteId}`);
+ expect(res.status).toBe(200);
+ expect(res.body.success).toBe(false);
+ expect(typeof res.body.error).toBe("string");
+ });
+
+ it("404s when the note does not exist", async () => {
+ const res = await api.post("/api/sql/execute/missingNote123");
+ expect(res.status).toBe(404);
+ });
+ });
+});