Skip to content

Build your personal knowledge base with Trilium Notes

22.7 KB
Raw Blame
import { beforeAll, describe, expect, it } from "vitest";

import becca from "../../becca/becca";
import { load } from "../../becca/becca_loader";
import { getContext } from "../../services/context";
import { getSql } from "../../services/sql/index";
import { registerVirtualNoteProvider, unregisterVirtualNoteProvider } from "../../services/virtual_notes";
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 ]
    );
}

function setExpanded(branchIds: string[], isExpanded: number) {
    for (const branchId of branchIds) {
        getSql().execute(
            "UPDATE branches SET isExpanded = ? WHERE branchId = ?",
            [ isExpanded, branchId ]
        );
        becca.getBranchOrThrow(branchId).isExpanded = !!isExpanded;
    }
}

/**
 * Builds `root → { child → grandchild → leaf, left → shared, right → shared }`, where
 * `shared` is one note cloned under two parents and has a child of its own.
 */
async function createSubtreeWithClone() {
    const create = (title: string, parentNoteId?: string) =>
        createTextNote(api, { parentNoteId, title });
    const root = await create("Subtree root");
    const child = await create("Subtree child", root.noteId);
    const grandchild = await create("Subtree grandchild", child.noteId);
    const leaf = await create("Subtree leaf", grandchild.noteId);
    const left = await create("Subtree left", root.noteId);
    const right = await create("Subtree right", root.noteId);
    const shared = await create("Subtree shared", left.noteId);
    const sharedChild = await create("Subtree shared child", shared.noteId);

    const clone = await api.put<{ success: boolean; branchId: string }>(
        `/api/notes/${shared.noteId}/clone-to-note/${right.noteId}`,
        { body: {} }
    );
    expect(clone.body.success).toBe(true);

    const collapsed = [
        root.branchId, grandchild.branchId, leaf.branchId, left.branchId, right.branchId,
        shared.branchId, clone.body.branchId, sharedChild.branchId
    ];
    return {
        root: root.branchId,
        expandedChild: child.branchId,
        collapsed,
        all: [ ...collapsed, child.branchId ]
    };
}

function noteExists(noteId: string): boolean {
    return getSql().getRowOrNull("SELECT noteId FROM notes WHERE noteId = ?", [ noteId ]) !== null;
}

/**
 * Counts the entity changes flagged `isErased` for the given ids. The client reloads itself as soon
 * as one of these reaches it (`froca_updater.processNoteChange`), so a batch that raises the count
 * before its last request kills the requests that were still to come.
 */
function erasedEntityChangeCount(entityIds: string[]): number {
    const placeholders = entityIds.map(() => "?").join(", ");
    return getSql().getValue<number>(
        `SELECT COUNT(1) FROM entity_changes WHERE isErased = 1 AND entityId IN (${placeholders})`,
        entityIds
    ) ?? 0;
}

