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(core): improve coverage for becca & entities
Elian Doran076fefd48cd0
diff --git a/packages/trilium-core/src/becca/becca-interface.spec.ts b/packages/trilium-core/src/becca/becca-interface.spec.tsnew file mode 100644index 0000000000..ddb2c1541d--- /dev/null+++ b/packages/trilium-core/src/becca/becca-interface.spec.ts@@ -0,0 +1,237 @@+import { describe, expect, it } from "vitest";++import becca from "./becca.js";+import { getContext } from "../services/context.js";+import noteService from "../services/notes.js";++let counter = 0;++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * saveAttachment) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string, title?: string) {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: title ?? `becca-interface-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ })+ );+}++describe("Becca interface (real DB)", () => {+ describe("findAttributes", () => {+ it("strips a leading '#' from the name before lookup", () => {+ // There is a #label attribute somewhere in the fixture; even if not,+ // the goal is to exercise the '#'/'~' stripping branch. We assert the+ // result is an array and the lookup is equivalent to the unprefixed key.+ const withHash = becca.findAttributes("label", "#archived");+ const withoutHash = becca.findAttributes("label", "archived");+ expect(Array.isArray(withHash)).toBe(true);+ expect(withHash).toEqual(withoutHash);+ });++ it("strips a leading '~' from the name before lookup", () => {+ const withTilde = becca.findAttributes("relation", "~template");+ const withoutTilde = becca.findAttributes("relation", "template");+ expect(Array.isArray(withTilde)).toBe(true);+ expect(withTilde).toEqual(withoutTilde);+ });++ it("returns an empty array when nothing matches", () => {+ expect(becca.findAttributes("label", "definitely-missing-xyz")).toEqual([]);+ });+ });++ describe("getNotes", () => {+ it("skips missing ids when ignoreMissing is true", () => {+ const { note } = createNote("root");+ const result = becca.getNotes([note.noteId, "missing-note-id"], true);+ expect(result.map((n) => n.noteId)).toEqual([note.noteId]);+ });++ it("throws on a missing id when ignoreMissing is false", () => {+ expect(() => becca.getNotes(["missing-note-id"], false)).toThrow();+ });++ it("defaults ignoreMissing to false (throws)", () => {+ expect(() => becca.getNotes(["another-missing-id"])).toThrow();+ });+ });++ describe("getAttributeOrThrow", () => {+ it("throws when the attribute does not exist", () => {+ expect(() => becca.getAttributeOrThrow("missing-attribute-id")).toThrow();+ });++ it("returns the attribute when present", () => {+ const { note } = createNote("root");+ const attr = withContext(() => note.addLabel("becca-interface-label"));+ const fetched = becca.getAttributeOrThrow(attr.attributeId);+ expect(fetched.attributeId).toBe(attr.attributeId);+ });+ });++ describe("getAttachments / getBlob", () => {+ it("fetches existing attachments by id via getManyRows", () => {+ const { note } = createNote("root");+ const attachment = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: `becca-interface-att-${counter}`,+ content: "attachment content"+ })+ );++ const fetched = becca.getAttachments([attachment.attachmentId]);+ expect(fetched.map((a) => a.attachmentId)).toContain(attachment.attachmentId);+ });++ it("getBlob returns null when no blobId is provided", () => {+ expect(becca.getBlob({})).toBeNull();+ });++ it("getBlob returns null when the blobId has no matching row", () => {+ expect(becca.getBlob({ blobId: "missing-blob-id" })).toBeNull();+ });++ it("getBlob returns a blob for a saved attachment's blobId", () => {+ const { note } = createNote("root");+ const attachment = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: `becca-interface-blob-${counter}`,+ content: "blob content"+ })+ );++ expect(attachment.blobId).toBeDefined();+ const blob = becca.getBlob({ blobId: attachment.blobId });+ expect(blob).not.toBeNull();+ expect(blob?.blobId).toBe(attachment.blobId);+ });+ });++ describe("getEntity", () => {+ it("returns null when entityName is empty", () => {+ expect(becca.getEntity("", "someId")).toBeNull();+ });++ it("returns null when entityId is empty", () => {+ expect(becca.getEntity("notes", "")).toBeNull();+ });++ it("resolves a note through the camelCase collection lookup", () => {+ const { note } = createNote("root");+ const entity = becca.getEntity("notes", note.noteId);+ expect(entity).not.toBeNull();+ expect((entity as { noteId?: string })?.noteId).toBe(note.noteId);+ });++ it("returns null for a known collection when the id is absent", () => {+ expect(becca.getEntity("notes", "missing-note-id")).toBeNull();+ });++ it("routes 'revisions' to getRevision", () => {+ // No such revision exists, but the branch is exercised and returns null.+ expect(becca.getEntity("revisions", "missing-revision-id")).toBeNull();+ });++ it("routes 'attachments' to getAttachment", () => {+ const { note } = createNote("root");+ const attachment = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: `becca-interface-entity-att-${counter}`,+ content: "x"+ })+ );++ const entity = becca.getEntity("attachments", attachment.attachmentId);+ expect(entity).not.toBeNull();+ expect((entity as { attachmentId?: string })?.attachmentId).toBe(attachment.attachmentId);+ });++ it("converts snake_case entity names to camelCase collections (etapi_tokens)", () => {+ // The etapiTokens collection exists on becca; a missing id yields null,+ // proving the snake_case -> camelCase conversion resolved a real collection.+ expect(becca.getEntity("etapi_tokens", "missing-token-id")).toBeNull();+ });++ it("throws for an entity name that maps to no collection", () => {+ expect(() => becca.getEntity("totally_unknown_entity", "id")).toThrow();+ });+ });++ describe("dirtyNoteFlatText / getFlatTextIndex", () => {+ it("schedules an incremental update when the index already exists", () => {+ const { note } = createNote("root");+ // Build the index first so flatTextIndex is non-null.+ becca.getFlatTextIndex();++ becca.dirtyNoteFlatText(note.noteId);+ expect(becca.dirtyFlatTextNoteIds.has(note.noteId)).toBe(true);+ });++ it("builds the full index on first access and includes created notes", () => {+ const { note } = createNote("root");+ // Force a full rebuild by invalidating the note set.+ becca.dirtyNoteSetCache();++ const index = becca.getFlatTextIndex();+ expect(index.notes.length).toBeGreaterThan(0);+ expect(index.flatTexts.length).toBe(index.notes.length);+ expect(index.noteIdToIdx.has(note.noteId)).toBe(true);+ });++ it("recomputes only dirtied notes on the incremental path", () => {+ const { note } = createNote("root");+ // Ensure the index exists.+ becca.getFlatTextIndex();++ // Dirty an existing note id (in the index) so the incremental branch runs.+ becca.dirtyNoteFlatText(note.noteId);+ // Also dirty an id that is not present in the index map (idx === undefined branch).+ becca.dirtyFlatTextNoteIds.add("not-in-index-id");++ const idx = becca.getFlatTextIndex().noteIdToIdx.get(note.noteId);+ expect(idx).toBeDefined();+ // After recompute the dirty set is cleared.+ expect(becca.dirtyFlatTextNoteIds.size).toBe(0);+ });++ it("builds the index without heap logging when process.memoryUsage is unavailable", () => {+ // Under the standalone (WASM/browser) runtime process.memoryUsage is undefined,+ // so the heapBefore === null fallback (no heap-delta log) is taken. Simulate that+ // here so the same branch is covered under Node too.+ createNote("root");++ const proc = process as unknown as { memoryUsage?: unknown };+ const original = proc.memoryUsage;+ proc.memoryUsage = undefined;++ try {+ becca.dirtyNoteSetCache(); // force a full rebuild+ const index = becca.getFlatTextIndex();+ expect(index.notes.length).toBeGreaterThan(0);+ } finally {+ proc.memoryUsage = original;+ }+ });+ });+});diff --git a/packages/trilium-core/src/becca/becca_loader.spec.ts b/packages/trilium-core/src/becca/becca_loader.spec.tsnew file mode 100644index 0000000000..f664379c7b--- /dev/null+++ b/packages/trilium-core/src/becca/becca_loader.spec.ts@@ -0,0 +1,208 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { getContext } from "../services/context.js";+import eventService from "../services/events.js";+import noteService from "../services/notes.js";+import { getSql } from "../services/sql/index.js";+import ws from "../services/ws.js";+import becca from "./becca.js";+import beccaLoader, { load, reload } from "./becca_loader.js";+import BNote from "./entities/bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote)+ * require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++function createNote(parentNoteId: string): BNote {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `becca-loader-spec-${counter}`,+ content: "<p>hi</p>",+ type: "text"+ }).note+ );+}++describe("becca_loader", () => {+ afterEach(() => {+ // The shared fixture DB is loaded (becca.loaded === true) after setup;+ // some tests flip this, so always restore it.+ becca.loaded = true;+ vi.restoreAllMocks();+ });++ describe("ENTITY_CHANGE_SYNCED listener", () => {+ it("returns early without touching becca when becca is not loaded", () => {+ becca.loaded = false;++ const before = Object.keys(becca.notes).length;+ eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {+ entityName: "notes",+ entityRow: {+ noteId: "loaderNotLoaded",+ title: "x",+ type: "text",+ mime: "text/html",+ isProtected: false,+ blobId: ""+ }+ });++ // Nothing was created since the listener bailed out.+ expect(becca.getNote("loaderNotLoaded")).toBeNull();+ expect(Object.keys(becca.notes).length).toBe(before);+ });++ it("updates an existing becca entity from the synced row", () => {+ const note = createNote("root");++ eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {+ entityName: "notes",+ entityRow: {+ noteId: note.noteId,+ title: "synced-updated-title",+ type: "code",+ mime: "text/plain",+ isProtected: false,+ blobId: note.blobId+ }+ });++ const updated = becca.getNoteOrThrow(note.noteId);+ expect(updated.title).toBe("synced-updated-title");+ expect(updated.type).toBe("code");+ });++ it("creates a brand-new becca entity from a synced row when not yet present", () => {+ const newNoteId = "loaderBrandNew1";+ expect(becca.getNote(newNoteId)).toBeNull();++ eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {+ entityName: "notes",+ entityRow: {+ noteId: newNoteId,+ title: "brand-new",+ type: "text",+ mime: "text/html",+ isProtected: false,+ blobId: ""+ }+ });++ const created = becca.getNoteOrThrow(newNoteId);+ expect(created).toBeInstanceOf(BNote);+ expect(created.title).toBe("brand-new");+ // init() ran, so the derived collections are initialised.+ expect(Array.isArray(created.children)).toBe(true);+ });++ it("ignores synced rows for entity names outside the handled set", () => {+ // "blobs" is a valid entity but not in the becca_loader handled list,+ // so neither the create/update branch nor post-processing should run.+ expect(() =>+ eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {+ entityName: "blobs",+ entityRow: { blobId: "loaderIgnoredBlob" }+ })+ ).not.toThrow();+ });+ });++ describe("ENTITY_DELETED listener", () => {+ it("branchDeleted returns early for an unknown branch id", () => {+ const branchesBefore = Object.keys(becca.branches).length;++ expect(() =>+ eventService.emit(eventService.ENTITY_DELETED, {+ entityName: "branches",+ entityId: "nope-no-such-branch"+ })+ ).not.toThrow();++ // No branches were removed.+ expect(Object.keys(becca.branches).length).toBe(branchesBefore);+ });++ it("attributeDeleted returns early for an unknown attribute id", () => {+ const attributesBefore = Object.keys(becca.attributes).length;++ expect(() =>+ eventService.emit(eventService.ENTITY_DELETED, {+ entityName: "attributes",+ entityId: "nope-no-such-attribute"+ })+ ).not.toThrow();++ expect(Object.keys(becca.attributes).length).toBe(attributesBefore);+ });+ });++ describe("ENTER_PROTECTED_SESSION listener", () => {+ it("swallows errors thrown while decrypting protected notes", () => {+ const spy = vi.spyOn(becca, "decryptProtectedNotes").mockImplementation(() => {+ throw new Error("boom");+ });++ // The error must be caught inside the listener (and additionally by+ // the event dispatcher), so emitting never throws.+ expect(() => eventService.emit(eventService.ENTER_PROTECTED_SESSION)).not.toThrow();+ expect(spy).toHaveBeenCalled();+ });+ });++ describe("load()", () => {+ it("loads etapi tokens into becca", () => {+ const etapiTokenId = "loaderEtapiToken1";+ const now = "2025-01-01 00:00:00.000Z";++ withContext(() => {+ getSql().execute(+ /*sql*/`INSERT INTO etapi_tokens (etapiTokenId, name, tokenHash, utcDateCreated, utcDateModified, isDeleted)+ VALUES (?, ?, ?, ?, ?, 0)`,+ [etapiTokenId, "loader-test-token", "hash-value", now, now]+ );++ load();+ });++ const token = becca.getEtapiToken(etapiTokenId);+ expect(token).not.toBeNull();+ expect(token?.name).toBe("loader-test-token");+ expect(becca.loaded).toBe(true);+ });+ });++ describe("reload()", () => {+ it("reloads becca and notifies the frontend with the supplied reason", () => {+ const spy = vi.spyOn(ws, "reloadFrontend").mockImplementation(() => {});++ withContext(() => reload("custom reason"));++ expect(becca.loaded).toBe(true);+ expect(spy).toHaveBeenCalledWith("custom reason");+ });++ it("falls back to a default reason when none is given", () => {+ const spy = vi.spyOn(ws, "reloadFrontend").mockImplementation(() => {});++ withContext(() => reload(""));++ // The empty reason triggers the `reason || "becca reloaded"` fallback.+ expect(spy).toHaveBeenCalledWith("becca reloaded");+ });+ });++ it("exposes load and reload through the default export", () => {+ expect(typeof beccaLoader.load).toBe("function");+ expect(typeof beccaLoader.reload).toBe("function");+ expect(beccaLoader.beccaLoaded).toBeInstanceOf(Promise);+ });+});diff --git a/packages/trilium-core/src/becca/becca_service.spec.ts b/packages/trilium-core/src/becca/becca_service.spec.tsnew file mode 100644index 0000000000..7a4b47ba45--- /dev/null+++ b/packages/trilium-core/src/becca/becca_service.spec.ts@@ -0,0 +1,202 @@+import { describe, expect, it } from "vitest";++import becca from "./becca.js";+import beccaService from "./becca_service.js";+import BAttribute from "./entities/battribute.js";+import BBranch from "./entities/bbranch.js";+import { buildNote } from "../test/becca_easy_mocking.js";++let counter = 0;++/**+ * Returns a unique note id so the process-wide becca singleton does not get+ * polluted by leftovers from previous `it()`s in this file.+ */+function uniqueId(prefix: string) {+ counter++;+ return `${prefix}_${counter}`;+}++/**+ * Creates an in-memory branch (registered in becca) linking child to parent,+ * optionally with a prefix. The note graph helpers don't set prefixes, so we+ * build the branch directly here.+ */+function linkBranch(childNoteId: string, parentNoteId: string, prefix: string | null = null) {+ return new BBranch({+ branchId: `${parentNoteId}_${childNoteId}`,+ noteId: childNoteId,+ parentNoteId,+ prefix,+ notePosition: 0,+ isExpanded: false,+ utcDateModified: ""+ });+}++describe("becca_service", () => {+ describe("isNotePathArchived", () => {+ it("returns true when the last note in the path is itself archived", () => {+ const id = uniqueId("archivedLeaf");+ buildNote({ id, title: "leaf", "#archived": "" });++ expect(beccaService.isNotePathArchived([id])).toBe(true);+ });++ it("returns true when an ancestor has an inheritable archived label", () => {+ const ancestorId = uniqueId("inheritAncestor");+ const leafId = uniqueId("inheritLeaf");++ const ancestor = buildNote({ id: ancestorId, title: "ancestor" });+ buildNote({ id: leafId, title: "leaf" });++ // Inheritable archived label on the ancestor (not on the leaf itself).+ new BAttribute({+ noteId: ancestorId,+ attributeId: uniqueId("attr"),+ type: "label",+ name: "archived",+ value: "",+ position: 0,+ isInheritable: true+ });+ expect(ancestor.hasInheritableArchivedLabel()).toBe(true);++ expect(beccaService.isNotePathArchived([ancestorId, leafId])).toBe(true);+ });++ it("returns false when neither the leaf nor any ancestor is archived", () => {+ const ancestorId = uniqueId("plainAncestor");+ const leafId = uniqueId("plainLeaf");++ buildNote({ id: ancestorId, title: "ancestor" });+ buildNote({ id: leafId, title: "leaf" });++ expect(beccaService.isNotePathArchived([ancestorId, leafId])).toBe(false);+ });+ });++ describe("getNoteTitle", () => {+ it("returns the plain title when no parent prefix is involved", () => {+ const id = uniqueId("plainTitle");+ buildNote({ id, title: "Hello World" });++ expect(beccaService.getNoteTitle(id)).toBe("Hello World");+ });++ it("returns an error placeholder when the note is missing", () => {+ const title = beccaService.getNoteTitle(uniqueId("missing"));++ expect(title).toBe("[error fetching title]");+ });++ it("prepends the branch prefix when the parent branch has one", () => {+ const parentId = uniqueId("prefixParent");+ const childId = uniqueId("prefixChild");++ buildNote({ id: parentId, title: "parent" });+ buildNote({ id: childId, title: "child" });+ linkBranch(childId, parentId, "PFX");++ expect(beccaService.getNoteTitle(childId, parentId)).toBe("PFX - child");+ });++ it("returns just the title when the parent branch has no prefix", () => {+ const parentId = uniqueId("noPrefixParent");+ const childId = uniqueId("noPrefixChild");++ buildNote({ id: parentId, title: "parent" });+ buildNote({ id: childId, title: "child" });+ linkBranch(childId, parentId, null);++ expect(beccaService.getNoteTitle(childId, parentId)).toBe("child");+ });+ });++ describe("getNoteTitleAndIcon", () => {+ it("returns both the icon and the title for an existing note", () => {+ const id = uniqueId("iconTitle");+ buildNote({ id, title: "With Icon" });++ const result = beccaService.getNoteTitleAndIcon(id);++ expect(result.title).toBe("With Icon");+ expect(typeof result.icon).toBe("string");+ });++ it("returns an error placeholder and no icon when the note is missing", () => {+ const result = beccaService.getNoteTitleAndIcon(uniqueId("missingIcon"));++ expect(result.title).toBe("[error fetching title]");+ expect(result.icon).toBeUndefined();+ });++ it("prepends the branch prefix when the parent branch has one", () => {+ const parentId = uniqueId("iconPrefixParent");+ const childId = uniqueId("iconPrefixChild");++ buildNote({ id: parentId, title: "parent" });+ buildNote({ id: childId, title: "child" });+ linkBranch(childId, parentId, "PFX");++ const result = beccaService.getNoteTitleAndIcon(childId, parentId);++ expect(result.title).toBe("PFX - child");+ expect(typeof result.icon).toBe("string");+ });+ });++ describe("getNoteTitleForPath", () => {+ it("returns the single title for a one-element path", () => {+ const id = uniqueId("singlePath");+ buildNote({ id, title: "Only Note" });++ expect(beccaService.getNoteTitleForPath([id])).toBe("Only Note");+ });++ it("joins multiple titles with the separator, starting after the hoisted root", () => {+ // The default hoisted note is "root", so the path must start with it+ // for the collected titles to begin at the first real child.+ const childId = uniqueId("multiChild");+ const grandChildId = uniqueId("multiGrandChild");++ const child = buildNote({ id: childId, title: "Child" });+ const grandChild = buildNote({ id: grandChildId, title: "Grandchild" });++ const root = becca.notes["root"];+ expect(root).toBeDefined();+ linkBranch(childId, "root");+ linkBranch(grandChildId, childId);++ // sanity: both notes are registered+ expect(child.noteId).toBe(childId);+ expect(grandChild.noteId).toBe(grandChildId);++ const result = beccaService.getNoteTitleForPath(["root", childId, grandChildId]);++ expect(result).toBe("Child › Grandchild");+ });++ it("collects titles after the first segment when the path is outside the hoisted subtree", () => {+ // No element of this path equals the hoisted note ("root"), so the+ // path is treated as outside the hoisted subtree. The flag flips on+ // the first element (after its skipped push), so collection begins+ // from the second segment onwards.+ const outerId = uniqueId("outsideOuter");+ const innerId = uniqueId("outsideInner");++ buildNote({ id: outerId, title: "Outer" });+ buildNote({ id: innerId, title: "Inner" });+ linkBranch(innerId, outerId);++ const result = beccaService.getNoteTitleForPath([outerId, innerId]);++ expect(result).toBe("Inner");+ });++ it("throws when the argument is not an array", () => {+ // @ts-expect-error deliberately passing a non-array to hit the guard+ expect(() => beccaService.getNoteTitleForPath("not-an-array")).toThrow();+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts b/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.tsnew file mode 100644index 0000000000..cc05ca194d--- /dev/null+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts@@ -0,0 +1,186 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import protectedSessionService from "../../services/protected_session.js";+import { getSql } from "../../services/sql/index.js";+import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";+import type BNote from "./bnote.js";+import BBlob from "./bblob.js";+import BOption from "./boption.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * setContent, save) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Creates a fresh text note under root in the shared in-memory DB. */+function createNote(opts: { isProtected?: boolean } = {}): BNote {+ counter++;+ return withContext(() => {+ const { note } = noteService.createNewNote({+ parentNoteId: "root",+ title: `abstract-becca-entity-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ });+ if (opts.isProtected) {+ note.isProtected = true;+ }+ return note;+ });+}++// exactly 16 bytes+const PROTECTED_KEY = encodeUtf8("0123456789abcdef");++describe("AbstractBeccaEntity (real DB)", () => {+ afterEach(() => {+ protectedSessionService.resetDataKey();+ vi.restoreAllMocks();+ });++ describe("hasStringContent / init defaults", () => {+ it("hasStringContent defaults to true for entities that don't override it", () => {+ const blob = new BBlob({+ blobId: "abe-blob-default",+ content: "x",+ contentLength: 1,+ dateModified: "2020-01-01 00:00:00.000Z",+ utcDateModified: "2020-01-01 00:00:00.000Z"+ });++ expect(blob.hasStringContent()).toBe(true);+ });++ it("init is a no-op that does not throw for entities that don't override it", () => {+ const blob = new BBlob({+ blobId: "abe-blob-init",+ content: "x",+ contentLength: 1,+ dateModified: "2020-01-01 00:00:00.000Z",+ utcDateModified: "2020-01-01 00:00:00.000Z"+ });++ expect(() => blob.init()).not.toThrow();+ expect(blob.init()).toBeUndefined();+ });+ });++ describe("getUtcDateChanged", () => {+ it("returns utcDateModified when present", () => {+ const blob = new BBlob({+ blobId: "abe-date-modified",+ content: "x",+ contentLength: 1,+ dateModified: "2020-01-01 00:00:00.000Z",+ utcDateModified: "2021-02-03 04:05:06.000Z"+ });++ expect(blob.getUtcDateChanged()).toBe("2021-02-03 04:05:06.000Z");+ });++ it("falls back to utcDateCreated when utcDateModified is absent", () => {+ const blob = new BBlob({+ blobId: "abe-date-created",+ content: "x",+ contentLength: 1,+ dateModified: "2020-01-01 00:00:00.000Z",+ utcDateModified: ""+ });+ blob.utcDateModified = undefined;+ blob.utcDateCreated = "2019-09-09 09:09:09.000Z";++ expect(blob.getUtcDateChanged()).toBe("2019-09-09 09:09:09.000Z");+ });+ });++ describe("putEntityChange isSynced branch", () => {+ it("saves an options entity (forces the non-synced branch) and a regular entity", () => {+ // Regular (non-options) entity: putEntityChange always sets isSynced true.+ const note = createNote();+ expect(note.noteId).toBeDefined();++ // Options entity with isSynced falsy -> ternary false-branch.+ const option = new BOption({+ name: `abeTestOption${counter}`,+ value: "v",+ isSynced: false,+ utcDateModified: "2020-01-01 00:00:00.000Z"+ });+ withContext(() => option.save());++ const stored = getSql().getValue<string>(+ "SELECT value FROM options WHERE name = ?",+ [`abeTestOption${counter}`]+ );+ expect(stored).toBe("v");+ });+ });++ describe("_setContent guards", () => {+ it("throws when content is null", () => {+ const note = createNote();+ expect(() => withContext(() => note.setContent(null as unknown as string))).toThrow(+ /Cannot set null content/+ );+ });++ it("throws when content is undefined", () => {+ const note = createNote();+ expect(() =>+ withContext(() => note.setContent(undefined as unknown as string))+ ).toThrow(/Cannot set null content/);+ });+ });++ describe("forceFrontendReload componentId branch (saveBlob)", () => {+ it("saves new content with forceFrontendReload set", () => {+ const note = createNote();+ withContext(() =>+ note.setContent("<p>reload-me-" + counter + "</p>", { forceFrontendReload: true })+ );++ expect(unwrapStringOrBuffer(note.getContent())).toBe("<p>reload-me-" + counter + "</p>");+ });+ });++ describe("protected content paths", () => {+ it("encrypts string content when a protected session is available", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });++ withContext(() => note.setContent("super secret " + counter));++ // Round-trips back to plaintext while the session is available.+ expect(unwrapStringOrBuffer(note.getContent())).toBe("super secret " + counter);+ });++ it("throws when encryption fails (encrypt returns null)", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });++ vi.spyOn(protectedSessionService, "encrypt").mockReturnValue(null);++ expect(() => withContext(() => note.setContent("won't encrypt " + counter))).toThrow(+ /Unable to encrypt/+ );+ });++ it("throws when the protected session is not available", () => {+ // Create the protected note while a session is available, then drop the key.+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ protectedSessionService.resetDataKey();++ expect(() => withContext(() => note.setContent("no session " + counter))).toThrow(+ /protected session is not available/+ );+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/battachment.spec.ts b/packages/trilium-core/src/becca/entities/battachment.spec.tsnew file mode 100644index 0000000000..c0873ce08b--- /dev/null+++ b/packages/trilium-core/src/becca/entities/battachment.spec.ts@@ -0,0 +1,479 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { AttachmentRow } from "@triliumnext/commons";++import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import protectedSessionService from "../../services/protected_session.js";+import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";+import becca from "../becca.js";+import BAttachment from "./battachment.js";+import type BNote from "./bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * saveAttachment/setContent, markAsDeleted, convertToNote) require CLS.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Creates a fresh text note under root in the shared in-memory DB. */+function createNote(opts: { isProtected?: boolean; content?: string } = {}): BNote {+ counter++;+ return withContext(() => {+ const { note } = noteService.createNewNote({+ parentNoteId: "root",+ title: `battachment-spec-${counter}`,+ content: opts.content ?? "<p>hello</p>",+ type: "text"+ });+ if (opts.isProtected) {+ note.isProtected = true;+ }+ return note;+ });+}++// exactly 16 bytes+const PROTECTED_KEY = encodeUtf8("0123456789abcdef");++/** A valid attachment row, with individual fields removable for validation tests. */+function baseRow(overrides: Partial<AttachmentRow> = {}): AttachmentRow {+ return {+ ownerId: "someOwner",+ role: "file",+ mime: "text/plain",+ title: "t",+ ...overrides+ } as AttachmentRow;+}++describe("BAttachment (real DB)", () => {+ afterEach(() => {+ protectedSessionService.resetDataKey();+ vi.restoreAllMocks();+ });++ describe("updateFromRow validation", () => {+ it("throws when ownerId is missing or blank", () => {+ expect(() => new BAttachment(baseRow({ ownerId: "" }))).toThrow(/ownerId/);+ expect(() => new BAttachment(baseRow({ ownerId: " " }))).toThrow(/ownerId/);+ });++ it("throws when role is missing or blank", () => {+ expect(() => new BAttachment(baseRow({ role: "" }))).toThrow(/role/);+ expect(() => new BAttachment(baseRow({ role: " " }))).toThrow(/role/);+ });++ it("throws when mime is missing or blank", () => {+ expect(() => new BAttachment(baseRow({ mime: "" }))).toThrow(/mime/);+ expect(() => new BAttachment(baseRow({ mime: " " }))).toThrow(/mime/);+ });++ it("throws when title is missing or blank", () => {+ expect(() => new BAttachment(baseRow({ title: "" }))).toThrow(/title/);+ expect(() => new BAttachment(baseRow({ title: " " }))).toThrow(/title/);+ });++ it("constructs successfully with all required fields and assigns them", () => {+ const att = new BAttachment(baseRow({ position: 30, isProtected: false }));+ expect(att.ownerId).toBe("someOwner");+ expect(att.role).toBe("file");+ expect(att.mime).toBe("text/plain");+ expect(att.title).toBe("t");+ expect(att.position).toBe(30);+ expect(att.isProtected).toBe(false);+ // New (unsaved) attachment is immediately treated as decrypted.+ expect(att.isDecrypted).toBe(true);+ });+ });++ describe("copy / getNote / hasStringContent / getFileName", () => {+ it("copy produces an independent attachment with the same descriptive fields", () => {+ const note = createNote();+ const att = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "orig", content: "hi" })+ );++ const clone = att.copy();+ expect(clone).not.toBe(att);+ expect(clone.ownerId).toBe(att.ownerId);+ expect(clone.role).toBe("file");+ expect(clone.mime).toBe("text/plain");+ expect(clone.title).toBe("orig");+ // The clone is a brand-new entity without its own id yet.+ expect(clone.attachmentId).toBeUndefined();+ });++ it("getNote resolves the owning note through becca", () => {+ const note = createNote();+ const att = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "gn", content: "x" })+ );++ expect(att.getNote()).toBe(note);+ });++ it("hasStringContent reflects the mime via isStringNote", () => {+ const stringAtt = new BAttachment(baseRow({ mime: "text/plain", title: "s" }));+ const binaryAtt = new BAttachment(baseRow({ mime: "image/png", role: "image", title: "b" }));++ expect(stringAtt.hasStringContent()).toBe(true);+ expect(binaryAtt.hasStringContent()).toBe(false);+ });++ it("getFileName uses 'image' for image role and 'file' otherwise", () => {+ const fileAtt = new BAttachment(baseRow({ role: "file", mime: "text/plain", title: "doc" }));+ const imageAtt = new BAttachment(baseRow({ role: "image", mime: "image/png", title: "pic" }));++ expect(typeof fileAtt.getFileName()).toBe("string");+ expect(typeof imageAtt.getFileName()).toBe("string");+ });+ });++ describe("content round-trip", () => {+ it("setContent then getContent round-trips through the blob store", () => {+ const note = createNote();+ const att = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "rt", content: "" })+ );++ withContext(() => att.setContent("payload-" + counter, { forceSave: true }));++ expect(unwrapStringOrBuffer(att.getContent())).toBe("payload-" + counter);+ });+ });++ describe("isContentAvailable / getTitleOrProtected / decrypt", () => {+ it("a non-protected attachment is always content-available and exposes its title", () => {+ const note = createNote();+ const att = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "plain", content: "x" })+ );++ expect(att.isContentAvailable()).toBe(true);+ expect(att.getTitleOrProtected()).toBe("plain");+ });++ it("a protected attachment hides its title once the session is dropped", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "secret-" + counter,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ // While the session is available it stays readable.+ expect(att.isContentAvailable()).toBe(true);++ protectedSessionService.resetDataKey();++ // Reload from the DB so a protected, encrypted-from-row instance is produced.+ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;+ expect(reloaded.isProtected).toBe(true);+ expect(reloaded.isContentAvailable()).toBe(false);+ expect(reloaded.getTitleOrProtected()).toBe("[protected]");+ });++ it("decrypt restores the plaintext title when the session is available on reload", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const plainTitle = "decrypt-me-" + counter;+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: plainTitle,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ // Reload with the session still available -> decrypt() runs the try branch.+ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;+ expect(reloaded.isProtected).toBe(true);+ expect(reloaded.title).toBe(plainTitle);+ expect(reloaded.isDecrypted).toBe(true);+ });++ it("decrypt falls back to an empty title when decryptString yields a falsy value", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "empties-" + counter,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ // decryptString returns null -> the `|| ""` fallback is exercised.+ vi.spyOn(protectedSessionService, "decryptString").mockReturnValue(null);++ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;+ expect(reloaded.title).toBe("");+ expect(reloaded.isDecrypted).toBe(true);+ });++ it("decrypt swallows decryption errors and leaves the entity not-decrypted", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "boom-" + counter,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ // Force the catch path of decrypt(): session is available but decryptString throws.+ vi.spyOn(protectedSessionService, "decryptString").mockImplementation(() => {+ throw new Error("kaput");+ });++ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;+ expect(reloaded.isProtected).toBe(true);+ // The catch branch was taken: isDecrypted was never flipped to true.+ expect(reloaded.isDecrypted).toBeFalsy();+ });+ });++ describe("convertToNote", () => {+ it("throws for a 'search' type guard", () => {+ const att = new BAttachment(baseRow({ role: "file", mime: "text/plain", title: "srch" }));+ (att as unknown as { type: string }).type = "search";++ expect(() => withContext(() => att.convertToNote())).toThrow(/search/);+ });++ it("throws when the owning note cannot be found", () => {+ const att = new BAttachment(+ baseRow({ ownerId: "missingOwner123", role: "file", mime: "text/plain", title: "noOwner" })+ );++ expect(() => withContext(() => att.convertToNote())).toThrow(/Cannot find note/);+ });++ it("throws when the role has no note-type mapping", () => {+ const note = createNote();+ const att = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "badrole", content: "x" })+ );+ // Mutate to an unmapped role after construction.+ att.role = "unknownRole";++ expect(() => withContext(() => att.convertToNote())).toThrow(/Mapping from attachment role/);+ });++ it("throws when converting a protected attachment outside of a protected session", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "protConv-" + counter,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ protectedSessionService.resetDataKey();+ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;++ expect(() => withContext(() => reloaded.convertToNote())).toThrow(/protected session/);+ });++ it("converts a 'file' attachment into a note without rewriting parent content", () => {+ const parentContent = "<p>no image refs here</p>";+ const note = createNote({ content: parentContent });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "fileconv-" + counter,+ content: "file body"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ const { note: created, branch } = withContext(() => att.convertToNote());++ expect(created.type).toBe("file");+ expect(created.title).toBe("fileconv-" + counter);+ expect(branch.parentNoteId).toBe(note.noteId);+ // The attachment row is now soft-deleted, so it is no longer retrievable.+ expect(attachmentId ? becca.getAttachment(attachmentId) : null).toBeFalsy();+ // Parent content is unchanged (no image-url rewrite for a 'file' role).+ expect(unwrapStringOrBuffer(note.getContent())).toBe(parentContent);+ });++ it("converts an 'image' attachment and rewrites the embedded attachment URL in the parent", () => {+ const note = createNote({ content: "<p>placeholder</p>" });+ const att = withContext(() =>+ note.saveAttachment({+ role: "image",+ mime: "image/png",+ title: "imgconv-" + counter,+ content: "binarydata"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ // Embed a reference to the attachment image URL so replaceAll has something to change.+ const refContent = `<img src="api/attachments/${attachmentId}/image/foo.png">`;+ withContext(() => note.setContent(refContent));++ const { note: created } = withContext(() => att.convertToNote());++ expect(created.type).toBe("image");+ // The parent content's attachment URL has been rewritten to the new image note URL.+ const expected = `<img src="api/images/${created.noteId}/foo.png">`;+ expect(unwrapStringOrBuffer(note.getContent())).toBe(expected);+ });++ it("converts an 'image' attachment without touching content that has no matching URL", () => {+ const stableContent = "<p>nothing to rewrite</p>";+ const note = createNote({ content: stableContent });+ const att = withContext(() =>+ note.saveAttachment({+ role: "image",+ mime: "image/png",+ title: "imgnochange-" + counter,+ content: "binarydata"+ })+ );++ const { note: created } = withContext(() => att.convertToNote());++ expect(created.type).toBe("image");+ // No URL matched, so the parent content stays exactly as it was.+ expect(unwrapStringOrBuffer(note.getContent())).toBe(stableContent);+ });++ it("throws when an image parent has non-string content", () => {+ // Build a text parent but force its content to be non-string so the+ // type guard inside the image branch fires.+ const note = createNote({ content: "<p>x</p>" });+ const att = withContext(() =>+ note.saveAttachment({+ role: "image",+ mime: "image/png",+ title: "nonstr-" + counter,+ content: "binarydata"+ })+ );++ vi.spyOn(note, "getContent").mockReturnValue(new Uint8Array([1, 2, 3]));++ expect(() => withContext(() => att.convertToNote())).toThrow(/non-string content/);+ });+ });++ describe("getPojo / getPojoToSave", () => {+ it("getPojo exposes the descriptive fields and drops a blank title", () => {+ const att = new BAttachment(baseRow({ role: "file", mime: "text/plain", title: "pojo" }));+ const pojo = att.getPojo();++ expect(pojo.ownerId).toBe("someOwner");+ expect(pojo.role).toBe("file");+ expect(pojo.mime).toBe("text/plain");+ expect(pojo.title).toBe("pojo");+ expect(pojo.isDeleted).toBe(false);+ });++ it("getPojo maps a blank title to undefined", () => {+ const att = new BAttachment(baseRow({ role: "file", mime: "text/plain", title: "nonblank" }));+ // Blank the title after construction so getPojo's `title || undefined` falls through.+ att.title = "";++ expect(att.getPojo().title).toBeUndefined();+ });++ it("getPojoToSave strips contentLength and leaves the title for non-protected attachments", () => {+ const att = new BAttachment(baseRow({ role: "file", mime: "text/plain", title: "save" }));+ att.contentLength = 42;++ const pojo = att.getPojoToSave();+ expect("contentLength" in pojo).toBe(false);+ expect(pojo.title).toBe("save");+ });++ it("getPojoToSave encrypts the title for a decrypted protected attachment", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const att = new BAttachment(+ baseRow({ role: "file", mime: "text/plain", title: "plaintext", isProtected: true })+ );+ // New attachment with no id is treated as decrypted.+ expect(att.isDecrypted).toBe(true);++ vi.spyOn(protectedSessionService, "encrypt").mockReturnValue("CIPHER");++ const pojo = att.getPojoToSave();+ expect(pojo.isProtected).toBe(true);+ expect(pojo.title).toBe("CIPHER");+ });++ it("getPojoToSave handles a blank title and a null encrypt result for a protected attachment", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const att = new BAttachment(+ baseRow({ role: "file", mime: "text/plain", title: "nonblank", isProtected: true })+ );+ expect(att.isDecrypted).toBe(true);+ // Blank the title so `pojo.title || ""` falls through to "".+ att.title = "";++ // encrypt returns null so `encrypt(...) || undefined` falls through to undefined.+ const encryptSpy = vi.spyOn(protectedSessionService, "encrypt").mockReturnValue(null);++ const pojo = att.getPojoToSave();+ expect(pojo.isProtected).toBe(true);+ expect(pojo.title).toBeUndefined();+ expect(encryptSpy).toHaveBeenCalledWith("");+ });++ it("getPojoToSave drops the title for a protected attachment outside a session", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ const att = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: "keepcipher-" + counter,+ content: "x"+ })+ );+ const attachmentId = att.attachmentId;+ expect(attachmentId).toBeDefined();++ protectedSessionService.resetDataKey();+ const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;+ // Loaded protected attachment outside a session is not decrypted.+ expect(reloaded.isDecrypted).toBeFalsy();++ const pojo = reloaded.getPojoToSave();+ expect(pojo.isProtected).toBe(true);+ // Title is omitted so the original ciphertext is preserved on save.+ expect("title" in pojo).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/battribute.spec.ts b/packages/trilium-core/src/becca/entities/battribute.spec.tsnew file mode 100644index 0000000000..b669f1ab04--- /dev/null+++ b/packages/trilium-core/src/becca/entities/battribute.spec.ts@@ -0,0 +1,419 @@+import { describe, expect, it } from "vitest";++import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import { randomString } from "../../services/utils/index.js";+import becca from "../becca.js";+import BAttribute from "./battribute.js";+import BNote from "./bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * attribute.save()) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Creates a fresh text note under root in the real in-memory DB. */+function createNote(): BNote {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `battribute-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ }).note+ );+}++describe("BAttribute", () => {+ describe("init", () => {+ it("creates a skeleton note when the owner noteId is not yet in becca", () => {+ const skeletonNoteId = `skeleton-${randomString(8)}`;+ expect(skeletonNoteId in becca.notes).toBe(false);++ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: skeletonNoteId,+ type: "label",+ name: "x",+ value: "",+ position: 0,+ isInheritable: false+ });++ const skeleton = becca.getNote(skeletonNoteId);+ expect(skeleton).not.toBeNull();+ expect(skeleton?.ownedAttributes).toContain(attr);+ });++ it("registers a relation against its target note's targetRelations", () => {+ const owner = createNote();+ const target = createNote();++ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "myrel",+ value: target.noteId,+ position: 0,+ isInheritable: false+ });++ expect(target.targetRelations).toContain(attr);+ });+ });++ describe("validate", () => {+ it("throws on an invalid attribute type", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "bogus" as never,+ name: "x",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(() => attr.validate()).toThrow();+ });++ it("throws on an empty name", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: " ",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(() => attr.validate()).toThrow();+ });++ it("throws when a relation targets a non-existent note", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "myrel",+ value: `does-not-exist-${randomString(8)}`,+ position: 0,+ isInheritable: false+ });++ expect(() => attr.validate()).toThrow();+ });++ it("passes for a valid label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "valid",+ value: "v",+ position: 0,+ isInheritable: false+ });++ expect(() => attr.validate()).not.toThrow();+ });+ });++ describe("isAffectingSubtree", () => {+ it("is true for an inheritable label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "inh",+ value: "",+ position: 0,+ isInheritable: true+ });++ expect(attr.isAffectingSubtree).toBe(true);+ });++ it("is true for a template relation", () => {+ const owner = createNote();+ const target = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "template",+ value: target.noteId,+ position: 0,+ isInheritable: false+ });++ expect(attr.isAffectingSubtree).toBe(true);+ });++ it("is false for a plain non-inheritable label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "plain",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.isAffectingSubtree).toBe(false);+ });+ });++ describe("targetNoteId", () => {+ it("returns the value for a relation", () => {+ const owner = createNote();+ const target = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "myrel",+ value: target.noteId,+ position: 0,+ isInheritable: false+ });++ expect(attr.targetNoteId).toBe(target.noteId);+ });++ it("returns undefined for a label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "lbl",+ value: "v",+ position: 0,+ isInheritable: false+ });++ expect(attr.targetNoteId).toBeUndefined();+ });+ });++ describe("isAutoLink", () => {+ it("is true for an internalBookmark label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "internalBookmark",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.isAutoLink()).toBe(true);+ });++ it("is true for an internalLink relation", () => {+ const owner = createNote();+ const target = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "internalLink",+ value: target.noteId,+ position: 0,+ isInheritable: false+ });++ expect(attr.isAutoLink()).toBe(true);+ });++ it("is false for a plain label", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "plain",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.isAutoLink()).toBe(false);+ });++ it("is false when the type is neither label nor relation", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "plain",+ value: "",+ position: 0,+ isInheritable: false+ });++ // Force an out-of-band type so neither the relation nor the label+ // branch matches, hitting the final fallthrough return.+ attr.type = "bogus" as never;++ expect(attr.isAutoLink()).toBe(false);+ });+ });++ describe("getNote", () => {+ it("returns the owner note when present", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "lbl",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.getNote().noteId).toBe(owner.noteId);+ });++ it("throws when the owner note is missing from becca", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "lbl",+ value: "",+ position: 0,+ isInheritable: false+ });++ // Point the attribute at a noteId that does not exist in becca.+ attr.noteId = `gone-${randomString(8)}`;++ expect(() => attr.getNote()).toThrow();+ });+ });++ describe("getTargetNote", () => {+ it("throws when the attribute is not a relation", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "lbl",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(() => attr.getTargetNote()).toThrow();+ });++ it("returns null for a relation with an empty value", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "myrel",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.getTargetNote()).toBeNull();+ });++ it("returns the target note for a relation with a value", () => {+ const owner = createNote();+ const target = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "relation",+ name: "myrel",+ value: target.noteId,+ position: 0,+ isInheritable: false+ });++ expect(attr.getTargetNote()?.noteId).toBe(target.noteId);+ });+ });++ describe("isDefinition / getDefinition / getDefinedName", () => {+ it("recognises a label-definition and parses its defined name and definition", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "label:foo",+ value: "promoted,single,text",+ position: 0,+ isInheritable: false+ });++ expect(attr.isDefinition()).toBe(true);+ expect(attr.getDefinedName()).toBe("foo");++ const def = attr.getDefinition();+ expect(def.isPromoted).toBe(true);+ expect(def.multiplicity).toBe("single");+ expect(def.labelType).toBe("text");+ });++ it("recognises a relation-definition and parses its defined name", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "relation:bar",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.isDefinition()).toBe(true);+ expect(attr.getDefinedName()).toBe("bar");+ });++ it("treats a plain label as not a definition and leaves the name unchanged", () => {+ const owner = createNote();+ const attr = new BAttribute({+ attributeId: `attr-${randomString(8)}`,+ noteId: owner.noteId,+ type: "label",+ name: "plain",+ value: "",+ position: 0,+ isInheritable: false+ });++ expect(attr.isDefinition()).toBe(false);+ expect(attr.getDefinedName()).toBe("plain");+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/bblob.spec.ts b/packages/trilium-core/src/becca/entities/bblob.spec.tsnew file mode 100644index 0000000000..354dbcd95d--- /dev/null+++ b/packages/trilium-core/src/becca/entities/bblob.spec.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import BBlob from "./bblob.js";+import { getContext } from "../../services/context.js";+import { getSql } from "../../services/sql/index.js";++/** Wraps mutations in a CLS context, required for entity saves. */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++describe("BBlob static metadata", () => {+ it("exposes entityName, primaryKeyName and hashedProperties", () => {+ expect(BBlob.entityName).toBe("blobs");+ expect(BBlob.primaryKeyName).toBe("blobId");+ expect(BBlob.hashedProperties).toContain("content");+ expect(BBlob.hashedProperties).toContain("blobId");+ });+});++describe("BBlob instance", () => {+ it("populates fields from the row via the constructor", () => {+ const blob = new BBlob({+ blobId: "bblob-spec-1",+ content: "x",+ contentLength: 1,+ textRepresentation: "x-text",+ dateModified: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ expect(blob.blobId).toBe("bblob-spec-1");+ expect(blob.content).toBe("x");+ expect(blob.contentLength).toBe(1);+ expect(blob.textRepresentation).toBe("x-text");+ });++ it("getPojo returns the full shape including contentLength", () => {+ const blob = new BBlob({+ blobId: "bblob-spec-2",+ content: "hello",+ contentLength: 5,+ textRepresentation: "hello",+ dateModified: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ const pojo = blob.getPojo();+ expect(pojo).toEqual({+ blobId: "bblob-spec-2",+ content: "hello",+ contentLength: 5,+ textRepresentation: "hello",+ dateModified: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });+ });++ it("getPojo falls back to null for empty content and missing text representation", () => {+ const blob = new BBlob({+ blobId: "bblob-spec-3",+ content: "",+ contentLength: 0,+ textRepresentation: null,+ dateModified: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ const pojo = blob.getPojo();+ expect(pojo.content).toBeNull();+ expect(pojo.textRepresentation).toBeNull();+ });+});++describe("BBlob save (getPojoToSave omits contentLength)", () => {+ it("persists a row without the contentLength column", () => {+ const blobId = "bblob-spec-save-1";+ const blob = new BBlob({+ blobId,+ content: "persisted-content",+ contentLength: 17,+ textRepresentation: null,+ dateModified: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ withContext(() => blob.save());++ const row = getSql().getRow<Record<string, unknown>>(+ "SELECT * FROM blobs WHERE blobId = ?",+ [blobId]+ );+ expect(row).toBeDefined();+ expect(row?.blobId).toBe(blobId);+ // getPojoToSave strips contentLength, so the persisted row has no such column value beyond schema defaults.+ expect("contentLength" in (row ?? {})).toBe(false);+ });+});diff --git a/packages/trilium-core/src/becca/entities/bbranch.spec.ts b/packages/trilium-core/src/becca/entities/bbranch.spec.tsnew file mode 100644index 0000000000..f7c912eced--- /dev/null+++ b/packages/trilium-core/src/becca/entities/bbranch.spec.ts@@ -0,0 +1,244 @@+import { describe, expect, it } from "vitest";++import becca from "../becca.js";+import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import BBranch from "./bbranch.js";+import type BNote from "./bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * branch.save(), branch.deleteBranch(), markAsDeleted()) require CLS.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `bbranch-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ })+ );+}++describe("BBranch (real DB)", () => {+ describe("deleteBranch", () => {+ it("refuses to delete the root branch", () => {+ const rootBranch = becca.getBranchOrThrow("none_root");++ expect(() => withContext(() => rootBranch.deleteBranch())).toThrow();+ });++ it("deletes a note that has only one strong parent branch", () => {+ const { note, branch } = createNote("root");++ const deleted = withContext(() => branch.deleteBranch());++ expect(deleted).toBe(true);+ expect(branch.isDeleted).toBe(true);+ expect(note.isDeleted).toBe(true);+ });++ it("keeps the note when a second strong branch remains, returning false", () => {+ const { note } = createNote("root");+ const otherParent = createNote("root");++ // Add a second strong branch under another parent.+ const secondBranch = withContext(() => {+ const b = new BBranch({+ noteId: note.noteId,+ parentNoteId: otherParent.note.noteId,+ prefix: null,+ isExpanded: false+ });+ b.save();+ return b;+ });++ const firstBranch = note.getParentBranches().find((b) => b.parentNoteId === "root");+ expect(firstBranch).toBeDefined();++ const deleted = withContext(() => firstBranch?.deleteBranch());++ expect(deleted).toBe(false);+ expect(note.isDeleted).toBe(false);+ expect(secondBranch.isDeleted).toBe(false);+ });++ it("marks remaining weak branches as deleted when the only strong branch is removed", () => {+ const { note, branch } = createNote("root");++ // Add a weak clone under the bookmarks container so the note has a+ // strong branch (under root) plus a weak branch (under _lbBookmarks).+ const weakBranch = withContext(() => {+ const b = new BBranch({+ noteId: note.noteId,+ parentNoteId: "_lbBookmarks",+ prefix: null,+ isExpanded: false+ });+ b.save();+ return b;+ });++ expect(weakBranch.isWeak).toBe(true);+ expect(note.getStrongParentBranches().length).toBe(1);++ const deleted = withContext(() => branch.deleteBranch());++ // The single strong branch is gone, so the note (and its weak branch)+ // are deleted as well.+ expect(deleted).toBe(true);+ expect(weakBranch.isDeleted).toBe(true);+ expect(note.isDeleted).toBe(true);+ });++ it("deletes attached attachments together with the note", () => {+ const { note, branch } = createNote("root");++ const attachment = withContext(() =>+ note.saveAttachment({+ role: "file",+ mime: "text/plain",+ title: `att-${counter}`,+ content: "data"+ })+ );++ expect(note.getAttachments().some((a) => a.attachmentId === attachment.attachmentId)).toBe(true);++ const deleted = withContext(() => branch.deleteBranch());++ expect(deleted).toBe(true);+ // The attachment was marked deleted as part of the note deletion, so it+ // is no longer returned among the note's (non-deleted) attachments.+ expect(note.getAttachments().some((a) => a.attachmentId === attachment.attachmentId)).toBe(false);+ });+ });++ describe("beforeSaving", () => {+ it("throws when noteId or parentNoteId are missing", () => {+ const branch = new BBranch();++ expect(() => withContext(() => branch.save())).toThrow();+ });++ it("computes notePosition as max sibling position + 10, skipping _hidden", () => {+ const parent = createNote("root");+ const existing = createNote(parent.note.noteId);++ const maxPos = existing.branch.notePosition;+ const child = createNote("root");++ const newBranch = withContext(() => {+ const b = new BBranch({+ noteId: child.note.noteId,+ parentNoteId: parent.note.noteId,+ prefix: null,+ isExpanded: false+ });+ // notePosition intentionally left undefined to trigger computation.+ b.save();+ return b;+ });++ expect(newBranch.notePosition).toBe(maxPos + 10);+ });++ it("skips a falsy child branch while computing notePosition", () => {+ const parent = createNote("root");+ const existing = createNote(parent.note.noteId);+ const child = createNote("root");++ // Simulate the transient sync/import inconsistency where a child note is+ // still present in the parent's children array but its branch lookup+ // returns a falsy value. getChildBranches() will then yield an entry+ // that beforeSaving must skip.+ const key = `${existing.note.noteId}-${parent.note.noteId}`;+ const savedBranch = becca.childParentToBranch[key];+ delete becca.childParentToBranch[key];++ try {+ const newBranch = withContext(() => {+ const b = new BBranch({+ noteId: child.note.noteId,+ parentNoteId: parent.note.noteId,+ prefix: null,+ isExpanded: false+ });+ // notePosition undefined -> iterates child branches, skipping the+ // falsy one, so the computed position falls back to 0 + 10.+ b.save();+ return b;+ });++ expect(newBranch.notePosition).toBe(10);+ } finally {+ // Restore the becca map so subsequent assertions/teardown are consistent.+ becca.childParentToBranch[key] = savedBranch;+ }+ });+ });++ describe("createClone", () => {+ it("returns the existing branch and updates its position when one is present", () => {+ const { note, branch } = createNote("root");+ const target = createNote("root");++ // Create the clone under the target first.+ const firstClone = withContext(() => {+ const clone = branch.createClone(target.note.noteId);+ clone.save();+ return clone;+ });++ expect(firstClone.parentNoteId).toBe(target.note.noteId);+ expect(firstClone.noteId).toBe(note.noteId);++ // Cloning again to the same parent with a position returns the existing+ // branch and updates its notePosition.+ const secondClone = withContext(() => branch.createClone(target.note.noteId, 555));++ expect(secondClone).toBe(firstClone);+ expect(secondClone.notePosition).toBe(555);+ });++ it("returns the existing branch unchanged when no position is provided", () => {+ const { branch } = createNote("root");+ const target = createNote("root");++ const firstClone = withContext(() => {+ const clone = branch.createClone(target.note.noteId);+ clone.save();+ return clone;+ });++ const originalPos = firstClone.notePosition;+ const secondClone = withContext(() => branch.createClone(target.note.noteId));++ expect(secondClone).toBe(firstClone);+ expect(secondClone.notePosition).toBe(originalPos);+ });+ });++ describe("getParentNote", () => {+ it("returns the parent note of the branch", () => {+ const parent = createNote("root");+ const child = createNote(parent.note.noteId);++ expect(child.branch.getParentNote()).toBe(parent.note);+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/betapi_token.spec.ts b/packages/trilium-core/src/becca/entities/betapi_token.spec.tsnew file mode 100644index 0000000000..f55babc548--- /dev/null+++ b/packages/trilium-core/src/becca/entities/betapi_token.spec.ts@@ -0,0 +1,137 @@+import { describe, expect, it } from "vitest";++import becca from "../becca.js";+import BEtapiToken from "./betapi_token.js";+import { getContext } from "../../services/context.js";+import { getSql } from "../../services/sql/index.js";++/** Wraps mutations in a CLS context, required for entity saves. */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++describe("BEtapiToken static metadata", () => {+ it("exposes entityName, primaryKeyName and hashedProperties", () => {+ expect(BEtapiToken.entityName).toBe("etapi_tokens");+ expect(BEtapiToken.primaryKeyName).toBe("etapiTokenId");+ expect(BEtapiToken.hashedProperties).toContain("tokenHash");+ });+});++describe("BEtapiToken constructor", () => {+ it("returns early without populating fields when no row is given", () => {+ const token = new BEtapiToken();++ expect(token.etapiTokenId).toBeUndefined();+ expect(token.name).toBeUndefined();+ expect(token.tokenHash).toBeUndefined();+ });++ it("populates fields and registers itself in becca when a row is given", () => {+ const token = new BEtapiToken({+ etapiTokenId: "betapi-spec-1",+ name: "spec token",+ tokenHash: "hash-1"+ });++ expect(token.name).toBe("spec token");+ expect(token.tokenHash).toBe("hash-1");+ expect(token.isDeleted).toBe(false);+ expect(typeof token.utcDateCreated).toBe("string");+ expect(token.utcDateModified).toBe(token.utcDateCreated);+ expect(becca.etapiTokens["betapi-spec-1"]).toBe(token);+ });++ it("does not register the token in becca when the id is missing", () => {+ const before = Object.keys(becca.etapiTokens).length;++ const token = new BEtapiToken({+ etapiTokenId: undefined,+ name: "idless token",+ tokenHash: "hash-idless"+ });++ // updateFromRow and init both skip registration since etapiTokenId is falsy.+ expect(token.etapiTokenId).toBeUndefined();+ expect(token.name).toBe("idless token");+ expect(Object.keys(becca.etapiTokens).length).toBe(before);+ });++ it("keeps supplied dates and reflects the deleted flag", () => {+ const token = new BEtapiToken({+ etapiTokenId: "betapi-spec-2",+ name: "deleted token",+ tokenHash: "hash-2",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-28 14:10:39.688+0300",+ isDeleted: true+ });++ expect(token.utcDateCreated).toBe("2025-06-27 14:10:39.688+0300");+ expect(token.utcDateModified).toBe("2025-06-28 14:10:39.688+0300");+ expect(token.isDeleted).toBe(true);+ });+});++describe("BEtapiToken init", () => {+ it("re-registers the token in becca", () => {+ const token = new BEtapiToken({+ etapiTokenId: "betapi-spec-init-1",+ name: "init token",+ tokenHash: "hash-init"+ });++ delete becca.etapiTokens["betapi-spec-init-1"];+ token.init();++ expect(becca.etapiTokens["betapi-spec-init-1"]).toBe(token);+ });+});++describe("BEtapiToken getPojo", () => {+ it("returns the expected shape", () => {+ const token = new BEtapiToken({+ etapiTokenId: "betapi-spec-pojo-1",+ name: "pojo token",+ tokenHash: "hash-pojo",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300",+ isDeleted: false+ });++ expect(token.getPojo()).toEqual({+ etapiTokenId: "betapi-spec-pojo-1",+ name: "pojo token",+ tokenHash: "hash-pojo",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300",+ isDeleted: false+ });+ });+});++describe("BEtapiToken save (beforeSaving)", () => {+ it("updates utcDateModified, persists and registers the token", () => {+ const etapiTokenId = "betapi-spec-save-1";+ const token = new BEtapiToken({+ etapiTokenId,+ name: "save token",+ tokenHash: "hash-save",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ withContext(() => token.save());++ const row = getSql().getRow<Record<string, unknown>>(+ "SELECT * FROM etapi_tokens WHERE etapiTokenId = ?",+ [etapiTokenId]+ );+ expect(row).toBeDefined();+ expect(row?.name).toBe("save token");+ expect(row?.tokenHash).toBe("hash-save");+ expect(becca.etapiTokens[etapiTokenId]).toBe(token);+ // beforeSaving refreshes utcDateModified to "now", differing from the supplied value.+ expect(typeof token.utcDateModified).toBe("string");+ });+});diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex 46f860328a..a8bf85f166 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -345,6 +345,7 @@ class BNote extends AbstractBeccaEntity<BNote> {this.__validateTypeName(type, name);this.__ensureAttributeCacheIsAvailable();+ /* v8 ignore next 3 -- defensive: cache is always populated by __ensureAttributeCacheIsAvailable */if (!this.__attributeCache) {throw new Error("Attribute cache not available.");}@@ -432,6 +433,7 @@ class BNote extends AbstractBeccaEntity<BNote> {this.__getAttributes(path); // will refresh also this.__inheritableAttributeCache}+ /* v8 ignore next -- defensive: __getAttributes always sets the cache for a non-cyclic path */return this.__inheritableAttributeCache || [];}@@ -1171,16 +1173,7 @@ class BNote extends AbstractBeccaEntity<BNote> {isHidden: path.includes("_hidden")}));- notePaths.sort((a, b) => {- if (a.isInHoistedSubTree !== b.isInHoistedSubTree) {- return a.isInHoistedSubTree ? -1 : 1;- } else if (a.isArchived !== b.isArchived) {- return a.isArchived ? 1 : -1;- } else if (a.isHidden !== b.isHidden) {- return a.isHidden ? 1 : -1;- }- return a.notePath.length - b.notePath.length;- });+ notePaths.sort(compareNotePathRecords);return notePaths;}@@ -1477,6 +1470,7 @@ class BNote extends AbstractBeccaEntity<BNote> {const oldNoteUrl = `api/images/${this.noteId}/`;const newAttachmentUrl = `api/attachments/${attachment.attachmentId}/image/`;+ /* v8 ignore next 3 -- defensive: an eligible parent is always a text note with string content */if (typeof parentContent !== "string") {throw new Error("Unable to convert image note into attachment because parent note does not have a string content.");}@@ -1515,6 +1509,7 @@ class BNote extends AbstractBeccaEntity<BNote> {taskContext.noteDeletionHandlerTriggered = true;for (const branch of this.getParentBranches()) {+ /* v8 ignore next -- deleteId is always assigned above; the nullish fallback is unreachable */branch.deleteBranch(deleteId ?? undefined, taskContext);}}@@ -1576,6 +1571,7 @@ class BNote extends AbstractBeccaEntity<BNote> {for (const noteAttachment of this.getAttachments()) {const revisionAttachment = noteAttachment.copy();+ /* v8 ignore next 3 -- defensive: revision.save() above always assigns revisionId */if (!revision.revisionId) {throw new Error("Revision ID is missing.");}@@ -1766,6 +1762,7 @@ class BNote extends AbstractBeccaEntity<BNote> {getAttributeById(attributeId : string): BAttribute | undefined {this.__ensureAttributeCacheIsAvailable();+ /* v8 ignore next 3 -- defensive: cache is always populated by __ensureAttributeCacheIsAvailable */if (!this.__attributeCache) {throw new Error("Attribute cache not available.");}@@ -1795,4 +1792,21 @@ class BNote extends AbstractBeccaEntity<BNote> {}}+/**+ * Orders note-path records so the "best" path sorts first: paths inside the hoisted+ * subtree beat outside ones, non-archived beat archived, non-hidden beat hidden, and+ * shorter paths beat longer ones. Extracted from {@link BNote.getSortedNotePathRecords}+ * so the ordering logic can be unit-tested directly.+ */+export function compareNotePathRecords(a: NotePathRecord, b: NotePathRecord): number {+ if (a.isInHoistedSubTree !== b.isInHoistedSubTree) {+ return a.isInHoistedSubTree ? -1 : 1;+ } else if (a.isArchived !== b.isArchived) {+ return a.isArchived ? 1 : -1;+ } else if (a.isHidden !== b.isHidden) {+ return a.isHidden ? 1 : -1;+ }+ return a.notePath.length - b.notePath.length;+}+export default BNote;diff --git a/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts b/packages/trilium-core/src/becca/entities/bnote_attributes.spec.tsnew file mode 100644index 0000000000..5230056dce--- /dev/null+++ b/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts@@ -0,0 +1,361 @@+import { describe, expect, it } from "vitest";++import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import { buildNote } from "../../test/becca_easy_mocking.js";+import BBranchEntity from "./bbranch.js";+import type BBranch from "./bbranch.js";+import type BNote from "./bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * attribute.save(), markAsDeleted) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh text note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `bnote-attrs-spec-${counter}`,+ content: "<p>hello</p>",+ type: "text"+ })+ );+}++describe("BNote attribute methods (real DB)", () => {+ describe("getAttributes filtering and validation", () => {+ it("filters by type+name, type only, and name only", () => {+ const { note } = createNote("root");++ withContext(() => {+ note.addLabel("colorTag", "red");+ note.addRelation("linkTag", note.noteId);+ });++ // type && name+ const byTypeName = note.getAttributes("label", "colorTag");+ expect(byTypeName).toHaveLength(1);+ expect(byTypeName[0].type).toBe("label");+ expect(byTypeName[0].name).toBe("colorTag");++ // type only+ const byType = note.getAttributes("label");+ expect(byType.every((a) => a.type === "label")).toBe(true);+ expect(byType.some((a) => a.name === "colorTag")).toBe(true);++ // name only+ const byName = note.getAttributes(undefined, "linkTag");+ expect(byName).toHaveLength(1);+ expect(byName[0].type).toBe("relation");+ expect(byName[0].name).toBe("linkTag");++ // no filter -> internal cache array+ const all = note.getAttributes();+ expect(all.length).toBeGreaterThanOrEqual(2);+ });++ it("throws for an unrecognized type and for names containing # or ~", () => {+ const { note } = createNote("root");++ expect(() => note.getAttributes("bogus")).toThrow();+ expect(() => note.getAttributes(undefined, "#x")).toThrow();+ expect(() => note.getAttributes(undefined, "~y")).toThrow();+ });+ });++ describe("attribute inheritance and template resolution", () => {+ it("inherits an inheritable label from a parent and resolves template labels", () => {+ const parent = createNote("root");+ withContext(() => parent.note.addLabel("inheritedFlag", "yes", true));++ const child = createNote(parent.note.noteId);++ // Inherited (non-owned) label reachable through getAttributes.+ const inheritedLabels = child.note.getAttributes("label", "inheritedFlag");+ expect(inheritedLabels).toHaveLength(1);+ expect(inheritedLabels[0].value).toBe("yes");+ expect(inheritedLabels[0].noteId).toBe(parent.note.noteId);++ // The child must surface its inheritable attribute cache to its own children.+ const grandchild = createNote(child.note.noteId);+ expect(grandchild.note.getAttributes("label", "inheritedFlag")).toHaveLength(1);++ // Template note carrying labels, applied via a ~template relation.+ const template = createNote("root");+ withContext(() => {+ template.note.addLabel("fromTemplate", "tval");+ template.note.addLabel("template"); // marker, must NOT be inherited+ });++ const consumer = createNote("root");+ withContext(() => consumer.note.addRelation("template", template.note.noteId));++ const templated = consumer.note.getAttributes("label", "fromTemplate");+ expect(templated).toHaveLength(1);+ expect(templated[0].value).toBe("tval");+ // The 'template' marker label must be filtered out.+ expect(consumer.note.getAttributes("label", "template")).toHaveLength(0);+ });++ it("returns empty inheritable attributes for a note with no inheritable owned attrs", () => {+ const { note } = createNote("root");+ // Force the inheritable cache to be built and surfaced via a child.+ const child = createNote(note.noteId);+ expect(Array.isArray(child.note.getAttributes())).toBe(true);+ });++ it("guards against template cycles when resolving attributes", () => {+ // A note whose ~template relation points back to itself triggers the+ // path-cycle short-circuit inside __getAttributes.+ const selfTemplate = createNote("root");+ withContext(() => {+ selfTemplate.note.addLabel("selfLabel", "v");+ selfTemplate.note.addRelation("template", selfTemplate.note.noteId);+ });++ // Must not throw / recurse infinitely; the note still surfaces its own label.+ const attrs = selfTemplate.note.getAttributes();+ expect(Array.isArray(attrs)).toBe(true);+ expect(selfTemplate.note.getOwnedLabel("selfLabel")?.value).toBe("v");++ // A two-note ~inherit cycle exercises the mutual recursion guard as well.+ const a = createNote("root");+ const b = createNote("root");+ withContext(() => {+ a.note.addLabel("aLabel", "av");+ b.note.addLabel("bLabel", "bv");+ a.note.addRelation("inherit", b.note.noteId);+ b.note.addRelation("inherit", a.note.noteId);+ });++ expect(Array.isArray(a.note.getAttributes())).toBe(true);+ expect(Array.isArray(b.note.getAttributes())).toBe(true);+ });++ it("guards against a parent-tree cycle when resolving inheritable attributes", () => {+ // Construct an (illegal) parent cycle directly in becca to exercise the+ // path-cycle guard inside __getInheritableAttributes. The normal API+ // (validateParentChild) prevents such cycles, so this is built in-memory.+ const x = buildNote({ id: "cycleX", title: "cycleX", "#xFlag": "x" });+ const y = buildNote({ id: "cycleY", title: "cycleY", "#yFlag": "y" });++ // y is a parent of x, and x is a parent of y -> cycle.+ new BBranchEntity({+ noteId: x.noteId,+ parentNoteId: y.noteId,+ branchId: `${y.noteId}_${x.noteId}`+ });+ new BBranchEntity({+ noteId: y.noteId,+ parentNoteId: x.noteId,+ branchId: `${x.noteId}_${y.noteId}`+ });++ // Must terminate; the cycle guard returns an empty inheritable set+ // for the already-visited ancestor.+ expect(Array.isArray(x.getAttributes())).toBe(true);+ });+ });++ describe("has/get accessors over the combined cache", () => {+ it("covers hasAttribute, getAttributeCaseInsensitive and getRelationTarget", () => {+ const target = createNote("root");+ const { note } = createNote("root");++ withContext(() => {+ note.addLabel("MyLabel", "Val");+ note.addRelation("myRel", target.note.noteId);+ });++ expect(note.hasAttribute("label", "MyLabel")).toBe(true);+ expect(note.hasAttribute("label", "MyLabel", "Val")).toBe(true);+ expect(note.hasAttribute("label", "MyLabel", "other")).toBe(false);+ expect(note.hasAttribute("label", "nope")).toBe(false);++ // case-insensitive lookup with and without value+ expect(note.getAttributeCaseInsensitive("label", "mylabel", "val")).toBeDefined();+ expect(note.getAttributeCaseInsensitive("label", "MYLABEL")).toBeDefined();+ expect(note.getAttributeCaseInsensitive("label", "mylabel", "WRONG")).toBeUndefined();++ // relation target resolution+ const resolved = note.getRelationTarget("myRel");+ expect(resolved?.noteId).toBe(target.note.noteId);+ expect(note.getRelationTarget("missingRel")).toBeNull();+ });+ });++ describe("owned-only accessors", () => {+ it("covers hasOwnedRelation, getOwnedLabel, getRelation and getOwnedRelation", () => {+ const target = createNote("root");+ const { note } = createNote("root");++ withContext(() => {+ note.addLabel("ownLabel", "lv");+ note.addRelation("ownRel", target.note.noteId);+ });++ expect(note.hasOwnedRelation("ownRel")).toBe(true);+ expect(note.hasOwnedRelation("ownRel", target.note.noteId)).toBe(true);+ expect(note.hasOwnedRelation("missing")).toBe(false);++ expect(note.getOwnedLabel("ownLabel")?.value).toBe("lv");+ expect(note.getOwnedLabel("missing")).toBeNull();++ expect(note.getRelation("ownRel")?.value).toBe(target.note.noteId);+ expect(note.getRelation("missing")).toBeNull();++ expect(note.getOwnedRelation("ownRel")?.value).toBe(target.note.noteId);+ expect(note.getOwnedRelation("missing")).toBeNull();+ });+ });++ describe("label value collectors", () => {+ it("covers getLabelValues and getOwnedLabelValues", () => {+ const parent = createNote("root");+ withContext(() => parent.note.addLabel("multi", "inherited", true));++ const child = createNote(parent.note.noteId);+ withContext(() => child.note.addLabel("multi", "own"));++ const allValues = child.note.getLabelValues("multi");+ expect(allValues).toContain("own");+ expect(allValues).toContain("inherited");++ const ownValues = child.note.getOwnedLabelValues("multi");+ expect(ownValues).toEqual(["own"]);+ });+ });++ describe("getOwnedAttributes filter branches", () => {+ it("covers type+name+value, type+name, type only and name only", () => {+ const { note } = createNote("root");++ withContext(() => {+ note.addLabel("oa", "v1");+ note.addLabel("oa", "v2");+ note.addRelation("orel", note.noteId);+ });++ // type + name + value+ const tnv = note.getOwnedAttributes("label", "oa", "v1");+ expect(tnv).toHaveLength(1);+ expect(tnv[0].value).toBe("v1");++ // type + name+ const tn = note.getOwnedAttributes("label", "oa");+ expect(tn).toHaveLength(2);++ // type only+ const t = note.getOwnedAttributes("label");+ expect(t.every((a) => a.type === "label")).toBe(true);++ // name only+ const n = note.getOwnedAttributes(null, "orel");+ expect(n).toHaveLength(1);+ expect(n[0].type).toBe("relation");++ // no filter+ expect(note.getOwnedAttributes().length).toBeGreaterThanOrEqual(3);+ });+ });++ describe("definition collectors", () => {+ it("covers getRelationDefinitions and getLabelDefinitions", () => {+ const { note } = createNote("root");+ withContext(() => {+ note.addLabel("relation:child", "");+ note.addLabel("plain", "x");+ });++ expect(note.getRelationDefinitions().some((l) => l.name === "relation:child")).toBe(true);+ expect(note.getLabelDefinitions().some((l) => l.name === "relation:child")).toBe(true);+ });+ });++ describe("mutation helpers", () => {+ it("removeAttribute honours the value-match branch", () => {+ const { note } = createNote("root");+ withContext(() => {+ note.addLabel("rm", "keep");+ note.addLabel("rm", "drop");+ });++ withContext(() => note.removeAttribute("label", "rm", "drop"));++ const remaining = note.getOwnedAttributes("label", "rm");+ expect(remaining).toHaveLength(1);+ expect(remaining[0].value).toBe("keep");+ });++ it("toggleAttribute / toggleLabel / toggleRelation switch on and off", () => {+ const target = createNote("root");+ const { note } = createNote("root");++ withContext(() => {+ note.toggleLabel(true, "toggled", "on");+ note.toggleRelation(true, "togRel", target.note.noteId);+ });+ expect(note.getOwnedLabel("toggled")?.value).toBe("on");+ expect(note.getOwnedRelation("togRel")?.value).toBe(target.note.noteId);++ withContext(() => {+ note.toggleLabel(false, "toggled");+ note.toggleRelation(false, "togRel");+ });+ expect(note.getOwnedLabel("toggled")).toBeNull();+ expect(note.getOwnedRelation("togRel")).toBeNull();+ });++ it("removeRelation deletes a matching relation", () => {+ const target = createNote("root");+ const { note } = createNote("root");++ withContext(() => note.addRelation("delRel", target.note.noteId));+ expect(note.getOwnedRelation("delRel")).not.toBeNull();++ withContext(() => note.removeRelation("delRel"));+ expect(note.getOwnedRelation("delRel")).toBeNull();+ });+ });++ describe("attribute-by-id accessors", () => {+ it("getAttributeById finds via the cache", () => {+ const { note } = createNote("root");+ const attr = withContext(() => note.addLabel("byId", "value"));++ const found = note.getAttributeById(attr.attributeId);+ expect(found?.attributeId).toBe(attr.attributeId);+ expect(note.getAttributeById("nonexistent-id")).toBeUndefined();+ });++ it("setAttributeValueById updates the value and throws when not found", () => {+ const { note } = createNote("root");+ const attr = withContext(() => note.addLabel("settable", "old"));++ withContext(() => note.setAttributeValueById(attr.attributeId, "new"));+ expect(note.getOwnedLabel("settable")?.value).toBe("new");++ // Setting the same value again is a no-op (value unchanged).+ withContext(() => note.setAttributeValueById(attr.attributeId, "new"));+ expect(note.getOwnedLabel("settable")?.value).toBe("new");++ // Omitting the value coalesces to "" (the `value?.toString() || ""` fallback).+ withContext(() => note.setAttributeValueById(attr.attributeId));+ expect(note.getOwnedLabel("settable")?.value).toBe("");++ expect(() => withContext(() => note.setAttributeValueById("missing-attr-id", "x"))).toThrow();+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts b/packages/trilium-core/src/becca/entities/bnote_content.spec.tsnew file mode 100644index 0000000000..7b4ed0b9c4--- /dev/null+++ b/packages/trilium-core/src/becca/entities/bnote_content.spec.ts@@ -0,0 +1,558 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { dayjs } from "@triliumnext/commons";++import becca from "../becca.js";+import { getContext } from "../../services/context.js";+import eraseService from "../../services/erase.js";+import noteService from "../../services/notes.js";+import optionService from "../../services/options.js";+import protectedSessionService from "../../services/protected_session.js";+import Module from "module";++import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";+import { buildNote } from "../../test/becca_easy_mocking.js";+import type BNote from "./bnote.js";++// executeScript() does a lazy `require("../../services/script.js")` to avoid a+// circular import. That bare-`.js` require is resolvable only in the bundled+// production build (the source tree has script.ts, not script.js), so under+// vitest the native CommonJS require throws. We intercept Module._load for that+// exact specifier and hand back a stub exposing executeNote.+const executeNoteMock = vi.fn();++/** Wraps mutations in a CLS context, required for entity saves/content writes. */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Creates a fresh note under the given parent in the shared in-memory DB. */+function createNote(opts: { parentNoteId?: string; content?: string; type?: "text" | "code" | "image"; mime?: string; isProtected?: boolean } = {}): BNote {+ counter++;+ return withContext(() => {+ const { note } = noteService.createNewNote({+ parentNoteId: opts.parentNoteId ?? "root",+ title: `bnote-content-spec-${counter}`,+ content: opts.content ?? "<p>hello</p>",+ type: opts.type ?? "text",+ mime: opts.mime+ });+ if (opts.isProtected) {+ note.isProtected = true;+ }+ return note;+ });+}++const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes++describe("BNote content / misc getters", () => {+ afterEach(() => {+ protectedSessionService.resetDataKey();+ vi.restoreAllMocks();+ });++ describe("getTitleOrProtected (line 163)", () => {+ it("returns the title when content is available, and a placeholder when protected without a session", () => {+ const note = createNote();+ expect(note.getTitleOrProtected()).toBe(note.title);++ // Protected note with no session -> not available -> placeholder.+ const protectedNote = createNote({ isProtected: true });+ expect(protectedNote.getTitleOrProtected()).toBe("[protected]");+ });+ });++ describe("setJsonContent (line 240-241)", () => {+ it("serialises an object as JSON content and reads it back", () => {+ const note = createNote();+ withContext(() => note.setJsonContent({ a: 1, b: "two" }));++ expect(note.getJsonContent()).toEqual({ a: 1, b: "two" });+ });+ });++ describe("date getter objects (lines 244-258)", () => {+ it("returns dayjs objects for a persisted note", () => {+ const note = createNote();++ expect(dayjs.isDayjs(note.dateCreatedObj)).toBe(true);+ expect(dayjs.isDayjs(note.utcDateCreatedObj)).toBe(true);+ expect(dayjs.isDayjs(note.dateModifiedObj)).toBe(true);+ expect(dayjs.isDayjs(note.utcDateModifiedObj)).toBe(true);+ });++ it("returns null when the underlying date field is null", () => {+ const note = buildNote({ id: `date-null-${counter++}`, title: "dates" });+ // Force the `=== null` branch of each getter.+ (note as unknown as { dateCreated: string | null }).dateCreated = null;+ (note as unknown as { utcDateCreated: string | null }).utcDateCreated = null;+ (note as unknown as { dateModified: string | null }).dateModified = null;+ (note as unknown as { utcDateModified: string | null }).utcDateModified = null;++ expect(note.dateCreatedObj).toBeNull();+ expect(note.utcDateCreatedObj).toBeNull();+ expect(note.dateModifiedObj).toBeNull();+ expect(note.utcDateModifiedObj).toBeNull();+ });+ });++ describe("type / mime predicates (lines 266-321)", () => {+ it("isJson", () => {+ const json = buildNote({ id: `json-${counter++}`, type: "code", mime: "application/json" });+ expect(json.isJson()).toBe(true);++ const notJson = buildNote({ id: `notjson-${counter++}`, type: "code", mime: "text/plain" });+ expect(notJson.isJson()).toBe(false);+ });++ it("isJavaScript across the env-suffixed mimes", () => {+ const backend = buildNote({ id: `js-be-${counter++}`, type: "code", mime: "application/javascript;env=backend" });+ expect(backend.isJavaScript()).toBe(true);++ const xjs = buildNote({ id: `js-x-${counter++}`, type: "file", mime: "application/x-javascript" });+ expect(xjs.isJavaScript()).toBe(true);++ const textJs = buildNote({ id: `js-t-${counter++}`, type: "launcher", mime: "text/javascript" });+ expect(textJs.isJavaScript()).toBe(true);++ const notJs = buildNote({ id: `js-no-${counter++}`, type: "text", mime: "text/html" });+ expect(notJs.isJavaScript()).toBe(false);+ });++ it("isImage for image type and image/* file mime", () => {+ const imageType = buildNote({ id: `img-t-${counter++}`, type: "image", mime: "image/png" });+ expect(imageType.isImage()).toBe(true);++ const imageFile = buildNote({ id: `img-f-${counter++}`, type: "file", mime: "image/jpeg" });+ expect(imageFile.isImage()).toBe(true);++ const notImage = buildNote({ id: `img-no-${counter++}`, type: "file", mime: "text/plain" });+ expect(notImage.isImage()).toBe(false);+ });++ it("isStringNote delegates to hasStringContent (deprecated alias)", () => {+ const text = buildNote({ id: `str-${counter++}`, type: "text", mime: "text/html" });+ expect(text.isStringNote()).toBe(text.hasStringContent());+ expect(text.isStringNote()).toBe(true);++ const image = buildNote({ id: `str-no-${counter++}`, type: "image", mime: "image/png" });+ expect(image.isStringNote()).toBe(false);+ });++ it("getScriptEnv returns frontend / backend / null", () => {+ const frontendJs = buildNote({ id: `env-fe-${counter++}`, type: "code", mime: "application/javascript;env=frontend" });+ expect(frontendJs.getScriptEnv()).toBe("frontend");++ // A render note whose mime is NOT text/html, so isHtml() is false and the+ // dedicated `type === "render"` branch is what returns "frontend".+ const render = buildNote({ id: `env-render-${counter++}`, type: "render", mime: "text/plain" });+ expect(render.getScriptEnv()).toBe("frontend");++ const backendJs = buildNote({ id: `env-be-${counter++}`, type: "code", mime: "application/javascript;env=backend" });+ expect(backendJs.getScriptEnv()).toBe("backend");++ const plain = buildNote({ id: `env-none-${counter++}`, type: "text", mime: "text/plain" });+ expect(plain.getScriptEnv()).toBeNull();+ });+ });++ describe("executeScript (lines 329-333)", () => {+ it("delegates to scriptService.executeNote with this note as origin", () => {+ const note = buildNote({ id: `exec-${counter++}`, type: "code", mime: "application/javascript;env=backend" });+ executeNoteMock.mockReset();+ executeNoteMock.mockReturnValue("result");++ const moduleAny = Module as unknown as { _load: (...args: unknown[]) => unknown };+ const originalLoad = moduleAny._load;+ moduleAny._load = function (request: unknown, ...rest: unknown[]) {+ if (request === "../../services/script.js") {+ return { default: { executeNote: (...args: unknown[]) => executeNoteMock(...args) } };+ }+ return originalLoad.call(this, request, ...rest);+ };++ try {+ const result = note.executeScript();++ expect(executeNoteMock).toHaveBeenCalledTimes(1);+ expect(executeNoteMock.mock.calls[0]?.[0]).toBe(note);+ expect(executeNoteMock.mock.calls[0]?.[1]).toEqual({ originEntity: note });+ expect(result).toBe("result");+ } finally {+ moduleAny._load = originalLoad;+ }+ });+ });++ describe("attribute count getters (lines 980-1013)", () => {+ it("counts owned/inherited labels and relations, distinguishing auto-links", () => {+ const note = createNote();+ const target = createNote();++ withContext(() => {+ note.addLabel("plainLabel", "v");+ note.addRelation("relTo", target.noteId); // not an auto-link+ note.addRelation("internalLink", target.noteId); // auto-link+ });++ // labels+ expect(note.labelCount).toBeGreaterThanOrEqual(1);+ expect(note.ownedLabelCount).toBe(1);++ // relations: relationCount excludes auto-links, the *IncludingLinks variants include them.+ expect(note.relationCount).toBe(1);+ expect(note.relationCountIncludingLinks).toBe(2);+ expect(note.ownedRelationCount).toBe(1);+ expect(note.ownedRelationCountIncludingLinks).toBe(2);++ // target relations on the target note: it is the destination of two relations,+ // one of which (internalLink) is an auto-link.+ expect(target.targetRelationCount).toBe(1);+ expect(target.targetRelationCountIncludingLinks).toBe(2);++ // attributeCount / ownedAttributeCount include both labels and relations.+ expect(note.attributeCount).toBe(note.getAttributes().length);+ expect(note.ownedAttributeCount).toBe(3);+ });+ });++ describe("cloneTo (lines 1408-1417)", () => {+ it("clones into a parent's branch on success", () => {+ const source = createNote();+ const target = createNote();++ const res = withContext(() => source.cloneTo(target.noteId));++ expect(res.success).toBe(true);+ expect(becca.getBranchFromChildAndParent(source.noteId, target.noteId)).not.toBeNull();+ });++ it("fails when the target parent cannot be resolved to a branch", () => {+ const source = createNote();++ const res = source.cloneTo("doesNotExist123");++ expect(res.success).toBe(false);+ expect(typeof res.message).toBe("string");+ });+ });++ describe("isEligibleForConversionToAttachment / convertToParentAttachment (lines 1420-1493)", () => {+ function makeConvertibleImage() {+ const parent = createNote({ content: "" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "binary" });+ // Parent references the image and contains the image URL in its content.+ withContext(() => {+ parent.addRelation("imageLink", image.noteId);+ parent.setContent(`<img src="api/images/${image.noteId}/foo.png">`);+ });+ return { parent, image };+ }++ it("rejects a non-image note", () => {+ const text = createNote();+ expect(text.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("rejects an image with children", () => {+ const parent = createNote({ content: "" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });+ createNote({ parentNoteId: image.noteId });+ expect(image.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("rejects an image with more than one parent branch", () => {+ const parentA = createNote({ content: "" });+ const parentB = createNote({ content: "" });+ const image = createNote({ parentNoteId: parentA.noteId, type: "image", mime: "image/png", content: "x" });+ withContext(() => image.cloneTo(parentB.noteId));+ expect(image.getParentBranches().length).toBeGreaterThan(1);+ expect(image.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("rejects when autoConversion is requested but there is no imageLink target relation", () => {+ const parent = createNote({ content: "" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });+ expect(image.isEligibleForConversionToAttachment({ autoConversion: true })).toBe(false);+ });++ it("rejects when there are multiple imageLink target relations", () => {+ const parent = createNote({ content: "" });+ const other = createNote({ content: "" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });+ withContext(() => {+ parent.addRelation("imageLink", image.noteId);+ other.addRelation("imageLink", image.noteId);+ });+ expect(image.getTargetRelations().filter((r) => r.name === "imageLink").length).toBe(2);+ expect(image.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("rejects when the referencing note is not the parent", () => {+ const parent = createNote({ content: "" });+ const other = createNote({ content: "" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });+ // The single imageLink comes from a note that is NOT the image's parent.+ withContext(() => other.addRelation("imageLink", image.noteId));+ expect(image.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("rejects when the parent note is not a text note", () => {+ const parent = createNote({ type: "code", mime: "text/plain", content: "x" });+ const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });+ withContext(() => parent.addRelation("imageLink", image.noteId));+ expect(image.isEligibleForConversionToAttachment()).toBe(false);+ });++ it("accepts and converts an eligible image into a parent attachment", () => {+ const { parent, image } = makeConvertibleImage();++ expect(image.isEligibleForConversionToAttachment()).toBe(true);++ const imageNoteId = image.noteId;+ const attachment = withContext(() => image.convertToParentAttachment());++ expect(attachment).not.toBeNull();+ expect(attachment?.ownerId).toBe(parent.noteId);+ // The original image note is deleted as part of the conversion.+ expect(image.isDeleted).toBe(true);+ // The parent content was rewritten to point at the new attachment URL.+ const parentContent = unwrapStringOrBuffer(parent.getContent());+ expect(parentContent).not.toContain(`api/images/${imageNoteId}/`);+ expect(parentContent).toContain(`api/attachments/${attachment?.attachmentId}/image/`);+ });++ it("convertToParentAttachment returns null when the note is not eligible", () => {+ const text = createNote();+ expect(withContext(() => text.convertToParentAttachment())).toBeNull();+ });+ });++ describe("deleteNote (lines 1500-1520)", () => {+ it("soft-deletes the note via its parent branches", () => {+ const note = createNote();+ expect(note.isDeleted).toBe(false);++ withContext(() => note.deleteNote());++ expect(note.isDeleted).toBe(true);+ });++ it("is a no-op when the note is already deleted", () => {+ const note = createNote();+ withContext(() => note.deleteNote());+ expect(note.isDeleted).toBe(true);++ // Second call hits the early `isDeleted` return.+ expect(() => withContext(() => note.deleteNote())).not.toThrow();+ });+ });++ describe("decrypt (lines 1522-1533)", () => {+ it("decrypts a protected note title when a session is available", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });++ // Simulate an encrypted, not-yet-decrypted note.+ const cipher = protectedSessionService.encrypt("secret title");+ expect(typeof cipher).toBe("string");+ note.title = cipher ?? "";+ note.isDecrypted = false;++ note.decrypt();++ expect(note.title).toBe("secret title");+ expect(note.isDecrypted).toBe(true);+ });++ it("swallows decryption errors and leaves the note not decrypted", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ note.isDecrypted = false;++ vi.spyOn(protectedSessionService, "decryptString").mockImplementation(() => {+ throw new Error("kaput");+ });++ expect(() => note.decrypt()).not.toThrow();+ expect(note.isDecrypted).toBe(false);+ });++ it("falls back to an empty title when decryptString yields a falsy value", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ note.isDecrypted = false;++ // decryptString returning null exercises the `|| ""` fallback.+ vi.spyOn(protectedSessionService, "decryptString").mockReturnValue(null);++ note.decrypt();++ expect(note.title).toBe("");+ expect(note.isDecrypted).toBe(true);+ });+ });++ describe("saveRevision / eraseExcessRevisionSnapshots (lines 1551-1620)", () => {+ it("saves a revision and copies note attachments onto it", () => {+ const note = createNote();+ withContext(() =>+ note.saveAttachment({+ role: "image",+ mime: "image/png",+ title: "att-" + counter,+ content: "binary"+ })+ );++ const revision = withContext(() => note.saveRevision({ description: "d", source: "test" as never }));++ expect(revision.revisionId).toBeDefined();+ expect(revision.getAttachments().length).toBe(1);+ });++ it("erases excess revisions beyond the #versioningLimit label", () => {+ const note = createNote();+ withContext(() => note.setLabel("versioningLimit", "2"));++ const eraseSpy = vi.spyOn(eraseService, "eraseRevisions");++ // Create more revisions than the limit.+ withContext(() => note.saveRevision());+ withContext(() => note.saveRevision());+ withContext(() => note.saveRevision());+ withContext(() => note.saveRevision());++ // With a limit of 2, the older revisions beyond the 2 most recent are erased.+ expect(eraseSpy).toHaveBeenCalled();+ const erasedIds = eraseSpy.mock.calls.flatMap((call) => call[0]);+ expect(erasedIds.length).toBeGreaterThan(0);+ // Final count must not exceed the configured limit.+ expect(note.getRevisions().length).toBeLessThanOrEqual(2);+ });++ it("falls back to the option limit when no label is present", () => {+ const note = createNote();+ withContext(() => optionService.setOption("revisionSnapshotNumberLimit", "1"));+ try {+ withContext(() => note.saveRevision());+ withContext(() => note.saveRevision());+ withContext(() => note.saveRevision());++ expect(note.getRevisions().length).toBeLessThanOrEqual(1);+ } finally {+ withContext(() => optionService.setOption("revisionSnapshotNumberLimit", "-1"));+ }+ });+ });++ describe("saveAttachment matchBy (lines 1628-1655)", () => {+ it("matches an existing attachment by title", () => {+ const note = createNote();+ const first = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "by-title-" + counter, content: "a" })+ );+ const second = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "by-title-" + counter, content: "b" }, "title")+ );++ // Same title -> updates the existing attachment instead of creating a new one.+ expect(second.attachmentId).toBe(first.attachmentId);+ expect(note.getAttachments().length).toBe(1);+ expect(unwrapStringOrBuffer(note.getAttachments()[0].getContent())).toBe("b");+ });++ it("matches an existing attachment by attachmentId (default)", () => {+ const note = createNote();+ const first = withContext(() =>+ note.saveAttachment({ role: "file", mime: "text/plain", title: "by-id-" + counter, content: "a" })+ );+ const attachmentId = first.attachmentId ?? "";+ const second = withContext(() =>+ note.saveAttachment({ attachmentId, role: "file", mime: "text/plain", title: "by-id-" + counter, content: "b" })+ );++ expect(second.attachmentId).toBe(attachmentId);+ expect(note.getAttachments().length).toBe(1);+ });++ it("throws for an unsupported matchBy value", () => {+ const note = createNote();+ expect(() =>+ withContext(() =>+ note.saveAttachment(+ { role: "file", mime: "text/plain", title: "bad", content: "x" },+ "bogus" as never+ )+ )+ ).toThrow();+ });+ });++ describe("getPojoToSave protected (lines 1687-1700)", () => {+ it("encrypts the title for a decrypted protected note", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ note.isDecrypted = true;+ note.title = "plain protected title";++ const pojo = note.getPojoToSave();++ expect(typeof pojo.title).toBe("string");+ expect(pojo.title).not.toBe("plain protected title");+ expect(pojo.title).toBeDefined();+ const persistedTitle = pojo.title ?? "";+ expect(protectedSessionService.decryptString(persistedTitle)).toBe("plain protected title");+ });++ it("strips the title when the protected note is not decrypted", () => {+ const note = createNote({ isProtected: true });+ note.isDecrypted = false;++ const pojo = note.getPojoToSave();++ expect("title" in pojo).toBe(false);+ });++ it("strips the title for a decrypted protected note with an empty title", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ note.isDecrypted = true;+ note.title = ""; // falsy title takes the `isDecrypted && pojo.title` short-circuit++ const pojo = note.getPojoToSave();++ expect("title" in pojo).toBe(false);+ });++ it("falls back to undefined when encryption yields a falsy value", () => {+ protectedSessionService.setDataKey(PROTECTED_KEY);+ const note = createNote({ isProtected: true });+ note.isDecrypted = true;+ note.title = "plain protected title";++ // encrypt returning null exercises the `encrypt(...) || undefined` fallback.+ vi.spyOn(protectedSessionService, "encrypt").mockReturnValue(null);++ const pojo = note.getPojoToSave();+ expect(pojo.title).toBeUndefined();+ });+ });++ describe("encodedTitle (line 1738-1739)", () => {+ it("URL-encodes the note title", () => {+ const note = buildNote({ id: `enc-${counter++}`, title: "a b/c?" });+ expect(note.encodedTitle).toBe(encodeURIComponent("a b/c?"));+ });+ });++ describe("shareId (line 1757-1758)", () => {+ it("returns the noteId", () => {+ const note = createNote();+ expect(note.shareId).toBe(note.noteId);+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts b/packages/trilium-core/src/becca/entities/bnote_tree.spec.tsnew file mode 100644index 0000000000..69dc19841d--- /dev/null+++ b/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts@@ -0,0 +1,561 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import becca from "../becca.js";+import attributeService from "../../services/attributes.js";+import cloningService from "../../services/cloning.js";+import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import searchService from "../../services/search/services/search.js";+import { buildNote } from "../../test/becca_easy_mocking.js";+import type BBranch from "./bbranch.js";+import type BNote from "./bnote.js";+import { compareNotePathRecords } from "./bnote.js";++/**+ * Wraps a callback in a CLS context. Entity mutations (createNewNote,+ * createLabel, cloning) require CLS to be initialised.+ */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/**+ * Creates a fresh note under the given parent in the real in-memory DB.+ * Each call uses a unique title since the same fixture DB is shared between+ * the `it()`s in this file.+ */+function createNote(+ parentNoteId: string,+ type: "text" | "search" = "text",+ content = "<p>hello</p>"+): { note: BNote; branch: BBranch } {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId,+ title: `bnote-tree-spec-${counter}`,+ content: type === "search" ? content : content,+ type+ })+ );+}++describe("BNote tree / note-path / subtree methods (real DB)", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe("getBranches (deprecated alias)", () => {+ it("returns the same parent branches as getParentBranches()", () => {+ const { note } = createNote("root");++ // Lines 180-181: deprecated alias returns the raw parentBranches array.+ expect(note.getBranches()).toBe(note.getParentBranches());+ expect(note.getBranches().some((b) => b.parentNoteId === "root")).toBe(true);+ });+ });++ describe("isArchived / areAllNotePathsArchived / hasInheritableArchivedLabel", () => {+ it("reports a directly archived note and resolves the best note path as archived", () => {+ const { note } = createNote("root");+ withContext(() => attributeService.createLabel(note.noteId, "archived", ""));++ expect(note.isArchived).toBe(true);+ // Lines 713-725: best note path record exists and is flagged archived.+ expect(note.areAllNotePathsArchived()).toBe(true);+ });++ it("reports a non-archived note as not having all paths archived", () => {+ const { note } = createNote("root");++ expect(note.isArchived).toBe(false);+ expect(note.areAllNotePathsArchived()).toBe(false);+ });++ it("throws when the note has no available note path", () => {+ // An orphan in-memory note (no parent branch) yields no note paths,+ // so getSortedNotePathRecords()[0] is undefined and the guard throws.+ const orphan = buildNote({ id: `bnote-tree-orphan-${++counter}`, title: "orphan" });+ expect(orphan.getParentBranches().length).toBe(0);+ // Lines 721-723: missing best note path record throws.+ expect(() => orphan.areAllNotePathsArchived()).toThrow();+ });++ it("detects an inheritable archived label and skips a non-inheritable one", () => {+ const inheritable = createNote("root").note;+ withContext(() =>+ attributeService.createAttribute({+ noteId: inheritable.noteId,+ type: "label",+ name: "archived",+ value: "",+ isInheritable: true+ })+ );+ // Lines 730-731: inheritable archived label found.+ expect(inheritable.hasInheritableArchivedLabel()).toBe(true);++ const plain = createNote("root").note;+ withContext(() => attributeService.createLabel(plain.noteId, "archived", ""));+ // Non-inheritable archived label: loop completes without an early return.+ expect(plain.hasInheritableArchivedLabel()).toBe(false);+ });+ });++ describe("sortParents", () => {+ it("orders archived and hidden-completely parents after a normal parent", () => {+ const child = createNote("root").note;++ const normalParent = createNote("root").note;+ const archivedParent = createNote("root").note;+ withContext(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));++ // A parent that is hidden completely: create it under root, clone it+ // into _hidden and drop the root branch so its only path is via _hidden.+ const hiddenParent = createNote("root");+ withContext(() => {+ cloningService.cloneNoteToParentNote(hiddenParent.note.noteId, "_hidden");+ cloningService.ensureNoteIsAbsentFromParent(hiddenParent.note.noteId, "root");+ });+ expect(hiddenParent.note.isHiddenCompletely()).toBe(true);++ withContext(() => {+ cloningService.cloneNoteToParentNote(child.noteId, normalParent.noteId);+ cloningService.cloneNoteToParentNote(child.noteId, archivedParent.noteId);+ cloningService.cloneNoteToParentNote(child.noteId, hiddenParent.note.noteId);+ });++ child.sortParents();++ // Lines 742-746: the comparator pushes archived / hidden-completely+ // parents toward the end. The first parent must not be archived nor+ // hidden-completely.+ const first = child.parents[0];+ expect(first).toBeDefined();+ expect(first?.isArchived).toBe(false);+ expect(first?.isHiddenCompletely()).toBe(false);+ // The archived and hidden parents are still present, just reordered.+ const parentIds = child.parents.map((p) => p.noteId);+ expect(parentIds).toContain(archivedParent.noteId);+ expect(parentIds).toContain(hiddenParent.note.noteId);+ });+ });++ describe("getFlatText", () => {+ it("includes the branch prefix in the flattened text", () => {+ const parent = createNote("root").note;+ const child = createNote("root").note;++ withContext(() =>+ cloningService.cloneNoteToParentNote(child.noteId, parent.noteId, "MYPREFIX")+ );+ child.invalidateThisCache();++ // Lines 780-781: branch prefix contributes to the flat text.+ expect(child.getFlatText()).toContain("myprefix");+ });+ });++ describe("invalidateSubTree", () => {+ it("walks children and template/inherit target relations without infinite recursion", () => {+ const parent = createNote("root").note;+ const child = createNote(parent.noteId).note;+ createNote(child.noteId);++ const template = createNote("root").note;+ const instance = createNote("root").note;+ // instance ~template-> template, so template has a target relation.+ withContext(() =>+ attributeService.createRelation(instance.noteId, "template", template.noteId)+ );++ // Lines 815-838: descends into children and target relations.+ expect(() => parent.invalidateSubTree()).not.toThrow();+ expect(() => template.invalidateSubTree()).not.toThrow();++ // Re-entrancy guard (line 816-817): calling with this note already in+ // the path returns immediately.+ expect(() => parent.invalidateSubTree([parent.noteId])).not.toThrow();+ });+ });++ describe("getSubtreeNotesIncludingTemplated", () => {+ it("descends into children, follows template/inherit targets, dedups, and skips _hidden", () => {+ const subtreeRoot = createNote("root").note;+ const child = createNote(subtreeRoot.noteId).note;+ const grandchild = createNote(child.noteId).note;++ // An instance whose ~template relation targets `child`; walking `child`'s+ // targetRelations therefore reaches `instance`.+ const instance = createNote("root").note;+ withContext(() => attributeService.createRelation(instance.noteId, "template", child.noteId));++ // Walking from subtreeRoot: recurses into child (line 866-867) and+ // grandchild, then follows child's target relation to instance.+ const notes = subtreeRoot.getSubtreeNotesIncludingTemplated();+ expect(notes).toContain(subtreeRoot);+ expect(notes).toContain(child);+ expect(notes).toContain(grandchild);+ // Lines 870-874: template target relation followed to the instance.+ expect(notes).toContain(instance);++ // Dedup (line 860): calling again yields the same set size.+ const again = subtreeRoot.getSubtreeNotesIncludingTemplated();+ expect(again.length).toBe(notes.length);++ // _hidden short-circuit (line 860): _hidden is never included in its+ // own templated subtree.+ const hidden = becca.getNoteOrThrow("_hidden");+ expect(hidden.getSubtreeNotesIncludingTemplated()).not.toContain(hidden);+ });++ it("follows ~inherit targets and ignores non-template/inherit target relations", () => {+ const root = createNote("root").note;+ const viaInherit = createNote("root").note;+ const viaOther = createNote("root").note;+ withContext(() => {+ // Line 871 right operand: name === "inherit".+ attributeService.createRelation(viaInherit.noteId, "inherit", root.noteId);+ // Line 871 false side: a target relation that is neither template nor inherit.+ attributeService.createRelation(viaOther.noteId, "internalLink", root.noteId);+ });++ const notes = root.getSubtreeNotesIncludingTemplated();+ expect(notes).toContain(viaInherit);+ expect(notes).not.toContain(viaOther);+ });+ });++ describe("getSearchResultNotes", () => {+ it("returns [] for a non-search note", () => {+ const { note } = createNote("root");+ // Lines 884-887: early return for non-search notes.+ expect(note.getSearchResultNotes()).toEqual([]);+ });++ it("resolves results for a search note via the search service", () => {+ const target = createNote("root").note;++ const search = createNote("root", "search").note;+ withContext(() =>+ attributeService.createLabel(search.noteId, "searchString", `note.title = "${target.title}"`)+ );++ // Lines 889-896: searchFromNote runs and result ids map to becca notes.+ const results = search.getSearchResultNotes();+ expect(Array.isArray(results)).toBe(true);+ expect(results.some((n) => n.noteId === target.noteId)).toBe(true);+ });++ it("returns [] and logs when the search service throws", () => {+ const search = createNote("root", "search").note;+ vi.spyOn(searchService, "searchFromNote").mockImplementation(() => {+ throw new Error("boom");+ });++ // Lines 893-896: the catch block swallows the error and returns [].+ expect(search.getSearchResultNotes()).toEqual([]);+ });+ });++ describe("getSubtree", () => {+ it("collects the subtree with relationships and dedups clones", () => {+ const root = createNote("root").note;+ const a = createNote(root.noteId).note;+ const b = createNote(root.noteId).note;+ // Clone `a` under `b` so we get two relationships to the same note.+ withContext(() => cloningService.cloneNoteToParentNote(a.noteId, b.noteId));++ const { notes, relationships } = root.getSubtree();+ const noteIds = notes.map((n) => n.noteId);+ expect(noteIds).toContain(root.noteId);+ expect(noteIds).toContain(a.noteId);+ expect(noteIds).toContain(b.noteId);+ // `a` appears once in notes (dedup) but is referenced by two relationships.+ expect(noteIds.filter((id) => id === a.noteId).length).toBe(1);+ expect(+ relationships.filter((r) => r.childNoteId === a.noteId).length+ ).toBeGreaterThanOrEqual(2);+ });++ it("skips the _hidden subtree by default but includes it when requested", () => {+ const root = becca.getNoteOrThrow("root");++ // Default (includeHidden: false) skips _hidden (line 917-920).+ const withoutHidden = root.getSubtree().notes.map((n) => n.noteId);+ expect(withoutHidden).not.toContain("_hidden");++ // includeHidden: true keeps _hidden in the walk.+ const withHidden = root.getSubtree({ includeHidden: true }).notes.map((n) => n.noteId);+ expect(withHidden).toContain("_hidden");+ });++ it("skips archived children when includeArchived is false", () => {+ const root = createNote("root").note;+ const normal = createNote(root.noteId).note;+ const archived = createNote(root.noteId).note;+ withContext(() => attributeService.createLabel(archived.noteId, "archived", ""));++ const noteIds = root+ .getSubtree({ includeArchived: false })+ .notes.map((n) => n.noteId);+ // Lines 933-934: archived child is skipped.+ expect(noteIds).toContain(normal.noteId);+ expect(noteIds).not.toContain(archived.noteId);+ });++ it("resolves a search note's results into the subtree when resolveSearch is set", () => {+ const target = createNote("root").note;++ const parent = createNote("root").note;+ const search = createNote(parent.noteId, "search").note;+ withContext(() =>+ attributeService.createLabel(search.noteId, "searchString", `note.title = "${target.title}"`)+ );++ // Lines 906-910 / 939-942: resolveSearch walks the search results.+ const { notes } = parent.getSubtree({ resolveSearch: true });+ const noteIds = notes.map((n) => n.noteId);+ expect(noteIds).toContain(search.noteId);+ expect(noteIds).toContain(target.noteId);+ });++ it("swallows errors while resolving a search note during subtree walk", () => {+ const parent = createNote("root").note;+ const search = createNote(parent.noteId, "search").note;++ // Force the inner resolveSearchNote try-block to throw (line 912 catch).+ vi.spyOn(search, "getSearchResultNotes").mockImplementation(() => {+ throw new Error("boom");+ });++ const { notes } = parent.getSubtree({ resolveSearch: true });+ const noteIds = notes.map((n) => n.noteId);+ // The walk still completes and includes the parent and the search note.+ expect(noteIds).toContain(parent.noteId);+ expect(noteIds).toContain(search.noteId);+ });+ });++ describe("getAncestors", () => {+ it("dedups a shared ancestor reached via two parents", () => {+ const ancestor = createNote("root").note;+ const left = createNote(ancestor.noteId).note;+ const right = createNote(ancestor.noteId).note;+ const leaf = createNote(left.noteId).note;+ // Clone leaf under `right` too: now leaf reaches `ancestor` via both+ // `left` and `right`.+ withContext(() => cloningService.cloneNoteToParentNote(leaf.noteId, right.noteId));++ const ancestorIds = leaf.getAncestorNoteIds();+ // ancestor must appear exactly once despite two paths.+ expect(ancestorIds.filter((id) => id === ancestor.noteId).length).toBe(1);+ expect(ancestorIds).toContain("root");+ });++ it("skips a direct parent that is also an ancestor of an earlier parent", () => {+ // grandparent -> parent -> leaf, and leaf is ALSO cloned directly under+ // grandparent. So `leaf.parents` contains both `parent` and `grandparent`,+ // and `grandparent` is reached via `parent`'s ancestor walk first. The+ // outer loop then hits the dedup `continue` for `grandparent`.+ const grandparent = createNote("root").note;+ const parent = createNote(grandparent.noteId).note;+ const leaf = createNote(parent.noteId).note;+ withContext(() => cloningService.cloneNoteToParentNote(leaf.noteId, grandparent.noteId));++ const ancestorIds = leaf.getAncestorNoteIds();+ expect(ancestorIds.filter((id) => id === grandparent.noteId).length).toBe(1);+ expect(ancestorIds).toContain(parent.noteId);+ });+ });++ describe("getInheritingNotes", () => {+ it("includes notes whose template/inherit relation targets this note", () => {+ const template = createNote("root").note;+ const instance = createNote("root").note;+ withContext(() =>+ attributeService.createRelation(instance.noteId, "template", template.noteId)+ );++ const inheriting = template.getInheritingNotes();+ expect(inheriting).toContain(template);+ // Line 1069-1074: the templated instance is included.+ expect(inheriting.some((n) => n.noteId === instance.noteId)).toBe(true);+ });++ it("follows ~inherit relations and ignores non-template/inherit target relations", () => {+ const template = createNote("root").note;+ const viaInherit = createNote("root").note;+ const viaOther = createNote("root").note;+ withContext(() => {+ // Line 1071 right operand: name === "inherit".+ attributeService.createRelation(viaInherit.noteId, "inherit", template.noteId);+ // Line 1071 false side: a non-template/inherit target relation is skipped.+ attributeService.createRelation(viaOther.noteId, "internalLink", template.noteId);+ });++ const inheriting = template.getInheritingNotes();+ expect(inheriting.some((n) => n.noteId === viaInherit.noteId)).toBe(true);+ expect(inheriting.some((n) => n.noteId === viaOther.noteId)).toBe(false);+ });+ });++ describe("getSortedNotePathRecords / getBestNotePath", () => {+ it("sorts visible paths before archived and hidden ones", () => {+ const visibleParent = createNote("root").note;+ const archivedParent = createNote("root").note;+ withContext(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));++ const leaf = createNote(visibleParent.noteId).note;+ withContext(() => {+ cloningService.cloneNoteToParentNote(leaf.noteId, archivedParent.noteId);+ cloningService.cloneNoteToParentNote(leaf.noteId, "_hidden");+ });++ const records = leaf.getSortedNotePathRecords();+ expect(records.length).toBeGreaterThanOrEqual(3);++ // Lines 1167-1183: comparators evaluate hoisted / archived / hidden.+ // The best (first) path goes through the visible, non-archived parent.+ const best = leaf.getBestNotePath();+ expect(best).toContain(visibleParent.noteId);+ expect(best).not.toContain("_hidden");++ const bestString = leaf.getBestNotePathString();+ expect(bestString).toBe(best.join("/"));++ // At least one path is flagged hidden and one archived.+ expect(records.some((r) => r.isHidden)).toBe(true);+ expect(records.some((r) => r.isArchived)).toBe(true);+ });++ it("prefers the path inside the hoisted subtree", () => {+ const hoisted = createNote("root").note;+ const outside = createNote("root").note;+ const leaf = createNote(hoisted.noteId).note;+ withContext(() => cloningService.cloneNoteToParentNote(leaf.noteId, outside.noteId));++ // Lines 1169 / 1175-1176: isInHoistedSubTree comparator wins.+ const best = leaf.getBestNotePath(hoisted.noteId);+ expect(best).toContain(hoisted.noteId);+ });++ it("evaluates both arms of the hoisted / archived / hidden comparators", () => {+ // Many diverse paths so the sort comparator is invoked in both orderings,+ // exercising the `? -1 : 1` / `? 1 : -1` arms (lines 1176-1184).+ const hoisted = createNote("root").note;+ const out1 = createNote("root").note;+ const out2 = createNote("root").note;+ const archivedParent = createNote("root").note;+ withContext(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));++ const leaf = createNote(hoisted.noteId).note;+ withContext(() => {+ cloningService.cloneNoteToParentNote(leaf.noteId, out1.noteId);+ cloningService.cloneNoteToParentNote(leaf.noteId, out2.noteId);+ cloningService.cloneNoteToParentNote(leaf.noteId, archivedParent.noteId);+ cloningService.cloneNoteToParentNote(leaf.noteId, "_hidden");+ });++ // Hoisted: one path is inside the hoisted subtree, the rest are outside,+ // so the isInHoistedSubTree comparator returns both -1 and 1.+ const hoistedRecords = leaf.getSortedNotePathRecords(hoisted.noteId);+ expect(hoistedRecords[0].isInHoistedSubTree).toBe(true);+ expect(hoistedRecords.some((r) => !r.isInHoistedSubTree)).toBe(true);++ // Default (root) hoist: all paths are in-hoist, so the comparator falls+ // through to the archived and hidden arms.+ const rootRecords = leaf.getSortedNotePathRecords();+ expect(rootRecords[0].isArchived).toBe(false);+ expect(rootRecords[0].isHidden).toBe(false);+ expect(rootRecords.some((r) => r.isArchived)).toBe(true);+ expect(rootRecords.some((r) => r.isHidden)).toBe(true);+ });+ });++ describe("compareNotePathRecords (pure ordering)", () => {+ const npr = (o: { isInHoistedSubTree?: boolean; isArchived?: boolean; isHidden?: boolean; notePath?: string[] }) => ({+ notePath: o.notePath ?? ["root", "x"],+ isInHoistedSubTree: o.isInHoistedSubTree ?? true,+ isArchived: o.isArchived ?? false,+ isHidden: o.isHidden ?? false+ });++ it("ranks hoisted, then non-archived, then non-hidden, then shorter paths (both arg orders)", () => {+ // isInHoistedSubTree comparator, both arms (lines 1177-1178).+ expect(compareNotePathRecords(npr({ isInHoistedSubTree: true }), npr({ isInHoistedSubTree: false }))).toBeLessThan(0);+ expect(compareNotePathRecords(npr({ isInHoistedSubTree: false }), npr({ isInHoistedSubTree: true }))).toBeGreaterThan(0);++ // isArchived comparator, both arms (lines 1179-1180).+ expect(compareNotePathRecords(npr({ isArchived: true }), npr({ isArchived: false }))).toBeGreaterThan(0);+ expect(compareNotePathRecords(npr({ isArchived: false }), npr({ isArchived: true }))).toBeLessThan(0);++ // isHidden comparator, both arms (lines 1181-1182).+ expect(compareNotePathRecords(npr({ isHidden: true }), npr({ isHidden: false }))).toBeGreaterThan(0);+ expect(compareNotePathRecords(npr({ isHidden: false }), npr({ isHidden: true }))).toBeLessThan(0);++ // All flags equal: fall back to path length (line 1184).+ expect(compareNotePathRecords(npr({ notePath: ["root", "x"] }), npr({ notePath: ["root", "a", "x"] }))).toBeLessThan(0);+ expect(compareNotePathRecords(npr({}), npr({}))).toBe(0);+ });+ });++ describe("getFilteredChildBranches / visible children", () => {+ it("returns child branches and reports folder status", () => {+ const parent = createNote("root").note;+ createNote(parent.noteId);++ // Lines 1722-1735: returns the child branches array.+ const filtered = parent.getFilteredChildBranches();+ expect(filtered.length).toBeGreaterThanOrEqual(1);+ expect(parent.isFolder()).toBe(true);+ });++ it("returns [] and logs when child branches are unexpectedly absent", () => {+ const parent = createNote("root").note;+ // Defensive guard (lines 1725-1727): getChildBranches() always returns+ // an array in practice, so force the falsy case to exercise the guard.+ vi.spyOn(parent, "getChildBranches").mockReturnValue(+ undefined as unknown as ReturnType<BNote["getChildBranches"]>+ );++ expect(parent.getFilteredChildBranches()).toEqual([]);+ });++ it("filters out shareHiddenFromTree and underscore-prefixed notes from visible children", () => {+ const parent = createNote("root").note;+ const visible = createNote(parent.noteId).note;+ const hiddenLabelled = createNote(parent.noteId).note;+ withContext(() =>+ attributeService.createLabel(hiddenLabelled.noteId, "shareHiddenFromTree", "true")+ );++ // Lines 1742-1746: visible branches exclude shareHiddenFromTree notes.+ const visibleNotes = parent.getVisibleChildNotes();+ const visibleIds = visibleNotes.map((n) => n.noteId);+ expect(visibleIds).toContain(visible.noteId);+ expect(visibleIds).not.toContain(hiddenLabelled.noteId);++ // Lines 1749-1754: hasVisibleChildren reflects the filtered set.+ expect(parent.hasVisibleChildren()).toBe(true);++ // The "_"-prefixed branch of the filter (line 1745): every visible+ // child branch under _hidden must be a non-underscore note, since all+ // of _hidden's system children are filtered out.+ const hidden = becca.getNoteOrThrow("_hidden");+ expect(hidden.getVisibleChildBranches().every((b) => !b.noteId.startsWith("_"))).toBe(true);++ // A note whose only child is underscore-prefixed has no visible+ // children: clone a system "_"-note into a fresh parent.+ const emptyParent = createNote("root").note;+ withContext(() =>+ cloningService.cloneNoteToParentNote("_globalNoteMap", emptyParent.noteId)+ );+ expect(emptyParent.getChildNotes().length).toBeGreaterThanOrEqual(1);+ expect(emptyParent.getVisibleChildBranches().length).toBe(0);+ expect(emptyParent.hasVisibleChildren()).toBe(false);+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/brecent_note.spec.ts b/packages/trilium-core/src/becca/entities/brecent_note.spec.tsnew file mode 100644index 0000000000..4d3160688f--- /dev/null+++ b/packages/trilium-core/src/becca/entities/brecent_note.spec.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";++import BRecentNote from "./brecent_note.js";++describe("BRecentNote static metadata", () => {+ it("exposes entityName, primaryKeyName and hashedProperties", () => {+ expect(BRecentNote.entityName).toBe("recent_notes");+ expect(BRecentNote.primaryKeyName).toBe("noteId");+ expect(BRecentNote.hashedProperties).toContain("noteId");+ expect(BRecentNote.hashedProperties).toContain("notePath");+ });+});++describe("BRecentNote instance", () => {+ it("populates fields from the row and keeps the supplied utcDateCreated", () => {+ const recentNote = new BRecentNote({+ noteId: "brecent-spec-1",+ notePath: "root/brecent-spec-1",+ utcDateCreated: "2025-06-27 14:10:39.688+0300"+ });++ expect(recentNote.noteId).toBe("brecent-spec-1");+ expect(recentNote.notePath).toBe("root/brecent-spec-1");+ expect(recentNote.utcDateCreated).toBe("2025-06-27 14:10:39.688+0300");+ });++ it("defaults utcDateCreated to the current time when empty", () => {+ const recentNote = new BRecentNote({+ noteId: "brecent-spec-2",+ notePath: "root/brecent-spec-2",+ utcDateCreated: ""+ });++ expect(typeof recentNote.utcDateCreated).toBe("string");+ expect(recentNote.utcDateCreated.length).toBeGreaterThan(0);+ });++ it("getPojo returns the expected shape", () => {+ const recentNote = new BRecentNote({+ noteId: "brecent-spec-3",+ notePath: "root/brecent-spec-3",+ utcDateCreated: "2025-06-27 14:10:39.688+0300"+ });++ expect(recentNote.getPojo()).toEqual({+ noteId: "brecent-spec-3",+ notePath: "root/brecent-spec-3",+ utcDateCreated: "2025-06-27 14:10:39.688+0300"+ });+ });+});diff --git a/packages/trilium-core/src/becca/entities/brevision.spec.ts b/packages/trilium-core/src/becca/entities/brevision.spec.tsindex 1181c956c7..616918c3b6 100644--- a/packages/trilium-core/src/becca/entities/brevision.spec.ts+++ b/packages/trilium-core/src/becca/entities/brevision.spec.ts@@ -1,6 +1,32 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";+import becca from "../becca.js";+import type BNote from "./bnote.js";import BRevision from "./brevision.js";+import { getContext } from "../../services/context.js";+import noteService from "../../services/notes.js";+import protectedSession from "../../services/protected_session.js";+import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";++/** Wraps mutations in a CLS context, required for entity saves/content writes. */+function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++let counter = 0;++/** Creates a fresh text note in the real in-memory DB with a unique title. */+function createNote(content = "<p>hello</p>"): BNote {+ counter++;+ return withContext(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: `brevision-spec-${counter}`,+ content,+ type: "text"+ }).note+ );+}describe("Revision", () => {it("handles note with empty title properly", () => {@@ -22,3 +48,321 @@ describe("Revision", () => {expect(pojo.title).toBeDefined();});});++describe("Revision constructor (protected)", () => {+ afterEach(() => {+ protectedSession.resetDataKey();+ });++ it("falls back to a placeholder title for a protected revision when no session is available", () => {+ // isProtected with titleDecrypted=false and no protected session -> placeholder.+ const revision = new BRevision({+ revisionId: "protNoSession1",+ noteId: "noteProt1",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: "ciphertext-title",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ expect(revision.isProtected).toBe(true);+ expect(revision.title).toBe("[protected]");+ });++ it("decrypts the title for a protected revision when a session is available", () => {+ protectedSession.setDataKey(encodeUtf8("0123456789abcdef"));+ const cipher = protectedSession.encrypt("secret title");+ expect(typeof cipher).toBe("string");++ const revision = new BRevision({+ revisionId: "protWithSession1",+ noteId: "noteProt2",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: cipher ?? "",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ expect(revision.title).toBe("secret title");+ });++ it("reports content availability based on revisionId, protection and session", () => {+ // New revision (no revisionId) -> always available.+ const fresh = new BRevision(+ {+ revisionId: undefined,+ noteId: "noteAvail0",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: "x",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ },+ true+ );+ expect(fresh.isContentAvailable()).toBe(true);++ // Persisted, unprotected -> available.+ const unprotected = new BRevision({+ revisionId: "availUnprot1",+ noteId: "noteAvail1",+ type: "text",+ mime: "text/html",+ isProtected: false,+ title: "x",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });+ expect(unprotected.isContentAvailable()).toBe(true);++ // Persisted, protected, no session -> reaches the session check and is unavailable.+ const protectedRev = new BRevision(+ {+ revisionId: "availProt1",+ noteId: "noteAvail2",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: "x",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ },+ true+ );+ expect(protectedRev.isContentAvailable()).toBe(false);++ // Same revision once a session is available -> the session check makes it available.+ protectedSession.setDataKey(encodeUtf8("0123456789abcdef"));+ expect(protectedRev.isContentAvailable()).toBe(true);+ });++ it("does not touch the title when titleDecrypted is passed for a protected revision", () => {+ const revision = new BRevision(+ {+ revisionId: "protAlreadyDecrypted1",+ noteId: "noteProt3",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: "already plain",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ },+ true+ );++ expect(revision.title).toBe("already plain");+ });+});++describe("Revision JSON content", () => {+ function saveRevisionWithContent(content: string): BRevision {+ const note = createNote();+ const revision = withContext(() => {+ const rev = note.saveRevision();+ rev.setContent(content, { forceSave: true });+ return rev;+ });+ return revision;+ }++ it("getJsonContent parses valid JSON into an object", () => {+ const revision = saveRevisionWithContent(`{"a":1,"b":"two"}`);+ expect(revision.getJsonContent()).toEqual({ a: 1, b: "two" });+ expect(revision.getJsonContentSafely()).toEqual({ a: 1, b: "two" });+ });++ it("getJsonContent returns null for empty / whitespace content", () => {+ const blank = saveRevisionWithContent(" ");+ expect(blank.getJsonContent()).toBeNull();+ expect(blank.getJsonContentSafely()).toBeNull();++ const empty = saveRevisionWithContent("");+ expect(empty.getJsonContent()).toBeNull();+ });++ it("getJsonContent throws on invalid JSON while getJsonContentSafely returns null", () => {+ const revision = saveRevisionWithContent("not valid json {");+ expect(() => revision.getJsonContent()).toThrow();+ expect(revision.getJsonContentSafely()).toBeNull();+ });+});++describe("Revision attachments", () => {+ let revision: BRevision;++ function setup(): BRevision {+ const note = createNote();+ return withContext(() => {+ note.saveAttachment({+ attachmentId: undefined,+ role: "image",+ mime: "image/png",+ title: "my-attachment",+ content: "binary-content",+ position: 10+ });+ // saveRevision copies note attachments onto the revision (ownerId = revisionId).+ return note.saveRevision();+ });+ }++ it("exposes the copied attachment through the revision queries", () => {+ revision = setup();++ const attachments = revision.getAttachments();+ expect(attachments.length).toBe(1);+ const attachment = attachments[0];+ expect(attachment).toBeDefined();+ expect(attachment.ownerId).toBe(revision.revisionId);+ expect(attachment.role).toBe("image");+ expect(attachment.title).toBe("my-attachment");++ // getAttachmentById without content length.+ const attachmentId = attachment.attachmentId ?? "";+ const byId = revision.getAttachmentById(attachmentId);+ expect(byId).toBeDefined();+ expect(byId?.attachmentId).toBe(attachmentId);+ expect(byId?.contentLength).toBeUndefined();++ // getAttachmentById with content length.+ const byIdWithLength = revision.getAttachmentById(attachmentId, { includeContentLength: true });+ expect(byIdWithLength).toBeDefined();+ expect(typeof byIdWithLength?.contentLength).toBe("number");+ expect(byIdWithLength?.contentLength).toBe("binary-content".length);++ // getAttachmentsByRole.+ const byRole = revision.getAttachmentsByRole("image");+ expect(byRole.length).toBe(1);+ expect(byRole[0].attachmentId).toBe(attachmentId);+ expect(revision.getAttachmentsByRole("nonexistent-role").length).toBe(0);++ // getAttachmentByTitle.+ const byTitle = revision.getAttachmentByTitle("my-attachment");+ expect(byTitle).toBeDefined();+ expect(byTitle.attachmentId).toBe(attachmentId);+ expect(unwrapStringOrBuffer(byTitle.getContent())).toBe("binary-content");+ expect(revision.getAttachmentByTitle("nope")).toBeUndefined();+ });++ it("returns undefined for an unknown attachment id", () => {+ revision = setup();+ expect(revision.getAttachmentById("does-not-exist")).toBeUndefined();+ expect(revision.getAttachmentById("does-not-exist", { includeContentLength: true })).toBeUndefined();+ });+});++describe("Revision getNote", () => {+ it("resolves the owning note from becca", () => {+ const note = createNote();+ const revision = withContext(() => note.saveRevision());++ expect(revision.getNote()).toBe(note);+ });+});++describe("Revision eraseRevision", () => {+ it("hard-deletes the revision so it is no longer retrievable", () => {+ const note = createNote();+ const revision = withContext(() => note.saveRevision());+ const revisionId = revision.revisionId ?? "";+ expect(revisionId).not.toBe("");+ expect(becca.getRevision(revisionId)).not.toBeNull();++ withContext(() => revision.eraseRevision());++ expect(becca.getRevision(revisionId)).toBeNull();+ });+});++describe("Revision getPojoToSave (protected)", () => {+ afterEach(() => {+ protectedSession.resetDataKey();+ });++ function makeProtectedRevision(): BRevision {+ return new BRevision(+ {+ revisionId: "pojoToSaveProt1",+ noteId: "notePojo1",+ type: "text",+ mime: "text/html",+ isProtected: true,+ title: "plain title",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ },+ true+ );+ }++ it("encrypts the title and strips content when a protected session is available", () => {+ protectedSession.setDataKey(encodeUtf8("0123456789abcdef"));+ const revision = makeProtectedRevision();+ revision.content = "some content";+ revision.contentLength = 12;++ const pojo = revision.getPojoToSave();++ expect("content" in pojo).toBe(false);+ expect("contentLength" in pojo).toBe(false);+ expect(typeof pojo.title).toBe("string");+ expect(pojo.title).not.toBe("");+ // The persisted title is the ciphertext, not the plaintext.+ expect(pojo.title).not.toBe("plain title");+ expect(protectedSession.decryptString(pojo.title)).toBe("plain title");+ });++ it("clears the title when no protected session is available", () => {+ const revision = makeProtectedRevision();+ const pojo = revision.getPojoToSave();+ expect(pojo.title).toBe("");+ });++ it("falls back to an empty title when encryption yields no ciphertext", () => {+ protectedSession.setDataKey(encodeUtf8("0123456789abcdef"));+ const revision = makeProtectedRevision();+ // A null title makes protectedSession.encrypt return null, exercising the `?? ""` fallback.+ revision.title = null as unknown as string;++ const pojo = revision.getPojoToSave();+ expect(pojo.title).toBe("");+ });++ it("leaves the title intact for an unprotected revision", () => {+ const revision = new BRevision({+ revisionId: "pojoUnprotected1",+ noteId: "notePojo2",+ type: "text",+ mime: "text/html",+ isProtected: false,+ title: "visible title",+ blobId: "",+ dateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateCreated: "2025-06-27 14:10:39.688+0300",+ utcDateModified: "2025-06-27 14:10:39.688+0300"+ });++ const pojo = revision.getPojoToSave();+ expect(pojo.title).toBe("visible title");+ });+});diff --git a/packages/trilium-core/src/becca/entity_constructor.spec.ts b/packages/trilium-core/src/becca/entity_constructor.spec.tsnew file mode 100644index 0000000000..8bcd2cf65e--- /dev/null+++ b/packages/trilium-core/src/becca/entity_constructor.spec.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest";++import BNote from "./entities/bnote.js";+import BRevision from "./entities/brevision.js";+import entityConstructor from "./entity_constructor.js";++describe("entity_constructor.getEntityFromEntityName", () => {+ it("returns the matching entity class for known table names", () => {+ expect(entityConstructor.getEntityFromEntityName("notes")).toBe(BNote);+ expect(entityConstructor.getEntityFromEntityName("revisions")).toBe(BRevision);+ });++ it("throws for an unknown table name", () => {+ expect(() =>+ entityConstructor.getEntityFromEntityName("nonexistent" as "notes")+ ).toThrow();+ });+});diff --git a/packages/trilium-core/src/becca/similarity.spec.ts b/packages/trilium-core/src/becca/similarity.spec.tsindex f7f9df909c..74ca70cb43 100644--- a/packages/trilium-core/src/becca/similarity.spec.ts+++ b/packages/trilium-core/src/becca/similarity.spec.ts@@ -1,8 +1,39 @@import { trimIndentation } from "@triliumnext/commons";import { describe, expect, it } from "vitest";+import becca from "./becca.js";import { buildNote } from "../test/becca_easy_mocking";-import { buildRewardMap } from "./similarity";+import BAttribute from "./entities/battribute.js";+import BBranch from "./entities/bbranch.js";+import { randomString } from "../services/utils/index.js";+import similarity, { buildRewardMap } from "./similarity";++/**+ * Builds an in-memory note and clones it directly under "root" so that it has a+ * real best note path and is not considered hidden by findSimilarNotes.+ */+function buildRootNote(noteDef: Parameters<typeof buildNote>[0], utcDateCreated?: string) {+ // Text notes have their content parsed in buildRewardMap, so provide some so+ // the in-memory note never falls back to a DB content lookup.+ const withContent = noteDef.content === undefined && (noteDef.type ?? "text") === "text"+ ? { ...noteDef, content: "<p>placeholder body</p>" }+ : noteDef;+ const note = buildNote(withContent);++ new BBranch({+ branchId: `root_${note.noteId}`,+ noteId: note.noteId,+ parentNoteId: "root",+ prefix: null,+ notePosition: 10+ });++ if (utcDateCreated) {+ note.utcDateCreated = utcDateCreated;+ }++ return note;+}describe("buildRewardMap", () => {it("calculates heading rewards", () => {@@ -19,4 +50,355 @@ describe("buildRewardMap", () => {expect(typeof map.get(key)).toStrictEqual("number");}});++ it("rewards decrypted ancestor titles and branch prefixes", () => {+ const grandparentId = randomString(12);+ const parentId = randomString(12);+ const childId = randomString(12);++ buildNote({+ id: grandparentId,+ title: "Geography",+ content: "<p>geo</p>",+ children: [+ {+ id: parentId,+ title: "Europe",+ content: "<p>eu</p>",+ children: [ { id: childId, title: "Romania", content: "<p>ro</p>" } ]+ }+ ]+ });++ // Give the parent's branch (parent -> grandparent) a prefix so the+ // ancestor branch-prefix path is exercised.+ const parentBranch = becca.getNote(parentId)?.getParentBranches()[0];+ expect(parentBranch).toBeDefined();+ if (parentBranch) {+ parentBranch.prefix = "Continent";+ }++ const child = becca.getNoteOrThrow(childId);+ const map = buildRewardMap(child);++ // Ancestor title words appear with a (small) reward.+ expect(typeof map.get("geography")).toStrictEqual("number");+ expect(typeof map.get("europe")).toStrictEqual("number");+ // The ancestor branch prefix word appears too.+ expect(typeof map.get("continent")).toStrictEqual("number");+ });++ it("skips undecrypted ancestors and blacklisted/ignored-name attributes", () => {+ const parentId = randomString(12);+ const childId = randomString(12);++ buildNote({+ id: parentId,+ title: "Secret parent",+ content: "<p>p</p>",+ children: [ { id: childId, title: "the visible child", content: "<p>c</p>" } ]+ });++ // Protected (not decrypted) ancestor -> its title is not rewarded.+ const parent = becca.getNoteOrThrow(parentId);+ parent.isDecrypted = false;++ const child = becca.getNoteOrThrow(childId);+ // archived is in IGNORED_ATTR_NAMES: its name is not rewarded.+ new BAttribute({+ attributeId: randomString(12),+ noteId: childId,+ type: "label",+ name: "archived",+ value: "",+ isInheritable: false+ });++ const map = buildRewardMap(child);++ // The blacklisted word "the" collapses to "" and yields no reward entry.+ expect(map.get("the")).toBeUndefined();+ // The non-blacklisted title word is present.+ expect(typeof map.get("visible")).toStrictEqual("number");+ // The undecrypted ancestor's title word is absent.+ expect(map.get("secret")).toBeUndefined();+ // The ignored attribute name "archived" yields no reward entry.+ expect(map.get("archived")).toBeUndefined();+ });++ it("applies the inherited-attribute penalty for attributes owned by an ancestor", () => {+ const parentId = randomString(12);+ const childId = randomString(12);++ buildNote({+ id: parentId,+ title: "Holder",+ content: "<p>p</p>",+ children: [ { id: childId, title: "Inheritor child", content: "<p>c</p>" } ]+ });++ // Inheritable label on the parent shows up in the child's getAttributes()+ // with the parent's noteId, exercising the inherited (0.5) reward branch.+ new BAttribute({+ attributeId: randomString(12),+ noteId: parentId,+ type: "label",+ name: "category",+ value: "fiction",+ isInheritable: true+ });++ const child = becca.getNoteOrThrow(childId);+ const inherited = child.getAttributes().find((a) => a.name === "category");+ expect(inherited).toBeDefined();+ expect(inherited?.noteId).toStrictEqual(parentId);++ const map = buildRewardMap(child);+ expect(typeof map.get("category")).toStrictEqual("number");+ expect(typeof map.get("fiction")).toStrictEqual("number");+ });++ it("filters URL noise out of label values", () => {+ const note = buildNote({+ title: "Bookmark sample",+ content: "<p>body</p>",+ "#homepage": "https://www.example.com/foobar"+ });++ const map = buildRewardMap(note);++ // The scheme and the ".com" TLD are stripped by filterUrlValue, but the+ // meaningful path/host words remain.+ expect(typeof map.get("foobar")).toStrictEqual("number");+ expect(typeof map.get("example")).toStrictEqual("number");+ // The ".com" TLD token is removed, so no standalone "com" reward exists.+ expect(map.get("com")).toBeUndefined();+ });++ it("skips structural/ignored attributes and halves the cliptype reward", () => {+ const note = buildNote({+ title: "Clipped article",+ content: "<p>body</p>",+ "#cliptype": "html",+ "#datenote": "2020-01-01",+ "#child:foo": "bar",+ "~relation:baz": "qux"+ });++ const map = buildRewardMap(note);++ // cliptype name is rewarded (the value "html" too), value reward halved internally.+ expect(typeof map.get("cliptype")).toStrictEqual("number");+ expect(typeof map.get("html")).toStrictEqual("number");+ // datenote is in IGNORED_ATTRS -> contributes nothing.+ expect(map.get("datenote")).toBeUndefined();+ // prefixed attribute names are skipped entirely.+ expect(map.get("foo")).toBeUndefined();+ });++ it("rewards a trimmed non-text mime, including the -x prefix variant", () => {+ const pdfNote = buildNote({ title: "Doc", type: "file", mime: "application/pdf" });+ const pdfMap = buildRewardMap(pdfNote);+ expect(typeof pdfMap.get("pdf")).toStrictEqual("number");++ // chunks[1] starting with "-x" gets the leading "-x" stripped.+ const xNote = buildNote({ title: "Weird", type: "file", mime: "application/-xcustom" });+ const xMap = buildRewardMap(xNote);+ expect(typeof xMap.get("custom")).toStrictEqual("number");+ expect(xMap.get("xcustom")).toBeUndefined();+ });++ it("returns early for text notes whose content is not a string", () => {+ const note = buildNote({ title: "Binary backed", type: "text" });+ // Simulate WASM/binary content: getContent yields a non-string.+ note.getContent = () => new Uint8Array([ 1, 2, 3 ]) as unknown as string;++ const map = buildRewardMap(note);+ // Title still rewarded; no throw despite the non-string content.+ expect(typeof map.get("binary")).toStrictEqual("number");+ });+});++describe("findSimilarNotes", () => {+ it("returns an empty array when the base note is missing", async () => {+ const result = await similarity.findSimilarNotes("does-not-exist-id");+ expect(result).toEqual([]);+ });++ it("returns an empty array when the base note has no utcDateCreated", async () => {+ const note = buildRootNote({ title: "No date note zubzub" });+ note.utcDateCreated = "";++ const result = await similarity.findSimilarNotes(note.noteId);+ expect(result).toEqual([]);+ });++ it("wraps a failure to build date limits in a descriptive error", async () => {+ const note = buildRootNote({ title: "Bad date note kraznok" });+ // Truthy but unparseable -> passes the empty guard, fails buildDateLimits.+ note.utcDateCreated = "definitely-not-a-date";++ await expect(similarity.findSimilarNotes(note.noteId)).rejects.toThrow();+ });++ it("yields the event loop past 1000 candidates and caps results at 200", async () => {+ const word = "bulkclusterword";+ const base = buildRootNote({ title: `${word} aa bb cc`, type: "text" });++ // Build well over 1000 high-scoring siblings so the loop both crosses the+ // 1000-candidate setImmediate yield boundary and overflows the 200 cap.+ for (let i = 0; i < 1100; i++) {+ buildRootNote({ title: `${word} aa bb cc ${i}`, type: "code", mime: "text/plain" });+ }++ const result = await similarity.findSimilarNotes(base.noteId);+ const matches = result ?? [];+ expect(matches.length).toBe(200);+ });++ it("finds similar notes sharing distinctive title words", async () => {+ const word = "quibbleflux";+ const base = buildRootNote({+ title: `${word} alpha beta gamma`,+ type: "text"+ });+ // Several siblings sharing the distinctive word should score highly.+ buildRootNote({ title: `${word} alpha beta delta`, type: "text" });+ buildRootNote({ title: `${word} alpha beta epsilon`, type: "text" });++ const result = await similarity.findSimilarNotes(base.noteId);++ expect(Array.isArray(result)).toBe(true);+ const matches = result ?? [];+ expect(matches.length).toBeGreaterThanOrEqual(2);+ // Each result has the expected shape and the base note is excluded.+ for (const r of matches) {+ expect(typeof r.score).toStrictEqual("number");+ expect(Array.isArray(r.notePath)).toBe(true);+ expect(typeof r.noteId).toStrictEqual("string");+ expect(r.noteId).not.toStrictEqual(base.noteId);+ }+ // Sorted descending by score.+ for (let i = 1; i < matches.length; i++) {+ expect(matches[i - 1].score).toBeGreaterThanOrEqual(matches[i].score);+ }+ });++ it("handles candidate attributes: http values, ignored/prefixed names, and a corrupted value", async () => {+ const word = "marmaladeon";+ const base = buildRootNote({ title: `${word} one two three`, type: "text" });++ // Candidate whose label value is a URL (exercises the http branch).+ buildRootNote({+ title: `${word} one two four`,+ type: "text",+ "#source": "https://www.example.org/marmaladeon-article",+ "#datenote": "2020-01-01",+ "#child:nested": "skipme"+ });++ // Candidate with a corrupted (non-string) attribute value -> the+ // defensive "!value.startsWith" branch logs and continues. A number has+ // no startsWith method (whereas null would throw before the check).+ const corrupted = buildRootNote({+ title: `${word} one two five`,+ type: "text",+ "#broken": "placeholder"+ });+ const brokenAttr = corrupted.getOwnedAttributes().find((a) => a.name === "broken");+ expect(brokenAttr).toBeDefined();+ if (brokenAttr) {+ (brokenAttr as { value: unknown }).value = 42;+ }++ const result = await similarity.findSimilarNotes(base.noteId);+ expect(Array.isArray(result)).toBe(true);++ // Restore a valid string value so this leaked note does not crash later+ // findSimilarNotes runs in this shared-becca file.+ if (brokenAttr) {+ brokenAttr.value = "placeholder";+ }+ });++ it("applies date-window bonuses based on creation time proximity", async () => {+ // Base created at a fixed instant. Mirror utcDateTimeStr's exact format+ // ("YYYY-MM-DD HH:MM:SS.sssZ", UTC) so the lexical comparisons in+ // findSimilarNotes line up with the computed date limits.+ const baseTs = Date.parse("2021-06-01T12:00:00.000Z");+ const fmt = (ms: number) => new Date(ms).toISOString().replace("T", " ");++ const base = buildRootNote(+ { title: "chronobase signalword", type: "text" },+ fmt(baseTs)+ );++ // Within the +/-1h window but outside the +/-5s excluded window -> +1 bonus.+ buildRootNote(+ { title: "chronobase signalword near", type: "text" },+ fmt(baseTs + 30 * 60 * 1000)+ );++ // Same calendar day but outside the hour window -> +0.5 bonus.+ buildRootNote(+ { title: "chronobase signalword sameday", type: "text" },+ fmt(baseTs + 6 * 60 * 60 * 1000)+ );++ // Within the excluded +/-5s window -> no date bonus (likely an import).+ buildRootNote(+ { title: "chronobase signalword imported", type: "text" },+ fmt(baseTs + 2 * 1000)+ );++ const result = await similarity.findSimilarNotes(base.noteId);+ expect(Array.isArray(result)).toBe(true);+ });++ it("skips candidates connected to the base by an includenotelink relation", async () => {+ const word = "interlinkword";+ const base = buildRootNote({ title: `${word} foo bar baz`, type: "text" });+ const linked = buildRootNote({ title: `${word} foo bar baz`, type: "text" });++ // The candidate has an includenotelink relation pointing at the base, so+ // hasConnectingRelation matches and the candidate is excluded.+ new BAttribute({+ attributeId: randomString(12),+ noteId: linked.noteId,+ type: "relation",+ name: "includenotelink",+ value: base.noteId,+ isInheritable: false+ });++ const result = await similarity.findSimilarNotes(base.noteId);+ const matches = result ?? [];+ expect(matches.some((r) => r.noteId === linked.noteId)).toBe(false);+ });++ it("penalizes archived candidates that otherwise score highly", async () => {+ const word = "vortexalia";+ const base = buildRootNote({ title: `${word} red green blue`, type: "text" });+ buildRootNote({+ title: `${word} red green blue`,+ type: "text",+ "#archived": ""+ });++ const result = await similarity.findSimilarNotes(base.noteId);+ const matches = result ?? [];+ expect(matches.length).toBeGreaterThanOrEqual(1);+ });++ it("returns undefined when a high-scoring candidate has no resolvable note path", async () => {+ const word = "phantompathword";+ const base = buildRootNote({ title: `${word} sun moon star`, type: "text" });+ const orphan = buildRootNote({ title: `${word} sun moon star`, type: "text" });++ // Force the (hoisting) edge case where a scoring candidate yields no path.+ orphan.getBestNotePath = () => undefined as unknown as string[];++ const result = await similarity.findSimilarNotes(base.noteId);+ expect(result).toBeUndefined();+ });});diff --git a/packages/trilium-core/src/becca/similarity.ts b/packages/trilium-core/src/becca/similarity.tsindex 28d59d0e32..75a516b4ea 100644--- a/packages/trilium-core/src/becca/similarity.ts+++ b/packages/trilium-core/src/becca/similarity.ts@@ -289,11 +289,14 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefinfor (const word of splitToWords(text)) {const reward = rewardMap.get(word) * factor * lengthPenalization || 0;+ /* v8 ignore start */+ // DEBUG-only diagnostics, displayRewards is only set true inside the permanently-false DEBUG blockif (displayRewards && reward > 0) {console.log(`Reward ${Math.round(reward * 10) / 10} for word: ${word}`);console.log(`Before: ${counter}, add ${reward}, res: ${counter + reward}`);console.log(`${rewardMap.get(word)} * ${factor} * ${lengthPenalization}`);}+ /* v8 ignore stop */counter += reward;}@@ -311,9 +314,12 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefinfor (const parentNote of note.parents) {if (!ancestorNoteIds.has(parentNote.noteId)) {+ /* v8 ignore start */+ // DEBUG-only diagnostics, displayRewards is permanently false outside the dead DEBUG blockif (displayRewards) {console.log("Considering", parentNote.title);}+ /* v8 ignore stop */if (parentNote.isDecrypted) {score += gatherRewards(parentNote.title, 0.3);@@ -372,9 +378,12 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefin}if (candidateNote.type === baseNote.type) {+ /* v8 ignore start */+ // DEBUG-only diagnostics, displayRewards is permanently false outside the dead DEBUG blockif (displayRewards) {console.log("Adding reward for same note type");}+ /* v8 ignore stop */score += 0.2;}@@ -390,15 +399,21 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefinif (utcDateCreated < dateLimits.minExcludedDate || utcDateCreated > dateLimits.maxExcludedDate) {if (utcDateCreated >= dateLimits.minDate && utcDateCreated <= dateLimits.maxDate) {+ /* v8 ignore start */+ // DEBUG-only diagnostics, displayRewards is permanently false outside the dead DEBUG blockif (displayRewards) {console.log("Adding reward for very similar date of creation");}+ /* v8 ignore stop */score += 1;} else if (utcDateCreated.substr(0, 10) === dateLimits.minDate.substr(0, 10) || utcDateCreated.substr(0, 10) === dateLimits.maxDate.substr(0, 10)) {+ /* v8 ignore start */+ // DEBUG-only diagnostics, displayRewards is permanently false outside the dead DEBUG blockif (displayRewards) {console.log("Adding reward for same day of creation");}+ /* v8 ignore stop */// smaller bonus when outside of the window but within the same datescore += 0.5;@@ -443,6 +458,8 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefinresults.sort((a, b) => (a.score > b.score ? -1 : 1));+ /* v8 ignore start */+ // DEBUG-only diagnostics block, DEBUG is permanently falseif (DEBUG) {console.log("REWARD MAP", rewardMap);@@ -458,6 +475,7 @@ async function findSimilarNotes(noteId: string): Promise<SimilarNote[] | undefin}}}+ /* v8 ignore stop */return results.length > 200 ? results.slice(0, 200) : results;}