describe("Branches API (core)", () => {
    beforeAll(() => {
        api = CoreApiTester.build();
    });

    describe("moving", () => {
        it("moves several branches into a childless note, in order, and expands it", async () => {
            const source = await createTextNote(api, { title: "Move source" });
            const target = await createTextNote(api, { parentNoteId: source.noteId, title: "Move target" });
            const children = [
                await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 1" }),
                await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 2" }),
                await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 3" })
            ];

            const res = await api.put<{ success: boolean }>(`/api/branches/move-to/${target.branchId}`, {
                body: { branchIds: children.map((child) => child.branchId) }
            });

            expect(res.status).toBe(200);
            expect(res.body.success).toBe(true);
            // Each original branch is replaced by a clone under the new parent.
            for (const child of children) {
                expect(getBranchRow(child.branchId)?.isDeleted).toBe(1);
            }
            expect(getSql().getColumn(
                "SELECT noteId FROM branches WHERE parentNoteId = ? AND isDeleted = 0 ORDER BY notePosition",
                [ target.noteId ]
            )).toEqual(children.map((child) => child.noteId));
            expect(getBranchRow(target.branchId)?.isExpanded).toBe(1);
        });

        it("stops at the first move that fails validation", async () => {
            const movable = await createTextNote(api, { title: "Movable" });
            const ancestor = await createTextNote(api, { title: "Ancestor of target" });
            const nestedTarget = await createTextNote(api, { parentNoteId: ancestor.noteId, title: "Nested target" });
            const notReached = await createTextNote(api, { title: "Not reached" });

            // Moving `ancestor` under its own descendant would create a cycle.
            const res = await api.put<{ success: boolean; message: string }>(
                `/api/branches/move-to/${nestedTarget.branchId}`,
                { body: { branchIds: [ movable.branchId, ancestor.branchId, notReached.branchId ] } }
            );

            expect(res.status).toBe(200);
            expect(res.body.success).toBe(false);
            expect(res.body.message).toBeTruthy();
            expect(getBranchRow(movable.branchId)?.isDeleted).toBe(1);
            expect(getBranchRow(ancestor.branchId)?.isDeleted).toBe(0);
            expect(getBranchRow(notReached.branchId)?.isDeleted).toBe(0);
        });

        it("400s without moving anything when a branch or the target does not exist", async () => {
            const parent = await createTextNote(api, { title: "Has a valid parent branch" });
            const child = await createTextNote(api, { title: "Not moved" });

            const missingBranch = await api.put(`/api/branches/move-to/${parent.branchId}`, {
                body: { branchIds: [ child.branchId, "missingBranch123" ] }
            });
            const missingTarget = await api.put("/api/branches/move-to/missingBranch123", {
                body: { branchIds: [ child.branchId ] }
            });
            const notAnArray = await api.put(`/api/branches/move-to/${parent.branchId}`, {
                body: { branchIds: child.branchId }
            });

            expect([ missingBranch.status, missingTarget.status, notAnArray.status ]).toEqual([ 400, 400, 400 ]);
            expect(getBranchRow(child.branchId)?.isDeleted).toBe(0);
        });

        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);
        });

        it("moves a branch before a sibling under a different parent (clone path)", async () => {
            const parentA = await createTextNote(api, { title: "Cross before A" });
            const parentB = await createTextNote(api, { title: "Cross before B" });
            const moving = await createTextNote(api, { parentNoteId: parentA.noteId, title: "Crosser" });
            const target = await createTextNote(api, { parentNoteId: parentB.noteId, title: "Before target" });

            const res = await api.put<{ success: boolean }>(
                `/api/branches/${moving.branchId}/move-before/${target.branchId}`
            );
            expect(res.status).toBe(200);
            expect(res.body.success).toBe(true);
            // original branch under parentA is replaced by a clone under parentB
            expect(getBranchRow(moving.branchId)?.isDeleted).toBe(1);
        });

        it("moves a branch after a sibling under a different parent (clone path)", async () => {
            const parentA = await createTextNote(api, { title: "Cross after A" });
            const parentB = await createTextNote(api, { title: "Cross after B" });
            const moving = await createTextNote(api, { parentNoteId: parentA.noteId, title: "Crosser after" });
            const first = await createTextNote(api, { parentNoteId: parentB.noteId, title: "After first" });
            // a second sibling after the target so the position-shift loop body runs
            await createTextNote(api, { parentNoteId: parentB.noteId, title: "After second" });

            const res = await api.put<{ success: boolean }>(
                `/api/branches/${moving.branchId}/move-after/${first.branchId}`
            );
            expect(res.status).toBe(200);
            expect(res.body.success).toBe(true);
            expect(getBranchRow(moving.branchId)?.isDeleted).toBe(1);
        });

        it("returns a 200 validation failure when the move would create a cycle (before)", async () => {
            const parent = await createTextNote(api, { title: "Cycle before parent" });
            const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Cycle before child" });

            // moving the parent's branch before its own descendant would create a cycle
            const res = await api.put<{ success: boolean; message: string }>(
                `/api/branches/${parent.branchId}/move-before/${child.branchId}`
            );
            expect(res.status).toBe(200);
            expect(res.body.success).toBe(false);
        });

        it("returns a 200 validation failure when the move would create a cycle (after)", async () => {
            const parent = await createTextNote(api, { title: "Cycle after parent" });
            const child = await createTextNote(api, { parentNoteId: parent.noteId, title: "Cycle after child" });

            const res = await api.put<{ success: boolean; message: string }>(
                `/api/branches/${parent.branchId}/move-after/${child.branchId}`
            );
            expect(res.status).toBe(200);
            expect(res.body.success).toBe(false);
        });
    });

    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 every descendant of a subtree, once per branch", async () => {
            const tree = await createSubtreeWithClone();
            setExpanded(tree.collapsed, 0);
            setExpanded([ tree.expandedChild ], 1);

            const res = await api.put<{ branchIds: string[] }>(
                `/api/branches/${tree.root}/expanded-subtree/1`
            );
            expect(res.status).toBe(200);
            expect(res.body.branchIds).toHaveLength(tree.collapsed.length);
            expect(new Set(res.body.branchIds)).toEqual(new Set(tree.collapsed));
            for (const branchId of tree.all) {
                expect(getBranchRow(branchId)?.isExpanded).toBe(1);
            }
        });

        it("collapses every descendant of a subtree, also below a collapsed note", async () => {
            const tree = await createSubtreeWithClone();
            setExpanded(tree.all, 1);
            setExpanded([ tree.expandedChild ], 0);

            const res = await api.put<{ branchIds: string[] }>(
                `/api/branches/${tree.root}/expanded-subtree/0`
            );
            expect(res.status).toBe(200);
            expect(res.body.branchIds).toHaveLength(tree.all.length - 1);
            expect(res.body.branchIds).not.toContain(tree.expandedChild);
            for (const branchId of tree.all) {
                expect(getBranchRow(branchId)?.isExpanded).toBe(0);
            }
        });

        it("reaches the virtual subtree below a note, and a subtree that is virtual itself", async () => {
            const anchor = await createTextNote(api, { title: "Virtual anchor" });
            const persistedChild = await createTextNote(api, { parentNoteId: anchor.noteId, title: "Persisted child" });
            registerVirtualNoteProvider({
                namespace: "_vexp",
                parentNoteId: anchor.noteId,
                getSubtree: () => [{
                    id: "_vexp",
                    title: "Virtual root",
                    type: "book",
                    children: [{
                        id: "_vexpBook",
                        title: "Virtual book",
                        type: "book",
                        children: [{ id: "_vexpPage", title: "Virtual page", type: "text" }]
                    }]
                }]
            });

            try {
                getContext().init(() => load());
                const virtualBranchIds = [ `${anchor.noteId}__vexp`, "_vexp__vexpBook", "_vexpBook__vexpPage" ];
                const isExpanded = (branchId: string) => becca.getBranch(branchId)?.isExpanded;

                const expand = await api.put<{ branchIds: string[] }>(`/api/branches/${anchor.branchId}/expanded-subtree/1`);
                expect(new Set(expand.body.branchIds)).toEqual(new Set([ anchor.branchId, persistedChild.branchId, ...virtualBranchIds ]));
                expect(getBranchRow(persistedChild.branchId)?.isExpanded).toBe(1);
                expect(virtualBranchIds.map(isExpanded)).toEqual([ true, true, true ]);

                const collapse = await api.put<{ branchIds: string[] }>(`/api/branches/_vexp__vexpBook/expanded-subtree/0`);
                expect(new Set(collapse.body.branchIds)).toEqual(new Set([ "_vexp__vexpBook", "_vexpBook__vexpPage" ]));
                expect(virtualBranchIds.map(isExpanded)).toEqual([ true, false, false ]);
                expect(getBranchRow(persistedChild.branchId)?.isExpanded).toBe(1);
            } finally {
                unregisterVirtualNoteProvider("_vexp");
                getContext().init(() => load());
            }
        });

        it("expands a note with more children than a call can take as arguments", async () => {
            const anchor = await createTextNote(api, { title: "Crowded anchor" });
            const childCount = 200_000;
            registerVirtualNoteProvider({
                namespace: "_vbig",
                parentNoteId: anchor.noteId,
                getSubtree: () => [{
                    id: "_vbig",
                    title: "Crowded note",
                    type: "book",
                    children: Array.from({ length: childCount }, (_, index) => ({
                        id: `_vbig${index}`, title: `Child ${index}`, type: "text" as const
                    }))
                }]
            });

            try {
                getContext().init(() => load());

                const res = await api.put<{ branchIds: string[] }>(`/api/branches/${anchor.noteId}__vbig/expanded-subtree/1`);
                expect(res.status).toBe(200);
                expect(res.body.branchIds).toHaveLength(childCount + 1);
            } finally {
                unregisterVirtualNoteProvider("_vbig");
                getContext().init(() => load());
            }
        }, 60_000);
    });

    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);
        });

        it("erases the note immediately when eraseNotes is set", async () => {
            const { noteId, branchId } = await createTextNote(api, { title: "To erase" });

            const res = await api.delete<{ noteDeleted: boolean }>(`/api/branches/${branchId}`, {
                query: { taskId: "test-branch-erase", last: "true", eraseNotes: "true" }
            });
            expect(res.status).toBe(200);
            expect(res.body.noteDeleted).toBe(true);

            // erasing removes the note row entirely
            const noteRow = getSql().getRowOrNull("SELECT noteId FROM notes WHERE noteId = ?", [ noteId ]);
            expect(noteRow).toBeNull();
        });

        it("holds a multi-branch erase back until the last request of the task group", async () => {
            const first = await createTextNote(api, { title: "Batch erase 1" });
            const second = await createTextNote(api, { title: "Batch erase 2" });
            const taskId = "test-branch-erase-batch";

            const firstRes = await api.delete(`/api/branches/${first.branchId}`, {
                query: { taskId, last: "false", eraseNotes: "true" }
            });
            expect(firstRes.status).toBe(200);

            // Both notes are soft-deleted at this point, but nothing is erased: the client is still
            // sending the rest of the batch, and an erase here would reload it out from under them.
            expect(noteExists(first.noteId)).toBe(true);
            expect(erasedEntityChangeCount([ first.noteId, second.noteId ])).toBe(0);
            expect(getBranchRow(first.branchId)?.isDeleted).toBe(1);

            const secondRes = await api.delete(`/api/branches/${second.branchId}`, {
                query: { taskId, last: "true", eraseNotes: "true" }
            });
            expect(secondRes.status).toBe(200);

            // The last request erases everything the group deleted, in one go.
            expect(noteExists(first.noteId)).toBe(false);
            expect(noteExists(second.noteId)).toBe(false);
            expect(erasedEntityChangeCount([ first.noteId, second.noteId ])).toBe(2);
        });
    });
});