Skip to content

Build your personal knowledge base with Trilium Notes

test(core): get rid of withContext

Elian Doran0807899f08cd
diff --git a/.claude/skills/writing-unit-tests/server-and-core.md b/.claude/skills/writing-unit-tests/server-and-core.md
index 9d5fda58ea..133d17c0c1 100644
--- a/.claude/skills/writing-unit-tests/server-and-core.md
+++ b/.claude/skills/writing-unit-tests/server-and-core.md
@@ -112,7 +112,10 @@ describe("createNewNote (real DB)", () => {
});
```
-**Mutations require CLS:** wrap `setContent`/`createNewNote`/etc. in `cls.init(() => ...)`. Supertest route tests get CLS for free; direct service calls do not.
+**Mutations require CLS** — wrap `setContent`/`createNewNote`/`BAttribute.save()`/etc. (anything that emits an entity change or opens a transaction) in a CLS context, or they throw. Supertest route tests and `CoreApiTester` (Pattern 0) get CLS for free; direct service/entity calls do not.
+- **In `apps/server` specs**, use `cls.init(() => ...)` from `@triliumnext/core` (as above).
+- **In `packages/trilium-core/src/**` specs** (which run cross-runtime and must NOT self-import `@triliumnext/core`), import `getContext` from a relative `context.js` and call it inline: `import { getContext } from "../services/context.js";` then `getContext().init(() => ...)`, or `await getContext().init(async () => { ... })` for async work (`init` returns the callback's promise, so awaiting and throwing propagate normally). See `import/enex.spec.ts` / `import/single.spec.ts` for the inline async form.
+- **Do NOT wrap this in a per-file helper.** A local `withContext(fn)` that just does `return getContext().init(fn)` is a pointless duplicate of the existing `getContext().init` / `cls.init` export — and because specs get written file-by-file, that wrapper once metastasised into 35 identical copies before being removed. Call `getContext().init(...)` / `cls.init(...)` directly at the call site.
## Pattern 4 — pure service, zero infra
diff --git a/packages/trilium-core/src/becca/becca-interface.spec.ts b/packages/trilium-core/src/becca/becca-interface.spec.ts
index ddb2c1541d..abcddd7b67 100644
--- a/packages/trilium-core/src/becca/becca-interface.spec.ts
+++ b/packages/trilium-core/src/becca/becca-interface.spec.ts
@@ -6,14 +6,6 @@ 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
@@ -21,7 +13,7 @@ function withContext<T>(fn: () => T): T {
*/
function createNote(parentNoteId: string, title?: string) {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: title ?? `becca-interface-spec-${counter}`,
@@ -78,7 +70,7 @@ describe("Becca interface (real DB)", () => {
it("returns the attribute when present", () => {
const { note } = createNote("root");
- const attr = withContext(() => note.addLabel("becca-interface-label"));
+ const attr = getContext().init(() => note.addLabel("becca-interface-label"));
const fetched = becca.getAttributeOrThrow(attr.attributeId);
expect(fetched.attributeId).toBe(attr.attributeId);
});
@@ -87,7 +79,7 @@ describe("Becca interface (real DB)", () => {
describe("getAttachments / getBlob", () => {
it("fetches existing attachments by id via getManyRows", () => {
const { note } = createNote("root");
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -110,7 +102,7 @@ describe("Becca interface (real DB)", () => {
it("getBlob returns a blob for a saved attachment's blobId", () => {
const { note } = createNote("root");
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -153,7 +145,7 @@ describe("Becca interface (real DB)", () => {
it("routes 'attachments' to getAttachment", () => {
const { note } = createNote("root");
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
diff --git a/packages/trilium-core/src/becca/becca_loader.spec.ts b/packages/trilium-core/src/becca/becca_loader.spec.ts
index f664379c7b..dc055cdc9e 100644
--- a/packages/trilium-core/src/becca/becca_loader.spec.ts
+++ b/packages/trilium-core/src/becca/becca_loader.spec.ts
@@ -9,19 +9,11 @@ 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(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `becca-loader-spec-${counter}`,
@@ -163,7 +155,7 @@ describe("becca_loader", () => {
const etapiTokenId = "loaderEtapiToken1";
const now = "2025-01-01 00:00:00.000Z";
- withContext(() => {
+ getContext().init(() => {
getSql().execute(
/*sql*/`INSERT INTO etapi_tokens (etapiTokenId, name, tokenHash, utcDateCreated, utcDateModified, isDeleted)
VALUES (?, ?, ?, ?, ?, 0)`,
@@ -184,7 +176,7 @@ describe("becca_loader", () => {
it("reloads becca and notifies the frontend with the supplied reason", () => {
const spy = vi.spyOn(ws, "reloadFrontend").mockImplementation(() => {});
- withContext(() => reload("custom reason"));
+ getContext().init(() => reload("custom reason"));
expect(becca.loaded).toBe(true);
expect(spy).toHaveBeenCalledWith("custom reason");
@@ -193,7 +185,7 @@ describe("becca_loader", () => {
it("falls back to a default reason when none is given", () => {
const spy = vi.spyOn(ws, "reloadFrontend").mockImplementation(() => {});
- withContext(() => reload(""));
+ getContext().init(() => reload(""));
// The empty reason triggers the `reason || "becca reloaded"` fallback.
expect(spy).toHaveBeenCalledWith("becca reloaded");
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.ts
index cc05ca194d..c8022885cc 100644
--- a/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts
+++ b/packages/trilium-core/src/becca/entities/abstract_becca_entity.spec.ts
@@ -9,20 +9,12 @@ 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(() => {
+ return getContext().init(() => {
const { note } = noteService.createNewNote({
parentNoteId: "root",
title: `abstract-becca-entity-spec-${counter}`,
@@ -113,7 +105,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
isSynced: false,
utcDateModified: "2020-01-01 00:00:00.000Z"
});
- withContext(() => option.save());
+ getContext().init(() => option.save());
const stored = getSql().getValue<string>(
"SELECT value FROM options WHERE name = ?",
@@ -126,7 +118,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
describe("_setContent guards", () => {
it("throws when content is null", () => {
const note = createNote();
- expect(() => withContext(() => note.setContent(null as unknown as string))).toThrow(
+ expect(() => getContext().init(() => note.setContent(null as unknown as string))).toThrow(
/Cannot set null content/
);
});
@@ -134,7 +126,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
it("throws when content is undefined", () => {
const note = createNote();
expect(() =>
- withContext(() => note.setContent(undefined as unknown as string))
+ getContext().init(() => note.setContent(undefined as unknown as string))
).toThrow(/Cannot set null content/);
});
});
@@ -142,7 +134,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
describe("forceFrontendReload componentId branch (saveBlob)", () => {
it("saves new content with forceFrontendReload set", () => {
const note = createNote();
- withContext(() =>
+ getContext().init(() =>
note.setContent("<p>reload-me-" + counter + "</p>", { forceFrontendReload: true })
);
@@ -155,7 +147,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
protectedSessionService.setDataKey(PROTECTED_KEY);
const note = createNote({ isProtected: true });
- withContext(() => note.setContent("super secret " + counter));
+ getContext().init(() => note.setContent("super secret " + counter));
// Round-trips back to plaintext while the session is available.
expect(unwrapStringOrBuffer(note.getContent())).toBe("super secret " + counter);
@@ -167,7 +159,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
vi.spyOn(protectedSessionService, "encrypt").mockReturnValue(null);
- expect(() => withContext(() => note.setContent("won't encrypt " + counter))).toThrow(
+ expect(() => getContext().init(() => note.setContent("won't encrypt " + counter))).toThrow(
/Unable to encrypt/
);
});
@@ -178,7 +170,7 @@ describe("AbstractBeccaEntity (real DB)", () => {
const note = createNote({ isProtected: true });
protectedSessionService.resetDataKey();
- expect(() => withContext(() => note.setContent("no session " + counter))).toThrow(
+ expect(() => getContext().init(() => 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.ts
index c0873ce08b..675d682ad2 100644
--- a/packages/trilium-core/src/becca/entities/battachment.spec.ts
+++ b/packages/trilium-core/src/becca/entities/battachment.spec.ts
@@ -10,20 +10,12 @@ 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(() => {
+ return getContext().init(() => {
const { note } = noteService.createNewNote({
parentNoteId: "root",
title: `battachment-spec-${counter}`,
@@ -94,7 +86,7 @@ describe("BAttachment (real DB)", () => {
describe("copy / getNote / hasStringContent / getFileName", () => {
it("copy produces an independent attachment with the same descriptive fields", () => {
const note = createNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "orig", content: "hi" })
);
@@ -110,7 +102,7 @@ describe("BAttachment (real DB)", () => {
it("getNote resolves the owning note through becca", () => {
const note = createNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "gn", content: "x" })
);
@@ -137,11 +129,11 @@ describe("BAttachment (real DB)", () => {
describe("content round-trip", () => {
it("setContent then getContent round-trips through the blob store", () => {
const note = createNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "rt", content: "" })
);
- withContext(() => att.setContent("payload-" + counter, { forceSave: true }));
+ getContext().init(() => att.setContent("payload-" + counter, { forceSave: true }));
expect(unwrapStringOrBuffer(att.getContent())).toBe("payload-" + counter);
});
@@ -150,7 +142,7 @@ describe("BAttachment (real DB)", () => {
describe("isContentAvailable / getTitleOrProtected / decrypt", () => {
it("a non-protected attachment is always content-available and exposes its title", () => {
const note = createNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "plain", content: "x" })
);
@@ -161,7 +153,7 @@ describe("BAttachment (real DB)", () => {
it("a protected attachment hides its title once the session is dropped", () => {
protectedSessionService.setDataKey(PROTECTED_KEY);
const note = createNote({ isProtected: true });
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -188,7 +180,7 @@ describe("BAttachment (real DB)", () => {
protectedSessionService.setDataKey(PROTECTED_KEY);
const note = createNote({ isProtected: true });
const plainTitle = "decrypt-me-" + counter;
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -209,7 +201,7 @@ describe("BAttachment (real DB)", () => {
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(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -231,7 +223,7 @@ describe("BAttachment (real DB)", () => {
it("decrypt swallows decryption errors and leaves the entity not-decrypted", () => {
protectedSessionService.setDataKey(PROTECTED_KEY);
const note = createNote({ isProtected: true });
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -259,7 +251,7 @@ describe("BAttachment (real DB)", () => {
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/);
+ expect(() => getContext().init(() => att.convertToNote())).toThrow(/search/);
});
it("throws when the owning note cannot be found", () => {
@@ -267,24 +259,24 @@ describe("BAttachment (real DB)", () => {
baseRow({ ownerId: "missingOwner123", role: "file", mime: "text/plain", title: "noOwner" })
);
- expect(() => withContext(() => att.convertToNote())).toThrow(/Cannot find note/);
+ expect(() => getContext().init(() => att.convertToNote())).toThrow(/Cannot find note/);
});
it("throws when the role has no note-type mapping", () => {
const note = createNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
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/);
+ expect(() => getContext().init(() => 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(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -298,13 +290,13 @@ describe("BAttachment (real DB)", () => {
protectedSessionService.resetDataKey();
const reloaded = attachmentId ? becca.getAttachmentOrThrow(attachmentId) : att;
- expect(() => withContext(() => reloaded.convertToNote())).toThrow(/protected session/);
+ expect(() => getContext().init(() => 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(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -315,7 +307,7 @@ describe("BAttachment (real DB)", () => {
const attachmentId = att.attachmentId;
expect(attachmentId).toBeDefined();
- const { note: created, branch } = withContext(() => att.convertToNote());
+ const { note: created, branch } = getContext().init(() => att.convertToNote());
expect(created.type).toBe("file");
expect(created.title).toBe("fileconv-" + counter);
@@ -328,7 +320,7 @@ describe("BAttachment (real DB)", () => {
it("converts an 'image' attachment and rewrites the embedded attachment URL in the parent", () => {
const note = createNote({ content: "<p>placeholder</p>" });
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "image",
mime: "image/png",
@@ -341,9 +333,9 @@ describe("BAttachment (real DB)", () => {
// 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));
+ getContext().init(() => note.setContent(refContent));
- const { note: created } = withContext(() => att.convertToNote());
+ const { note: created } = getContext().init(() => att.convertToNote());
expect(created.type).toBe("image");
// The parent content's attachment URL has been rewritten to the new image note URL.
@@ -354,7 +346,7 @@ describe("BAttachment (real DB)", () => {
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(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "image",
mime: "image/png",
@@ -363,7 +355,7 @@ describe("BAttachment (real DB)", () => {
})
);
- const { note: created } = withContext(() => att.convertToNote());
+ const { note: created } = getContext().init(() => att.convertToNote());
expect(created.type).toBe("image");
// No URL matched, so the parent content stays exactly as it was.
@@ -374,7 +366,7 @@ describe("BAttachment (real DB)", () => {
// 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(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "image",
mime: "image/png",
@@ -385,7 +377,7 @@ describe("BAttachment (real DB)", () => {
vi.spyOn(note, "getContent").mockReturnValue(new Uint8Array([1, 2, 3]));
- expect(() => withContext(() => att.convertToNote())).toThrow(/non-string content/);
+ expect(() => getContext().init(() => att.convertToNote())).toThrow(/non-string content/);
});
});
@@ -454,7 +446,7 @@ describe("BAttachment (real DB)", () => {
it("getPojoToSave drops the title for a protected attachment outside a session", () => {
protectedSessionService.setDataKey(PROTECTED_KEY);
const note = createNote({ isProtected: true });
- const att = withContext(() =>
+ const att = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
diff --git a/packages/trilium-core/src/becca/entities/battribute.spec.ts b/packages/trilium-core/src/becca/entities/battribute.spec.ts
index b669f1ab04..eb9c4dd395 100644
--- a/packages/trilium-core/src/becca/entities/battribute.spec.ts
+++ b/packages/trilium-core/src/becca/entities/battribute.spec.ts
@@ -7,20 +7,12 @@ 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(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: `battribute-spec-${counter}`,
diff --git a/packages/trilium-core/src/becca/entities/bblob.spec.ts b/packages/trilium-core/src/becca/entities/bblob.spec.ts
index 354dbcd95d..4de159c78c 100644
--- a/packages/trilium-core/src/becca/entities/bblob.spec.ts
+++ b/packages/trilium-core/src/becca/entities/bblob.spec.ts
@@ -4,11 +4,6 @@ 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");
@@ -84,7 +79,7 @@ describe("BBlob save (getPojoToSave omits contentLength)", () => {
utcDateModified: "2025-06-27 14:10:39.688+0300"
});
- withContext(() => blob.save());
+ getContext().init(() => blob.save());
const row = getSql().getRow<Record<string, unknown>>(
"SELECT * FROM blobs WHERE blobId = ?",
diff --git a/packages/trilium-core/src/becca/entities/bbranch.spec.ts b/packages/trilium-core/src/becca/entities/bbranch.spec.ts
index f7c912eced..12b0c00593 100644
--- a/packages/trilium-core/src/becca/entities/bbranch.spec.ts
+++ b/packages/trilium-core/src/becca/entities/bbranch.spec.ts
@@ -6,14 +6,6 @@ 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;
/**
@@ -23,7 +15,7 @@ let counter = 0;
*/
function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `bbranch-spec-${counter}`,
@@ -38,13 +30,13 @@ describe("BBranch (real DB)", () => {
it("refuses to delete the root branch", () => {
const rootBranch = becca.getBranchOrThrow("none_root");
- expect(() => withContext(() => rootBranch.deleteBranch())).toThrow();
+ expect(() => getContext().init(() => rootBranch.deleteBranch())).toThrow();
});
it("deletes a note that has only one strong parent branch", () => {
const { note, branch } = createNote("root");
- const deleted = withContext(() => branch.deleteBranch());
+ const deleted = getContext().init(() => branch.deleteBranch());
expect(deleted).toBe(true);
expect(branch.isDeleted).toBe(true);
@@ -56,7 +48,7 @@ describe("BBranch (real DB)", () => {
const otherParent = createNote("root");
// Add a second strong branch under another parent.
- const secondBranch = withContext(() => {
+ const secondBranch = getContext().init(() => {
const b = new BBranch({
noteId: note.noteId,
parentNoteId: otherParent.note.noteId,
@@ -70,7 +62,7 @@ describe("BBranch (real DB)", () => {
const firstBranch = note.getParentBranches().find((b) => b.parentNoteId === "root");
expect(firstBranch).toBeDefined();
- const deleted = withContext(() => firstBranch?.deleteBranch());
+ const deleted = getContext().init(() => firstBranch?.deleteBranch());
expect(deleted).toBe(false);
expect(note.isDeleted).toBe(false);
@@ -82,7 +74,7 @@ describe("BBranch (real DB)", () => {
// 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 weakBranch = getContext().init(() => {
const b = new BBranch({
noteId: note.noteId,
parentNoteId: "_lbBookmarks",
@@ -96,7 +88,7 @@ describe("BBranch (real DB)", () => {
expect(weakBranch.isWeak).toBe(true);
expect(note.getStrongParentBranches().length).toBe(1);
- const deleted = withContext(() => branch.deleteBranch());
+ const deleted = getContext().init(() => branch.deleteBranch());
// The single strong branch is gone, so the note (and its weak branch)
// are deleted as well.
@@ -108,7 +100,7 @@ describe("BBranch (real DB)", () => {
it("deletes attached attachments together with the note", () => {
const { note, branch } = createNote("root");
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({
role: "file",
mime: "text/plain",
@@ -119,7 +111,7 @@ describe("BBranch (real DB)", () => {
expect(note.getAttachments().some((a) => a.attachmentId === attachment.attachmentId)).toBe(true);
- const deleted = withContext(() => branch.deleteBranch());
+ const deleted = getContext().init(() => branch.deleteBranch());
expect(deleted).toBe(true);
// The attachment was marked deleted as part of the note deletion, so it
@@ -132,7 +124,7 @@ describe("BBranch (real DB)", () => {
it("throws when noteId or parentNoteId are missing", () => {
const branch = new BBranch();
- expect(() => withContext(() => branch.save())).toThrow();
+ expect(() => getContext().init(() => branch.save())).toThrow();
});
it("computes notePosition as max sibling position + 10, skipping _hidden", () => {
@@ -142,7 +134,7 @@ describe("BBranch (real DB)", () => {
const maxPos = existing.branch.notePosition;
const child = createNote("root");
- const newBranch = withContext(() => {
+ const newBranch = getContext().init(() => {
const b = new BBranch({
noteId: child.note.noteId,
parentNoteId: parent.note.noteId,
@@ -171,7 +163,7 @@ describe("BBranch (real DB)", () => {
delete becca.childParentToBranch[key];
try {
- const newBranch = withContext(() => {
+ const newBranch = getContext().init(() => {
const b = new BBranch({
noteId: child.note.noteId,
parentNoteId: parent.note.noteId,
@@ -198,7 +190,7 @@ describe("BBranch (real DB)", () => {
const target = createNote("root");
// Create the clone under the target first.
- const firstClone = withContext(() => {
+ const firstClone = getContext().init(() => {
const clone = branch.createClone(target.note.noteId);
clone.save();
return clone;
@@ -209,7 +201,7 @@ describe("BBranch (real DB)", () => {
// 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));
+ const secondClone = getContext().init(() => branch.createClone(target.note.noteId, 555));
expect(secondClone).toBe(firstClone);
expect(secondClone.notePosition).toBe(555);
@@ -219,14 +211,14 @@ describe("BBranch (real DB)", () => {
const { branch } = createNote("root");
const target = createNote("root");
- const firstClone = withContext(() => {
+ const firstClone = getContext().init(() => {
const clone = branch.createClone(target.note.noteId);
clone.save();
return clone;
});
const originalPos = firstClone.notePosition;
- const secondClone = withContext(() => branch.createClone(target.note.noteId));
+ const secondClone = getContext().init(() => branch.createClone(target.note.noteId));
expect(secondClone).toBe(firstClone);
expect(secondClone.notePosition).toBe(originalPos);
diff --git a/packages/trilium-core/src/becca/entities/betapi_token.spec.ts b/packages/trilium-core/src/becca/entities/betapi_token.spec.ts
index f55babc548..02457ad5de 100644
--- a/packages/trilium-core/src/becca/entities/betapi_token.spec.ts
+++ b/packages/trilium-core/src/becca/entities/betapi_token.spec.ts
@@ -5,11 +5,6 @@ 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");
@@ -121,7 +116,7 @@ describe("BEtapiToken save (beforeSaving)", () => {
utcDateModified: "2025-06-27 14:10:39.688+0300"
});
- withContext(() => token.save());
+ getContext().init(() => token.save());
const row = getSql().getRow<Record<string, unknown>>(
"SELECT * FROM etapi_tokens WHERE etapiTokenId = ?",
diff --git a/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts b/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts
index 5230056dce..e7bb9cee98 100644
--- a/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts
+++ b/packages/trilium-core/src/becca/entities/bnote_attributes.spec.ts
@@ -7,14 +7,6 @@ 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;
/**
@@ -24,7 +16,7 @@ let counter = 0;
*/
function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `bnote-attrs-spec-${counter}`,
@@ -39,7 +31,7 @@ describe("BNote attribute methods (real DB)", () => {
it("filters by type+name, type only, and name only", () => {
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("colorTag", "red");
note.addRelation("linkTag", note.noteId);
});
@@ -78,7 +70,7 @@ describe("BNote attribute methods (real DB)", () => {
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));
+ getContext().init(() => parent.note.addLabel("inheritedFlag", "yes", true));
const child = createNote(parent.note.noteId);
@@ -94,13 +86,13 @@ describe("BNote attribute methods (real DB)", () => {
// Template note carrying labels, applied via a ~template relation.
const template = createNote("root");
- withContext(() => {
+ getContext().init(() => {
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));
+ getContext().init(() => consumer.note.addRelation("template", template.note.noteId));
const templated = consumer.note.getAttributes("label", "fromTemplate");
expect(templated).toHaveLength(1);
@@ -120,7 +112,7 @@ describe("BNote attribute methods (real DB)", () => {
// A note whose ~template relation points back to itself triggers the
// path-cycle short-circuit inside __getAttributes.
const selfTemplate = createNote("root");
- withContext(() => {
+ getContext().init(() => {
selfTemplate.note.addLabel("selfLabel", "v");
selfTemplate.note.addRelation("template", selfTemplate.note.noteId);
});
@@ -133,7 +125,7 @@ describe("BNote attribute methods (real DB)", () => {
// A two-note ~inherit cycle exercises the mutual recursion guard as well.
const a = createNote("root");
const b = createNote("root");
- withContext(() => {
+ getContext().init(() => {
a.note.addLabel("aLabel", "av");
b.note.addLabel("bLabel", "bv");
a.note.addRelation("inherit", b.note.noteId);
@@ -174,7 +166,7 @@ describe("BNote attribute methods (real DB)", () => {
const target = createNote("root");
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("MyLabel", "Val");
note.addRelation("myRel", target.note.noteId);
});
@@ -201,7 +193,7 @@ describe("BNote attribute methods (real DB)", () => {
const target = createNote("root");
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("ownLabel", "lv");
note.addRelation("ownRel", target.note.noteId);
});
@@ -224,10 +216,10 @@ describe("BNote attribute methods (real DB)", () => {
describe("label value collectors", () => {
it("covers getLabelValues and getOwnedLabelValues", () => {
const parent = createNote("root");
- withContext(() => parent.note.addLabel("multi", "inherited", true));
+ getContext().init(() => parent.note.addLabel("multi", "inherited", true));
const child = createNote(parent.note.noteId);
- withContext(() => child.note.addLabel("multi", "own"));
+ getContext().init(() => child.note.addLabel("multi", "own"));
const allValues = child.note.getLabelValues("multi");
expect(allValues).toContain("own");
@@ -242,7 +234,7 @@ describe("BNote attribute methods (real DB)", () => {
it("covers type+name+value, type+name, type only and name only", () => {
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("oa", "v1");
note.addLabel("oa", "v2");
note.addRelation("orel", note.noteId);
@@ -274,7 +266,7 @@ describe("BNote attribute methods (real DB)", () => {
describe("definition collectors", () => {
it("covers getRelationDefinitions and getLabelDefinitions", () => {
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("relation:child", "");
note.addLabel("plain", "x");
});
@@ -287,12 +279,12 @@ describe("BNote attribute methods (real DB)", () => {
describe("mutation helpers", () => {
it("removeAttribute honours the value-match branch", () => {
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
note.addLabel("rm", "keep");
note.addLabel("rm", "drop");
});
- withContext(() => note.removeAttribute("label", "rm", "drop"));
+ getContext().init(() => note.removeAttribute("label", "rm", "drop"));
const remaining = note.getOwnedAttributes("label", "rm");
expect(remaining).toHaveLength(1);
@@ -303,14 +295,14 @@ describe("BNote attribute methods (real DB)", () => {
const target = createNote("root");
const { note } = createNote("root");
- withContext(() => {
+ getContext().init(() => {
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(() => {
+ getContext().init(() => {
note.toggleLabel(false, "toggled");
note.toggleRelation(false, "togRel");
});
@@ -322,10 +314,10 @@ describe("BNote attribute methods (real DB)", () => {
const target = createNote("root");
const { note } = createNote("root");
- withContext(() => note.addRelation("delRel", target.note.noteId));
+ getContext().init(() => note.addRelation("delRel", target.note.noteId));
expect(note.getOwnedRelation("delRel")).not.toBeNull();
- withContext(() => note.removeRelation("delRel"));
+ getContext().init(() => note.removeRelation("delRel"));
expect(note.getOwnedRelation("delRel")).toBeNull();
});
});
@@ -333,7 +325,7 @@ describe("BNote attribute methods (real DB)", () => {
describe("attribute-by-id accessors", () => {
it("getAttributeById finds via the cache", () => {
const { note } = createNote("root");
- const attr = withContext(() => note.addLabel("byId", "value"));
+ const attr = getContext().init(() => note.addLabel("byId", "value"));
const found = note.getAttributeById(attr.attributeId);
expect(found?.attributeId).toBe(attr.attributeId);
@@ -342,20 +334,20 @@ describe("BNote attribute methods (real DB)", () => {
it("setAttributeValueById updates the value and throws when not found", () => {
const { note } = createNote("root");
- const attr = withContext(() => note.addLabel("settable", "old"));
+ const attr = getContext().init(() => note.addLabel("settable", "old"));
- withContext(() => note.setAttributeValueById(attr.attributeId, "new"));
+ getContext().init(() => 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"));
+ getContext().init(() => 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));
+ getContext().init(() => note.setAttributeValueById(attr.attributeId));
expect(note.getOwnedLabel("settable")?.value).toBe("");
- expect(() => withContext(() => note.setAttributeValueById("missing-attr-id", "x"))).toThrow();
+ expect(() => getContext().init(() => 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.ts
index 7b4ed0b9c4..054270228e 100644
--- a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts
+++ b/packages/trilium-core/src/becca/entities/bnote_content.spec.ts
@@ -21,17 +21,12 @@ import type BNote from "./bnote.js";
// 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(() => {
+ return getContext().init(() => {
const { note } = noteService.createNewNote({
parentNoteId: opts.parentNoteId ?? "root",
title: `bnote-content-spec-${counter}`,
@@ -68,7 +63,7 @@ describe("BNote content / misc getters", () => {
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" }));
+ getContext().init(() => note.setJsonContent({ a: 1, b: "two" }));
expect(note.getJsonContent()).toEqual({ a: 1, b: "two" });
});
@@ -192,7 +187,7 @@ describe("BNote content / misc getters", () => {
const note = createNote();
const target = createNote();
- withContext(() => {
+ getContext().init(() => {
note.addLabel("plainLabel", "v");
note.addRelation("relTo", target.noteId); // not an auto-link
note.addRelation("internalLink", target.noteId); // auto-link
@@ -224,7 +219,7 @@ describe("BNote content / misc getters", () => {
const source = createNote();
const target = createNote();
- const res = withContext(() => source.cloneTo(target.noteId));
+ const res = getContext().init(() => source.cloneTo(target.noteId));
expect(res.success).toBe(true);
expect(becca.getBranchFromChildAndParent(source.noteId, target.noteId)).not.toBeNull();
@@ -245,7 +240,7 @@ describe("BNote content / misc getters", () => {
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(() => {
+ getContext().init(() => {
parent.addRelation("imageLink", image.noteId);
parent.setContent(`<img src="api/images/${image.noteId}/foo.png">`);
});
@@ -268,7 +263,7 @@ describe("BNote content / misc getters", () => {
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));
+ getContext().init(() => image.cloneTo(parentB.noteId));
expect(image.getParentBranches().length).toBeGreaterThan(1);
expect(image.isEligibleForConversionToAttachment()).toBe(false);
});
@@ -283,7 +278,7 @@ describe("BNote content / misc getters", () => {
const parent = createNote({ content: "" });
const other = createNote({ content: "" });
const image = createNote({ parentNoteId: parent.noteId, type: "image", mime: "image/png", content: "x" });
- withContext(() => {
+ getContext().init(() => {
parent.addRelation("imageLink", image.noteId);
other.addRelation("imageLink", image.noteId);
});
@@ -296,14 +291,14 @@ describe("BNote content / misc getters", () => {
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));
+ getContext().init(() => 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));
+ getContext().init(() => parent.addRelation("imageLink", image.noteId));
expect(image.isEligibleForConversionToAttachment()).toBe(false);
});
@@ -313,7 +308,7 @@ describe("BNote content / misc getters", () => {
expect(image.isEligibleForConversionToAttachment()).toBe(true);
const imageNoteId = image.noteId;
- const attachment = withContext(() => image.convertToParentAttachment());
+ const attachment = getContext().init(() => image.convertToParentAttachment());
expect(attachment).not.toBeNull();
expect(attachment?.ownerId).toBe(parent.noteId);
@@ -327,7 +322,7 @@ describe("BNote content / misc getters", () => {
it("convertToParentAttachment returns null when the note is not eligible", () => {
const text = createNote();
- expect(withContext(() => text.convertToParentAttachment())).toBeNull();
+ expect(getContext().init(() => text.convertToParentAttachment())).toBeNull();
});
});
@@ -336,18 +331,18 @@ describe("BNote content / misc getters", () => {
const note = createNote();
expect(note.isDeleted).toBe(false);
- withContext(() => note.deleteNote());
+ getContext().init(() => note.deleteNote());
expect(note.isDeleted).toBe(true);
});
it("is a no-op when the note is already deleted", () => {
const note = createNote();
- withContext(() => note.deleteNote());
+ getContext().init(() => note.deleteNote());
expect(note.isDeleted).toBe(true);
// Second call hits the early `isDeleted` return.
- expect(() => withContext(() => note.deleteNote())).not.toThrow();
+ expect(() => getContext().init(() => note.deleteNote())).not.toThrow();
});
});
@@ -399,7 +394,7 @@ describe("BNote content / misc getters", () => {
describe("saveRevision / eraseExcessRevisionSnapshots (lines 1551-1620)", () => {
it("saves a revision and copies note attachments onto it", () => {
const note = createNote();
- withContext(() =>
+ getContext().init(() =>
note.saveAttachment({
role: "image",
mime: "image/png",
@@ -408,7 +403,7 @@ describe("BNote content / misc getters", () => {
})
);
- const revision = withContext(() => note.saveRevision({ description: "d", source: "test" as never }));
+ const revision = getContext().init(() => note.saveRevision({ description: "d", source: "test" as never }));
expect(revision.revisionId).toBeDefined();
expect(revision.getAttachments().length).toBe(1);
@@ -416,15 +411,15 @@ describe("BNote content / misc getters", () => {
it("erases excess revisions beyond the #versioningLimit label", () => {
const note = createNote();
- withContext(() => note.setLabel("versioningLimit", "2"));
+ getContext().init(() => 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());
+ getContext().init(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
// With a limit of 2, the older revisions beyond the 2 most recent are erased.
expect(eraseSpy).toHaveBeenCalled();
@@ -436,15 +431,15 @@ describe("BNote content / misc getters", () => {
it("falls back to the option limit when no label is present", () => {
const note = createNote();
- withContext(() => optionService.setOption("revisionSnapshotNumberLimit", "1"));
+ getContext().init(() => optionService.setOption("revisionSnapshotNumberLimit", "1"));
try {
- withContext(() => note.saveRevision());
- withContext(() => note.saveRevision());
- withContext(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
+ getContext().init(() => note.saveRevision());
expect(note.getRevisions().length).toBeLessThanOrEqual(1);
} finally {
- withContext(() => optionService.setOption("revisionSnapshotNumberLimit", "-1"));
+ getContext().init(() => optionService.setOption("revisionSnapshotNumberLimit", "-1"));
}
});
});
@@ -452,10 +447,10 @@ describe("BNote content / misc getters", () => {
describe("saveAttachment matchBy (lines 1628-1655)", () => {
it("matches an existing attachment by title", () => {
const note = createNote();
- const first = withContext(() =>
+ const first = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "by-title-" + counter, content: "a" })
);
- const second = withContext(() =>
+ const second = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "by-title-" + counter, content: "b" }, "title")
);
@@ -467,11 +462,11 @@ describe("BNote content / misc getters", () => {
it("matches an existing attachment by attachmentId (default)", () => {
const note = createNote();
- const first = withContext(() =>
+ const first = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "by-id-" + counter, content: "a" })
);
const attachmentId = first.attachmentId ?? "";
- const second = withContext(() =>
+ const second = getContext().init(() =>
note.saveAttachment({ attachmentId, role: "file", mime: "text/plain", title: "by-id-" + counter, content: "b" })
);
@@ -482,7 +477,7 @@ describe("BNote content / misc getters", () => {
it("throws for an unsupported matchBy value", () => {
const note = createNote();
expect(() =>
- withContext(() =>
+ getContext().init(() =>
note.saveAttachment(
{ role: "file", mime: "text/plain", title: "bad", content: "x" },
"bogus" as never
diff --git a/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts b/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts
index 69dc19841d..c870fe781a 100644
--- a/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts
+++ b/packages/trilium-core/src/becca/entities/bnote_tree.spec.ts
@@ -11,14 +11,6 @@ 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;
/**
@@ -32,7 +24,7 @@ function createNote(
content = "<p>hello</p>"
): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `bnote-tree-spec-${counter}`,
@@ -60,7 +52,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
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", ""));
+ getContext().init(() => attributeService.createLabel(note.noteId, "archived", ""));
expect(note.isArchived).toBe(true);
// Lines 713-725: best note path record exists and is flagged archived.
@@ -85,7 +77,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
it("detects an inheritable archived label and skips a non-inheritable one", () => {
const inheritable = createNote("root").note;
- withContext(() =>
+ getContext().init(() =>
attributeService.createAttribute({
noteId: inheritable.noteId,
type: "label",
@@ -98,7 +90,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
expect(inheritable.hasInheritableArchivedLabel()).toBe(true);
const plain = createNote("root").note;
- withContext(() => attributeService.createLabel(plain.noteId, "archived", ""));
+ getContext().init(() => attributeService.createLabel(plain.noteId, "archived", ""));
// Non-inheritable archived label: loop completes without an early return.
expect(plain.hasInheritableArchivedLabel()).toBe(false);
});
@@ -110,18 +102,18 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const normalParent = createNote("root").note;
const archivedParent = createNote("root").note;
- withContext(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));
+ getContext().init(() => 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(() => {
+ getContext().init(() => {
cloningService.cloneNoteToParentNote(hiddenParent.note.noteId, "_hidden");
cloningService.ensureNoteIsAbsentFromParent(hiddenParent.note.noteId, "root");
});
expect(hiddenParent.note.isHiddenCompletely()).toBe(true);
- withContext(() => {
+ getContext().init(() => {
cloningService.cloneNoteToParentNote(child.noteId, normalParent.noteId);
cloningService.cloneNoteToParentNote(child.noteId, archivedParent.noteId);
cloningService.cloneNoteToParentNote(child.noteId, hiddenParent.note.noteId);
@@ -148,7 +140,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const parent = createNote("root").note;
const child = createNote("root").note;
- withContext(() =>
+ getContext().init(() =>
cloningService.cloneNoteToParentNote(child.noteId, parent.noteId, "MYPREFIX")
);
child.invalidateThisCache();
@@ -167,7 +159,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const template = createNote("root").note;
const instance = createNote("root").note;
// instance ~template-> template, so template has a target relation.
- withContext(() =>
+ getContext().init(() =>
attributeService.createRelation(instance.noteId, "template", template.noteId)
);
@@ -190,7 +182,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
// 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));
+ getContext().init(() => 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.
@@ -215,7 +207,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const root = createNote("root").note;
const viaInherit = createNote("root").note;
const viaOther = createNote("root").note;
- withContext(() => {
+ getContext().init(() => {
// 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.
@@ -239,7 +231,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const target = createNote("root").note;
const search = createNote("root", "search").note;
- withContext(() =>
+ getContext().init(() =>
attributeService.createLabel(search.noteId, "searchString", `note.title = "${target.title}"`)
);
@@ -266,7 +258,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
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));
+ getContext().init(() => cloningService.cloneNoteToParentNote(a.noteId, b.noteId));
const { notes, relationships } = root.getSubtree();
const noteIds = notes.map((n) => n.noteId);
@@ -296,7 +288,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const root = createNote("root").note;
const normal = createNote(root.noteId).note;
const archived = createNote(root.noteId).note;
- withContext(() => attributeService.createLabel(archived.noteId, "archived", ""));
+ getContext().init(() => attributeService.createLabel(archived.noteId, "archived", ""));
const noteIds = root
.getSubtree({ includeArchived: false })
@@ -311,7 +303,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const parent = createNote("root").note;
const search = createNote(parent.noteId, "search").note;
- withContext(() =>
+ getContext().init(() =>
attributeService.createLabel(search.noteId, "searchString", `note.title = "${target.title}"`)
);
@@ -347,7 +339,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
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));
+ getContext().init(() => cloningService.cloneNoteToParentNote(leaf.noteId, right.noteId));
const ancestorIds = leaf.getAncestorNoteIds();
// ancestor must appear exactly once despite two paths.
@@ -363,7 +355,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const grandparent = createNote("root").note;
const parent = createNote(grandparent.noteId).note;
const leaf = createNote(parent.noteId).note;
- withContext(() => cloningService.cloneNoteToParentNote(leaf.noteId, grandparent.noteId));
+ getContext().init(() => cloningService.cloneNoteToParentNote(leaf.noteId, grandparent.noteId));
const ancestorIds = leaf.getAncestorNoteIds();
expect(ancestorIds.filter((id) => id === grandparent.noteId).length).toBe(1);
@@ -375,7 +367,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
it("includes notes whose template/inherit relation targets this note", () => {
const template = createNote("root").note;
const instance = createNote("root").note;
- withContext(() =>
+ getContext().init(() =>
attributeService.createRelation(instance.noteId, "template", template.noteId)
);
@@ -389,7 +381,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const template = createNote("root").note;
const viaInherit = createNote("root").note;
const viaOther = createNote("root").note;
- withContext(() => {
+ getContext().init(() => {
// 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.
@@ -406,10 +398,10 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
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", ""));
+ getContext().init(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));
const leaf = createNote(visibleParent.noteId).note;
- withContext(() => {
+ getContext().init(() => {
cloningService.cloneNoteToParentNote(leaf.noteId, archivedParent.noteId);
cloningService.cloneNoteToParentNote(leaf.noteId, "_hidden");
});
@@ -435,7 +427,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const hoisted = createNote("root").note;
const outside = createNote("root").note;
const leaf = createNote(hoisted.noteId).note;
- withContext(() => cloningService.cloneNoteToParentNote(leaf.noteId, outside.noteId));
+ getContext().init(() => cloningService.cloneNoteToParentNote(leaf.noteId, outside.noteId));
// Lines 1169 / 1175-1176: isInHoistedSubTree comparator wins.
const best = leaf.getBestNotePath(hoisted.noteId);
@@ -449,10 +441,10 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const out1 = createNote("root").note;
const out2 = createNote("root").note;
const archivedParent = createNote("root").note;
- withContext(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));
+ getContext().init(() => attributeService.createLabel(archivedParent.noteId, "archived", ""));
const leaf = createNote(hoisted.noteId).note;
- withContext(() => {
+ getContext().init(() => {
cloningService.cloneNoteToParentNote(leaf.noteId, out1.noteId);
cloningService.cloneNoteToParentNote(leaf.noteId, out2.noteId);
cloningService.cloneNoteToParentNote(leaf.noteId, archivedParent.noteId);
@@ -528,7 +520,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
const parent = createNote("root").note;
const visible = createNote(parent.noteId).note;
const hiddenLabelled = createNote(parent.noteId).note;
- withContext(() =>
+ getContext().init(() =>
attributeService.createLabel(hiddenLabelled.noteId, "shareHiddenFromTree", "true")
);
@@ -550,7 +542,7 @@ describe("BNote tree / note-path / subtree methods (real DB)", () => {
// 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(() =>
+ getContext().init(() =>
cloningService.cloneNoteToParentNote("_globalNoteMap", emptyParent.noteId)
);
expect(emptyParent.getChildNotes().length).toBeGreaterThanOrEqual(1);
diff --git a/packages/trilium-core/src/becca/entities/brevision.spec.ts b/packages/trilium-core/src/becca/entities/brevision.spec.ts
index 616918c3b6..6b045c43a1 100644
--- a/packages/trilium-core/src/becca/entities/brevision.spec.ts
+++ b/packages/trilium-core/src/becca/entities/brevision.spec.ts
@@ -8,17 +8,12 @@ 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(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: `brevision-spec-${counter}`,
@@ -175,7 +170,7 @@ describe("Revision constructor (protected)", () => {
describe("Revision JSON content", () => {
function saveRevisionWithContent(content: string): BRevision {
const note = createNote();
- const revision = withContext(() => {
+ const revision = getContext().init(() => {
const rev = note.saveRevision();
rev.setContent(content, { forceSave: true });
return rev;
@@ -210,7 +205,7 @@ describe("Revision attachments", () => {
function setup(): BRevision {
const note = createNote();
- return withContext(() => {
+ return getContext().init(() => {
note.saveAttachment({
attachmentId: undefined,
role: "image",
@@ -272,7 +267,7 @@ describe("Revision attachments", () => {
describe("Revision getNote", () => {
it("resolves the owning note from becca", () => {
const note = createNote();
- const revision = withContext(() => note.saveRevision());
+ const revision = getContext().init(() => note.saveRevision());
expect(revision.getNote()).toBe(note);
});
@@ -281,12 +276,12 @@ describe("Revision getNote", () => {
describe("Revision eraseRevision", () => {
it("hard-deletes the revision so it is no longer retrievable", () => {
const note = createNote();
- const revision = withContext(() => note.saveRevision());
+ const revision = getContext().init(() => note.saveRevision());
const revisionId = revision.revisionId ?? "";
expect(revisionId).not.toBe("");
expect(becca.getRevision(revisionId)).not.toBeNull();
- withContext(() => revision.eraseRevision());
+ getContext().init(() => revision.eraseRevision());
expect(becca.getRevision(revisionId)).toBeNull();
});
diff --git a/packages/trilium-core/src/services/blob.spec.ts b/packages/trilium-core/src/services/blob.spec.ts
index 7587144044..ace3717d8a 100644
--- a/packages/trilium-core/src/services/blob.spec.ts
+++ b/packages/trilium-core/src/services/blob.spec.ts
@@ -11,23 +11,6 @@ import notesService from "./notes.js";
import { decodeUtf8, encodeUtf8 } from "./utils/binary.js";
import { hash } from "./utils/index.js";
-// These specs run through the server suite (apps/server/spec/setup.ts), which
-// boots an in-memory fixture DB and calls initializeCore. getBlobPojo reads
-// notes from becca and blobs from SQL, and createNewNote (used to seed test
-// content) is a write path, so anything touching the DB is wrapped in a CLS
-// context via getContext().init(...).
-function withContext<T>(fn: () => T): Promise<T> {
- return new Promise<T>((resolve, reject) => {
- getContext().init(async () => {
- try {
- resolve(await fn());
- } catch (e) {
- reject(e);
- }
- });
- });
-}
-
const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes
describe("blob", () => {
@@ -141,12 +124,12 @@ describe("blob", () => {
});
describe("getBlobPojo", () => {
- it("throws NotFoundError when the entity does not exist", async () => {
- await expect(withContext(() => blob.getBlobPojo("notes", "doesNotExist123"))).rejects.toBeInstanceOf(NotFoundError);
+ it("throws NotFoundError when the entity does not exist", () => {
+ expect(() => getContext().init(() => blob.getBlobPojo("notes", "doesNotExist123"))).toThrow(NotFoundError);
});
- it("returns the decoded string content of a text note's blob", async () => {
- const { noteId, content, blobId } = await withContext(() => {
+ it("returns the decoded string content of a text note's blob", () => {
+ const { noteId, content, blobId } = getContext().init(() => {
const { note } = notesService.createNewNote({
parentNoteId: "root",
title: "blob spec text note",
@@ -164,10 +147,10 @@ describe("blob", () => {
expect(becca.notes[noteId]).toBeDefined();
});
- it("nulls out the content for a note with binary (non-string) content", async () => {
+ it("nulls out the content for a note with binary (non-string) content", () => {
const binary = Uint8Array.from([0, 1, 2, 3, 4, 5]);
- const { pojoContent, contentLength } = await withContext(() => {
+ const { pojoContent, contentLength } = getContext().init(() => {
const { note } = notesService.createNewNote({
parentNoteId: "root",
title: "blob spec image note",
diff --git a/packages/trilium-core/src/services/branches.spec.ts b/packages/trilium-core/src/services/branches.spec.ts
index 755557e10b..71c112a040 100644
--- a/packages/trilium-core/src/services/branches.spec.ts
+++ b/packages/trilium-core/src/services/branches.spec.ts
@@ -8,14 +8,6 @@ import { getContext } from "./context.js";
import noteService from "./notes.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * branch.save(), branch.markAsDeleted()) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -25,7 +17,7 @@ let counter = 0;
*/
function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `branches-spec-${counter}`,
@@ -40,7 +32,7 @@ describe("branches service (real DB)", () => {
it("is a no-op when the branch already lives under the target parent", () => {
const { branch } = createNote("root");
- const res = withContext(() => branchService.moveBranchToNote(branch, "root"));
+ const res = getContext().init(() => branchService.moveBranchToNote(branch, "root"));
expect(res).toEqual({ success: true });
// The original branch must remain, no clone created.
@@ -59,7 +51,7 @@ describe("branches service (real DB)", () => {
[parent.note.noteId]
);
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToNote(child.branch, parent.note.noteId)
) as { success: boolean; branch: BBranch };
@@ -86,7 +78,7 @@ describe("branches service (real DB)", () => {
const someParent = createNote("root");
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToNote(rootBranch!, someParent.note.noteId)
) as [number, { success: boolean; message?: string }];
@@ -104,7 +96,7 @@ describe("branches service (real DB)", () => {
const descendant = createNote(ancestor.note.noteId);
// Moving the ancestor under its own descendant is a cycle.
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToNote(ancestor.branch, descendant.note.noteId)
) as [number, { success: boolean; message?: string }];
@@ -122,7 +114,7 @@ describe("branches service (real DB)", () => {
targetParent.branch.isExpanded = false;
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")
) as { success: boolean; branch: BBranch };
@@ -138,7 +130,7 @@ describe("branches service (real DB)", () => {
targetParent.branch.isExpanded = true;
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")
) as { success: boolean; branch: BBranch };
@@ -152,7 +144,7 @@ describe("branches service (real DB)", () => {
targetParent.branch.isExpanded = false;
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToBranch(child.branch, targetParent.branch, "ignored-branch-id")
);
@@ -168,7 +160,7 @@ describe("branches service (real DB)", () => {
targetParent.branch.isExpanded = false;
- const res = withContext(() =>
+ const res = getContext().init(() =>
branchService.moveBranchToBranch(rootBranch!, targetParent.branch, "ignored-branch-id")
) as [number, { success: boolean }];
diff --git a/packages/trilium-core/src/services/bulk_actions.spec.ts b/packages/trilium-core/src/services/bulk_actions.spec.ts
index 0a5d11122c..5fd31fe41c 100644
--- a/packages/trilium-core/src/services/bulk_actions.spec.ts
+++ b/packages/trilium-core/src/services/bulk_actions.spec.ts
@@ -11,14 +11,6 @@ import { getContext } from "./context.js";
import noteService from "./notes.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * note.save(), attribute.save()) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -28,7 +20,7 @@ let counter = 0;
*/
function createNote(parentNoteId: string): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `bulk-actions-spec-${counter}`,
@@ -54,7 +46,7 @@ describe("bulk_actions service (real DB)", () => {
it("skips note IDs that don't resolve to a note", () => {
// No note exists for this id, so nothing should throw and no handler runs.
expect(() =>
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "addLabel", labelName: "foo", labelValue: "bar" }],
["doesNotExist123"]
@@ -67,7 +59,7 @@ describe("bulk_actions service (real DB)", () => {
const a = createNote("root");
const b = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "addLabel", labelName: "fromSet" }],
new Set([a.note.noteId, b.note.noteId])
@@ -88,7 +80,7 @@ describe("bulk_actions service (real DB)", () => {
{ name: "addLabel", labelName: "appliedAfterFailure" }
];
- expect(() => withContext(() => bulkActionService.executeActions(actions, [note.note.noteId]))).not.toThrow();
+ expect(() => getContext().init(() => bulkActionService.executeActions(actions, [note.note.noteId]))).not.toThrow();
expect(note.note.hasLabel("appliedAfterFailure")).toBe(true);
});
});
@@ -97,7 +89,7 @@ describe("bulk_actions service (real DB)", () => {
it("addLabel / updateLabelValue / renameLabel / deleteLabel", () => {
const note = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "addLabel", labelName: "color", labelValue: "red" }],
[note.note.noteId]
@@ -105,7 +97,7 @@ describe("bulk_actions service (real DB)", () => {
);
expect(note.note.getOwnedLabelValue("color")).toBe("red");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "updateLabelValue", labelName: "color", labelValue: "blue" }],
[note.note.noteId]
@@ -113,7 +105,7 @@ describe("bulk_actions service (real DB)", () => {
);
expect(note.note.getOwnedLabelValue("color")).toBe("blue");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "renameLabel", oldLabelName: "color", newLabelName: "shade" }],
[note.note.noteId]
@@ -122,7 +114,7 @@ describe("bulk_actions service (real DB)", () => {
expect(note.note.hasOwnedLabel("color")).toBe(false);
expect(note.note.getOwnedLabelValue("shade")).toBe("blue");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions([{ name: "deleteLabel", labelName: "shade" }], [note.note.noteId])
);
expect(note.note.hasOwnedLabel("shade")).toBe(false);
@@ -135,7 +127,7 @@ describe("bulk_actions service (real DB)", () => {
const targetA = createNote("root");
const targetB = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "addRelation", relationName: "link", targetNoteId: targetA.note.noteId }],
[note.note.noteId]
@@ -143,7 +135,7 @@ describe("bulk_actions service (real DB)", () => {
);
expect(note.note.getOwnedRelationValue("link")).toBe(targetA.note.noteId);
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "updateRelationTarget", relationName: "link", targetNoteId: targetB.note.noteId }],
[note.note.noteId]
@@ -151,7 +143,7 @@ describe("bulk_actions service (real DB)", () => {
);
expect(note.note.getOwnedRelationValue("link")).toBe(targetB.note.noteId);
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "renameRelation", oldRelationName: "link", newRelationName: "ref" }],
[note.note.noteId]
@@ -160,7 +152,7 @@ describe("bulk_actions service (real DB)", () => {
expect(note.note.getOwnedRelations("link").length).toBe(0);
expect(note.note.getOwnedRelationValue("ref")).toBe(targetB.note.noteId);
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions([{ name: "deleteRelation", relationName: "ref" }], [note.note.noteId])
);
expect(note.note.getOwnedRelations("ref").length).toBe(0);
@@ -171,7 +163,7 @@ describe("bulk_actions service (real DB)", () => {
it("evaluates the new title as a template with `note` in scope", () => {
const note = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "renameNote", newTitle: "Prefix - ${note.noteId}" }],
[note.note.noteId]
@@ -185,7 +177,7 @@ describe("bulk_actions service (real DB)", () => {
const note = createNote("root");
const original = note.note.title;
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "renameNote", newTitle: original }],
[note.note.noteId]
@@ -200,7 +192,7 @@ describe("bulk_actions service (real DB)", () => {
it("runs the script against the note and persists changes", () => {
const note = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "executeScript", script: "note.setLabel('scripted', 'yes')" }],
[note.note.noteId]
@@ -217,7 +209,7 @@ describe("bulk_actions service (real DB)", () => {
// mutation regardless of whether save() ran).
const note = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "executeScript", script: "note.title = 'renamed by script';\nreturn;" }],
[note.note.noteId]
@@ -233,7 +225,7 @@ describe("bulk_actions service (real DB)", () => {
const labelsBefore = note.note.getOwnedAttributes().length;
expect(() =>
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions([{ name: "executeScript", script: " " }], [note.note.noteId])
)
).not.toThrow();
@@ -245,7 +237,7 @@ describe("bulk_actions service (real DB)", () => {
it("marks the targeted note as deleted", () => {
const note = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions([{ name: "deleteNote" }], [note.note.noteId])
);
@@ -257,10 +249,10 @@ describe("bulk_actions service (real DB)", () => {
it("erases all revisions of the targeted note", () => {
const note = createNote("root");
- withContext(() => note.note.saveRevision());
+ getContext().init(() => note.note.saveRevision());
expect(note.note.getRevisions().length).toBeGreaterThan(0);
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions([{ name: "deleteRevisions" }], [note.note.noteId])
);
@@ -273,7 +265,7 @@ describe("bulk_actions service (real DB)", () => {
const note = createNote("root");
const target = createNote("root");
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "moveNote", targetParentNoteId: target.note.noteId }],
[note.note.noteId]
@@ -290,12 +282,12 @@ describe("bulk_actions service (real DB)", () => {
const target = createNote("root");
// Give the note a second branch so getParentBranches().length > 1.
- withContext(() =>
+ getContext().init(() =>
cloningService.cloneNoteToParentNote(note.note.noteId, secondParent.note.noteId)
);
expect(note.note.getParentBranches().length).toBeGreaterThan(1);
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "moveNote", targetParentNoteId: target.note.noteId }],
[note.note.noteId]
@@ -311,7 +303,7 @@ describe("bulk_actions service (real DB)", () => {
const note = createNote("root");
expect(() =>
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActions(
[{ name: "moveNote", targetParentNoteId: "doesNotExist123" }],
[note.note.noteId]
@@ -329,12 +321,12 @@ describe("bulk_actions service (real DB)", () => {
const definitionNote = createNote("root");
const target = createNote("root");
- withContext(() => {
+ getContext().init(() => {
definitionNote.note.addLabel("action", JSON.stringify({ name: "addLabel", labelName: "fromDefinition", labelValue: "1" }));
definitionNote.note.addLabel("action", JSON.stringify({ name: "addLabel", labelName: "second", labelValue: "2" }));
});
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActionsFromNote(definitionNote.note, [target.note.noteId])
);
@@ -346,7 +338,7 @@ describe("bulk_actions service (real DB)", () => {
const definitionNote = createNote("root");
const target = createNote("root");
- withContext(() => {
+ getContext().init(() => {
// Invalid JSON.
definitionNote.note.addLabel("action", "{ not valid json");
// Unknown handler name.
@@ -356,7 +348,7 @@ describe("bulk_actions service (real DB)", () => {
});
expect(() =>
- withContext(() =>
+ getContext().init(() =>
bulkActionService.executeActionsFromNote(definitionNote.note, [target.note.noteId])
)
).not.toThrow();
diff --git a/packages/trilium-core/src/services/cloning.spec.ts b/packages/trilium-core/src/services/cloning.spec.ts
index ffd8d51395..51a62b2ca5 100644
--- a/packages/trilium-core/src/services/cloning.spec.ts
+++ b/packages/trilium-core/src/services/cloning.spec.ts
@@ -8,14 +8,6 @@ import { getContext } from "./context.js";
import noteService from "./notes.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * branch.save(), branch.deleteBranch()) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -25,7 +17,7 @@ let counter = 0;
*/
function createNote(parentNoteId: string, type: "text" | "search" = "text"): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `cloning-spec-${counter}`,
@@ -41,7 +33,7 @@ describe("cloning service (real DB)", () => {
const source = createNote("root");
const target = createNote("root");
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.cloneNoteToParentNote(source.note.noteId, target.note.noteId, "my-prefix")
);
@@ -108,7 +100,7 @@ describe("cloning service (real DB)", () => {
targetParent.branch.isExpanded = false;
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.cloneNoteToBranch(source.note.noteId, targetParent.branch.branchId!, "px")
) as { success: boolean; branchId?: string };
@@ -137,7 +129,7 @@ describe("cloning service (real DB)", () => {
const source = createNote("root");
const target = createNote("root");
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.ensureNoteIsPresentInParent(source.note.noteId, target.note.noteId, "ep")
) as { branch: BBranch | null; success: boolean };
@@ -194,10 +186,10 @@ describe("cloning service (real DB)", () => {
const target = createNote("root");
// Add a second branch so removing it does not delete the note.
- withContext(() => cloningService.cloneNoteToParentNote(source.note.noteId, target.note.noteId));
+ getContext().init(() => cloningService.cloneNoteToParentNote(source.note.noteId, target.note.noteId));
expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).not.toBeNull();
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.ensureNoteIsAbsentFromParent(source.note.noteId, target.note.noteId)
);
@@ -211,7 +203,7 @@ describe("cloning service (real DB)", () => {
it("refuses to remove the only strong branch since it would delete the note", () => {
const source = createNote("root");
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.ensureNoteIsAbsentFromParent(source.note.noteId, "root")
) as { success: boolean; message?: string };
@@ -236,7 +228,7 @@ describe("cloning service (real DB)", () => {
const source = createNote("root");
const target = createNote("root");
- const present = withContext(() =>
+ const present = getContext().init(() =>
cloningService.toggleNoteInParent(true, source.note.noteId, target.note.noteId, "tp")
) as { branch: BBranch | null; success: boolean };
@@ -244,7 +236,7 @@ describe("cloning service (real DB)", () => {
expect(present.branch).not.toBeNull();
expect(becca.getBranchFromChildAndParent(source.note.noteId, target.note.noteId)).not.toBeNull();
- const absent = withContext(() =>
+ const absent = getContext().init(() =>
cloningService.toggleNoteInParent(false, source.note.noteId, target.note.noteId)
);
@@ -262,7 +254,7 @@ describe("cloning service (real DB)", () => {
const afterPos = first.branch.notePosition;
- const res = withContext(() =>
+ const res = getContext().init(() =>
cloningService.cloneNoteAfter(source.note.noteId, first.branch.branchId!)
) as { success: boolean; branchId?: string };
diff --git a/packages/trilium-core/src/services/consistency_checks.spec.ts b/packages/trilium-core/src/services/consistency_checks.spec.ts
index 22b1c02116..7fab767ec0 100644
--- a/packages/trilium-core/src/services/consistency_checks.spec.ts
+++ b/packages/trilium-core/src/services/consistency_checks.spec.ts
@@ -6,22 +6,6 @@ import syncOptions from "./sync_options.js";
import optionsService from "./options.js";
import becca_loader from "../becca/becca_loader.js";
-/**
- * Wraps a callback in CLS context and waits for it to complete.
- */
-function withContext(fn: () => void | Promise<void>): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- getContext().init(async () => {
- try {
- await fn();
- resolve();
- } catch (e) {
- reject(e);
- }
- });
- });
-}
-
let testCounter = 0;
/**
@@ -65,7 +49,7 @@ function setOption(name: string, value: string) {
describe("Consistency checks during partial sync", () => {
it("should NOT fix broken references when sync is incomplete", async () => {
- await withContext(async () => {
+ await getContext().init(async () => {
// Simulate sync being configured
setOption("syncServerHost", "https://fake-sync-server");
expect(syncOptions.isSyncSetup()).toBe(true);
@@ -103,7 +87,7 @@ describe("Consistency checks during partial sync", () => {
});
it("should fix broken references when sync is complete", async () => {
- await withContext(async () => {
+ await getContext().init(async () => {
// Simulate sync being configured and complete
setOption("syncServerHost", "https://fake-sync-server");
setOption("syncIncomplete", "false");
@@ -130,7 +114,7 @@ describe("Consistency checks during partial sync", () => {
});
it("should fix broken references when sync is not configured", async () => {
- await withContext(async () => {
+ await getContext().init(async () => {
// Ensure sync is not configured
setOption("syncServerHost", "");
expect(syncOptions.isSyncSetup()).toBe(false);
diff --git a/packages/trilium-core/src/services/content_hash.spec.ts b/packages/trilium-core/src/services/content_hash.spec.ts
index dc364abb8c..84cb3a51b5 100644
--- a/packages/trilium-core/src/services/content_hash.spec.ts
+++ b/packages/trilium-core/src/services/content_hash.spec.ts
@@ -5,23 +5,6 @@ import contentHash from "./content_hash.js";
import { getSql } from "./sql/index.js";
import { hash } from "./utils/index.js";
-/**
- * Wraps a callback in CLS context and waits for it to complete.
- * `getEntityHashes` reads the `disableSlowQueryLogging` flag from the
- * context and calls `eraseUnusedBlobs` (a write), so a context is required.
- */
-function withContext<T>(fn: () => T): Promise<T> {
- return new Promise<T>((resolve, reject) => {
- getContext().init(async () => {
- try {
- resolve(await fn());
- } catch (e) {
- reject(e);
- }
- });
- });
-}
-
let testCounter = 0;
/**
@@ -54,8 +37,8 @@ function insertEntityChange(opts: {
describe("content_hash", () => {
describe("getEntityHashes", () => {
- it("computes a per-sector hash keyed by entity name and first id char", async () => {
- const result = await withContext(() => {
+ it("computes a per-sector hash keyed by entity name and first id char", () => {
+ const result = getContext().init(() => {
insertEntityChange({ entityName: "spec_a", entityId: "Xfoo111", hash: "AAA" });
insertEntityChange({ entityName: "spec_a", entityId: "Xbar222", hash: "BBB" });
return contentHash.getEntityHashes();
@@ -73,8 +56,8 @@ describe("content_hash", () => {
expect(sectorHashes["X"]).toBe(expected);
});
- it("segments different first id chars into separate sectors", async () => {
- const result = await withContext(() => {
+ it("segments different first id chars into separate sectors", () => {
+ const result = getContext().init(() => {
insertEntityChange({ entityName: "spec_b", entityId: "1one", hash: "H1" });
insertEntityChange({ entityName: "spec_b", entityId: "2two", hash: "H2" });
return contentHash.getEntityHashes();
@@ -88,9 +71,9 @@ describe("content_hash", () => {
expect(sectorHashes["1"]).not.toBe(sectorHashes["2"]);
});
- it("incorporates the isErased flag and excludes unsynced and note_reordering rows", async () => {
+ it("incorporates the isErased flag and excludes unsynced and note_reordering rows", () => {
const erasedId = `Eerased${testCounter}`;
- const result = await withContext(() => {
+ const result = getContext().init(() => {
insertEntityChange({ entityName: "spec_c", entityId: erasedId, hash: "ER", isErased: true });
// Not synced -> must be ignored entirely.
insertEntityChange({ entityName: "spec_c", entityId: "EunsyncedZ", hash: "NO", isSynced: false });
@@ -106,8 +89,8 @@ describe("content_hash", () => {
expect(result).not.toHaveProperty("note_reordering");
});
- it("returns the seeded demo entity types from the fixture DB", async () => {
- const result = await withContext(() => contentHash.getEntityHashes());
+ it("returns the seeded demo entity types from the fixture DB", () => {
+ const result = getContext().init(() => contentHash.getEntityHashes());
// The fixture document.db is seeded with real notes/branches.
expect(result).toHaveProperty("notes");
@@ -122,8 +105,8 @@ describe("content_hash", () => {
});
describe("checkContentHashes", () => {
- it("reports no failed checks when the supplied hashes match local hashes", async () => {
- const failed = await withContext(() => {
+ it("reports no failed checks when the supplied hashes match local hashes", () => {
+ const failed = getContext().init(() => {
const local = contentHash.getEntityHashes();
return contentHash.checkContentHashes(local);
});
@@ -131,8 +114,8 @@ describe("content_hash", () => {
expect(failed).toEqual([]);
});
- it("flags a sector whose remote hash differs from the local one", async () => {
- const failed = await withContext(() => {
+ it("flags a sector whose remote hash differs from the local one", () => {
+ const failed = getContext().init(() => {
insertEntityChange({ entityName: "spec_d", entityId: "Mmismatch", hash: "LOCAL" });
const local = contentHash.getEntityHashes();
@@ -148,8 +131,8 @@ describe("content_hash", () => {
expect(mismatch?.sector).toBe("M");
});
- it("flags a sector present locally but missing entirely from the remote", async () => {
- const failed = await withContext(() => {
+ it("flags a sector present locally but missing entirely from the remote", () => {
+ const failed = getContext().init(() => {
insertEntityChange({ entityName: "spec_e", entityId: "Olocalonly", hash: "ONLY" });
const local = contentHash.getEntityHashes();
diff --git a/packages/trilium-core/src/services/encryption/password.spec.ts b/packages/trilium-core/src/services/encryption/password.spec.ts
index 60ec41c3ec..60cf9de625 100644
--- a/packages/trilium-core/src/services/encryption/password.spec.ts
+++ b/packages/trilium-core/src/services/encryption/password.spec.ts
@@ -22,15 +22,6 @@ if (isBrowserRuntime) {
vi.setConfig({ testTimeout: 60000, hookTimeout: 60000 });
}
-/**
- * Wraps a callback in a CLS context. The mutating password operations call
- * options.setOption/createOption, which save BOption entities and therefore
- * require an initialised CLS context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
describe("password service (real DB)", () => {
describe("isPasswordSet", () => {
it("reports true for the seeded fixture which already has a password", () => {
@@ -70,7 +61,7 @@ describe("password service (real DB)", () => {
expect(dataKeyBefore).toBeInstanceOf(Uint8Array);
const newPassword = "brandNewPass-123";
- const result = await withContext(() =>
+ const result = await getContext().init(() =>
passwordService.changePassword(FIXTURE_PASSWORD, newPassword)
);
expect(result.success).toBe(true);
@@ -96,7 +87,7 @@ describe("password service (real DB)", () => {
describe("resetPassword", () => {
it("clears every password-related option and makes isPasswordSet false", () => {
- const result = withContext(() => passwordService.resetPassword());
+ const result = getContext().init(() => passwordService.resetPassword());
expect(result.success).toBe(true);
expect(options.getOption("passwordVerificationHash")).toBe("");
@@ -118,7 +109,7 @@ describe("password service (real DB)", () => {
it("creates a fresh, verifiable password and a recoverable data key", async () => {
const freshPassword = "freshlySet-456";
- const result = await withContext(() => passwordService.setPassword(freshPassword));
+ const result = await getContext().init(() => passwordService.setPassword(freshPassword));
expect(result.success).toBe(true);
expect(passwordService.isPasswordSet()).toBe(true);
diff --git a/packages/trilium-core/src/services/encryption/password_encryption.spec.ts b/packages/trilium-core/src/services/encryption/password_encryption.spec.ts
index 427363bedf..d41fe1e8f1 100644
--- a/packages/trilium-core/src/services/encryption/password_encryption.spec.ts
+++ b/packages/trilium-core/src/services/encryption/password_encryption.spec.ts
@@ -22,14 +22,6 @@ if (isBrowserRuntime) {
vi.setConfig({ testTimeout: 60000, hookTimeout: 60000 });
}
-/**
- * Wraps a callback in a CLS context. setDataKey calls options.setOption, which
- * saves a BOption entity and therefore requires an initialised CLS context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
describe("password_encryption (real DB)", () => {
describe("verifyPassword", () => {
it("returns true for the seeded fixture password and false for a wrong one", async () => {
@@ -76,7 +68,7 @@ describe("password_encryption (real DB)", () => {
const oldCipher = options.getOption("encryptedDataKey");
const plainTextKey = "0123456789abcdef"; // 16 chars
- await withContext(() =>
+ await getContext().init(() =>
passwordEncryption.setDataKey(FIXTURE_PASSWORD, plainTextKey)
);
@@ -94,7 +86,7 @@ describe("password_encryption (real DB)", () => {
const otherPassword = "another-pass-789";
const rawKey = Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
- await withContext(() => passwordEncryption.setDataKey(otherPassword, rawKey));
+ await getContext().init(() => passwordEncryption.setDataKey(otherPassword, rawKey));
const recovered = (await passwordEncryption.getDataKey(otherPassword)) as Uint8Array;
expect(Array.from(recovered)).toEqual(Array.from(rawKey));
@@ -117,7 +109,7 @@ describe("password_encryption (real DB)", () => {
describe("verifyPassword without a stored hash", () => {
it("returns false for any password once passwordVerificationHash is empty", async () => {
// Kept last: clearing the stored hash is destructive for this fork's DB.
- withContext(() => options.setOption("passwordVerificationHash", ""));
+ getContext().init(() => options.setOption("passwordVerificationHash", ""));
expect(await passwordEncryption.verifyPassword(FIXTURE_PASSWORD)).toBe(false);
expect(await passwordEncryption.verifyPassword("anything")).toBe(false);
diff --git a/packages/trilium-core/src/services/entity_changes.spec.ts b/packages/trilium-core/src/services/entity_changes.spec.ts
index bcab5d60b7..e04d2d43fb 100644
--- a/packages/trilium-core/src/services/entity_changes.spec.ts
+++ b/packages/trilium-core/src/services/entity_changes.spec.ts
@@ -9,15 +9,6 @@ import getInstanceId from "./instance_id.js";
import { getContext } from "./context.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. `putEntityChange` reads the component id
- * and registers the inserted change id via the execution context, both of
- * which require an active CLS context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -57,7 +48,7 @@ describe("entity_changes service (real DB)", () => {
// No changeId provided -> a random one must be generated.
delete ec.changeId;
- withContext(() => entityChangesService.putEntityChange(ec));
+ getContext().init(() => entityChangesService.putEntityChange(ec));
const row = readRow(ec.entityName, ec.entityId);
expect(row).not.toBeNull();
@@ -75,7 +66,7 @@ describe("entity_changes service (real DB)", () => {
it("registers the inserted change id in the CLS context and bumps maxEntityChangeId", () => {
const ec = buildEntityChange();
- const idsAfter = withContext(() => {
+ const idsAfter = getContext().init(() => {
entityChangesService.putEntityChange(ec);
return getContext().get<number[]>("entityChangeIds") ?? [];
});
@@ -88,7 +79,7 @@ describe("entity_changes service (real DB)", () => {
it("falls back to the 'NA' componentId when none is available in the context", () => {
const ec = buildEntityChange();
- withContext(() => entityChangesService.putEntityChange(ec));
+ getContext().init(() => entityChangesService.putEntityChange(ec));
const row = readRow(ec.entityName, ec.entityId)!;
expect(row.componentId).toBe("NA");
@@ -102,7 +93,7 @@ describe("entity_changes service (real DB)", () => {
isSynced: false
});
- withContext(() => entityChangesService.putEntityChange(ec));
+ getContext().init(() => entityChangesService.putEntityChange(ec));
const row = readRow(ec.entityName, ec.entityId)!;
expect(row.changeId).toBe("fixedChangeId");
@@ -116,7 +107,7 @@ describe("entity_changes service (real DB)", () => {
it("persists the supplied instance id rather than the local one", () => {
const ec = buildEntityChange();
- withContext(() => entityChangesService.putEntityChangeWithInstanceId(ec, "remoteInst1"));
+ getContext().init(() => entityChangesService.putEntityChangeWithInstanceId(ec, "remoteInst1"));
const row = readRow(ec.entityName, ec.entityId)!;
expect(row.instanceId).toBe("remoteInst1");
@@ -127,7 +118,7 @@ describe("entity_changes service (real DB)", () => {
it("ignores the incoming changeId and generates a fresh one", () => {
const ec = buildEntityChange({ changeId: "originalChange" });
- withContext(() => entityChangesService.putEntityChangeWithForcedChange(ec));
+ getContext().init(() => entityChangesService.putEntityChangeWithForcedChange(ec));
const row = readRow(ec.entityName, ec.entityId)!;
expect(typeof row.changeId).toBe("string");
@@ -142,7 +133,7 @@ describe("entity_changes service (real DB)", () => {
instanceId: "shouldBeDropped"
});
- withContext(() => entityChangesService.putEntityChangeForOtherInstances(ec));
+ getContext().init(() => entityChangesService.putEntityChangeForOtherInstances(ec));
const row = readRow(ec.entityName, ec.entityId)!;
// Both fields were reset to null and then defaulted at insert time.
@@ -155,7 +146,7 @@ describe("entity_changes service (real DB)", () => {
it("writes a synced note_reordering change and emits ENTITY_CHANGED with the branch map", () => {
const emitSpy = vi.spyOn(events, "emit");
- withContext(() => entityChangesService.putNoteReorderingEntityChange("root", "comp-reorder"));
+ getContext().init(() => entityChangesService.putNoteReorderingEntityChange("root", "comp-reorder"));
const row = readRow("note_reordering", "root")!;
expect(row).not.toBeNull();
@@ -183,7 +174,7 @@ describe("entity_changes service (real DB)", () => {
// Inserting a new change advances the in-memory counter past the
// previous max, and recalculation converges back to the DB value.
const ec = buildEntityChange();
- withContext(() => entityChangesService.putEntityChange(ec));
+ getContext().init(() => entityChangesService.putEntityChange(ec));
expect(entityChangesService.getMaxEntityChangeId()).toBeGreaterThan(dbMax);
entityChangesService.recalculateMaxEntityChangeId();
@@ -210,7 +201,7 @@ describe("entity_changes service (real DB)", () => {
);
expect(before.length).toBeGreaterThan(0);
- withContext(() => entityChangesService.addEntityChangesForSector("options", sector));
+ getContext().init(() => entityChangesService.addEntityChangesForSector("options", sector));
const after = sql.getColumn<string>(
"SELECT changeId FROM entity_changes WHERE entityName = 'options' AND SUBSTR(entityId, 1, 1) = ?",
@@ -230,13 +221,13 @@ describe("entity_changes service (real DB)", () => {
// Seed an erased change that must survive the rebuild.
const erased = buildEntityChange({ isErased: true });
- withContext(() => entityChangesService.putEntityChange(erased));
+ getContext().init(() => entityChangesService.putEntityChange(erased));
const erasedCountBefore = sql.getValue<number>(
"SELECT COUNT(1) FROM entity_changes WHERE isErased = 1"
);
- withContext(() => entityChangesService.fillAllEntityChanges());
+ getContext().init(() => entityChangesService.fillAllEntityChanges());
// Every note in becca must now have a corresponding (non-erased) change.
const notesWithoutChange = sql.getValue<number>(`
diff --git a/packages/trilium-core/src/services/erase.spec.ts b/packages/trilium-core/src/services/erase.spec.ts
index e4ca9d8038..96410477ec 100644
--- a/packages/trilium-core/src/services/erase.spec.ts
+++ b/packages/trilium-core/src/services/erase.spec.ts
@@ -7,15 +7,6 @@ import eraseService from "./erase.js";
import noteService from "./notes.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * markAsDeleted, setContent) require CLS to be initialised. The erase
- * service itself also opens a transaction, which needs the context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -25,7 +16,7 @@ let counter = 0;
*/
function createNote(content = "<p>hello</p>"): BNote {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: `erase-spec-${counter}`,
@@ -53,11 +44,11 @@ describe("erase service (real DB)", () => {
const noteId = note.noteId;
const branch = note.getParentBranches()[0];
const branchId = branch.branchId!;
- const attribute = withContext(() => note.addLabel("eraseMe", "v"));
+ const attribute = getContext().init(() => note.addLabel("eraseMe", "v"));
const attributeId = attribute.attributeId;
const deleteId = `del-${counter}`;
- withContext(() => {
+ getContext().init(() => {
attribute.markAsDeleted(deleteId);
branch.markAsDeleted(deleteId);
note.markAsDeleted(deleteId);
@@ -66,7 +57,7 @@ describe("erase service (real DB)", () => {
// Sanity: rows still physically present after a soft delete.
expect(rowCount("notes", "noteId", noteId)).toBe(1);
- withContext(() => eraseService.eraseNotesWithDeleteId(deleteId));
+ getContext().init(() => eraseService.eraseNotesWithDeleteId(deleteId));
// The physical rows are gone.
expect(rowCount("notes", "noteId", noteId)).toBe(0);
@@ -82,17 +73,17 @@ describe("erase service (real DB)", () => {
it("erases a soft-deleted attachment carrying a matching deleteId", () => {
const note = createNote();
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "att", content: "data" })
);
const attachmentId = attachment.attachmentId;
const deleteId = `del-att-${counter}`;
- withContext(() => attachment.markAsDeleted(deleteId));
+ getContext().init(() => attachment.markAsDeleted(deleteId));
expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(1);
- withContext(() => eraseService.eraseNotesWithDeleteId(deleteId));
+ getContext().init(() => eraseService.eraseNotesWithDeleteId(deleteId));
expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(0);
expect(entityChangeFor("attachments", attachmentId)?.isErased).toBe(1);
@@ -102,7 +93,7 @@ describe("erase service (real DB)", () => {
const note = createNote();
const noteId = note.noteId;
- withContext(() => eraseService.eraseNotesWithDeleteId("nonexistent-delete-id"));
+ getContext().init(() => eraseService.eraseNotesWithDeleteId("nonexistent-delete-id"));
// The live note is untouched.
expect(rowCount("notes", "noteId", noteId)).toBe(1);
@@ -116,11 +107,11 @@ describe("erase service (real DB)", () => {
const branchId = note.getParentBranches()[0].branchId!;
// deleteNote soft-deletes the note, its branch and attributes.
- withContext(() => note.deleteNote());
+ getContext().init(() => note.deleteNote());
expect(rowCount("notes", "noteId", noteId)).toBe(1);
- withContext(() => eraseService.eraseDeletedNotesNow());
+ getContext().init(() => eraseService.eraseDeletedNotesNow());
expect(rowCount("notes", "noteId", noteId)).toBe(0);
expect(rowCount("branches", "branchId", branchId)).toBe(0);
@@ -131,7 +122,7 @@ describe("erase service (real DB)", () => {
const note = createNote();
const noteId = note.noteId;
- withContext(() => eraseService.eraseDeletedNotesNow());
+ getContext().init(() => eraseService.eraseDeletedNotesNow());
expect(rowCount("notes", "noteId", noteId)).toBe(1);
});
@@ -142,7 +133,7 @@ describe("erase service (real DB)", () => {
// Insert an orphan blob with a matching entity_changes record. It is
// referenced by nothing, so it qualifies as unused.
const blobId = `orphanBlob-${++counter}`;
- withContext(() => {
+ getContext().init(() => {
getSql().execute(
"INSERT INTO blobs (blobId, content, dateModified, utcDateModified) VALUES (?, ?, ?, ?)",
[blobId, "junk", "2020-01-01 00:00:00.000+0000", "2020-01-01 00:00:00.000Z"]
@@ -155,7 +146,7 @@ describe("erase service (real DB)", () => {
);
});
- withContext(() => eraseService.eraseUnusedBlobs());
+ getContext().init(() => eraseService.eraseUnusedBlobs());
// Blobs are purged completely rather than marked erased.
expect(rowCount("blobs", "blobId", blobId)).toBe(0);
@@ -169,7 +160,7 @@ describe("erase service (real DB)", () => {
]);
expect(blobId).toBeTruthy();
- withContext(() => eraseService.eraseUnusedBlobs());
+ getContext().init(() => eraseService.eraseUnusedBlobs());
expect(rowCount("blobs", "blobId", blobId)).toBe(1);
});
@@ -178,21 +169,21 @@ describe("erase service (real DB)", () => {
describe("eraseUnusedAttachmentsNow", () => {
it("erases an attachment scheduled for erasure in the past", () => {
const note = createNote();
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "sched", content: "x" })
);
const attachmentId = attachment.attachmentId;
// Mark the attachment as scheduled for erasure well in the past so it
// falls before the now-based cutoff.
- withContext(() =>
+ getContext().init(() =>
getSql().execute(
"UPDATE attachments SET utcDateScheduledForErasureSince = ? WHERE attachmentId = ?",
["2000-01-01 00:00:00.000Z", attachmentId]
)
);
- withContext(() => eraseService.eraseUnusedAttachmentsNow());
+ getContext().init(() => eraseService.eraseUnusedAttachmentsNow());
expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(0);
expect(entityChangeFor("attachments", attachmentId)?.isErased).toBe(1);
@@ -200,12 +191,12 @@ describe("erase service (real DB)", () => {
it("does not erase an attachment that is not scheduled for erasure", () => {
const note = createNote();
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({ role: "file", mime: "text/plain", title: "keep", content: "x" })
);
const attachmentId = attachment.attachmentId;
- withContext(() => eraseService.eraseUnusedAttachmentsNow());
+ getContext().init(() => eraseService.eraseUnusedAttachmentsNow());
expect(rowCount("attachments", "attachmentId", attachmentId)).toBe(1);
});
@@ -216,7 +207,7 @@ describe("erase service (real DB)", () => {
const note = createNote();
const noteId = note.noteId;
- withContext(() => {
+ getContext().init(() => {
eraseService.eraseAttachments([]);
eraseService.eraseRevisions([]);
});
diff --git a/packages/trilium-core/src/services/export/opml.spec.ts b/packages/trilium-core/src/services/export/opml.spec.ts
index 38aa1a3027..638bc03f83 100644
--- a/packages/trilium-core/src/services/export/opml.spec.ts
+++ b/packages/trilium-core/src/services/export/opml.spec.ts
@@ -9,14 +9,6 @@ import sql_init from "../sql_init.js";
import TaskContext from "../task_context.js";
import opml from "./opml.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * addLabel) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -29,7 +21,7 @@ function createNote(
overrides: Partial<{ title: string; content: string; type: BNote["type"]; mime: string }> = {}
): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: overrides.title ?? `opml-export-spec-${counter}`,
@@ -174,7 +166,7 @@ describe("exportToOpml (real DB)", () => {
const { note: parent, branch } = createNote("root", { title: "Export parent", content: "" });
createNote(parent.noteId, { title: "Kept child", content: "<p>keep</p>" });
const { note: excluded } = createNote(parent.noteId, { title: "Excluded child", content: "<p>no</p>" });
- withContext(() => excluded.addLabel("excludeFromExport"));
+ getContext().init(() => excluded.addLabel("excludeFromExport"));
const body = runExport(branch, "2.0").body;
@@ -186,7 +178,7 @@ describe("exportToOpml (real DB)", () => {
it("includes the branch prefix in the title and the download filename", () => {
const { note, branch } = createNote("root", { title: "Prefixed", content: "" });
- withContext(() => {
+ getContext().init(() => {
branch.prefix = "Pre";
branch.save();
});
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index 5eddaa156d..d028f4e1f6 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -16,10 +16,6 @@ import zip from "./zip.js";
// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.
const isBrowserRuntime = typeof window !== "undefined";
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -32,7 +28,7 @@ function createNote(
overrides: Partial<{ title: string; content: string; type: BNote["type"]; mime: string }> = {}
): { note: BNote; branch: BBranch } {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: overrides.title ?? `zip-spec-${counter}`,
@@ -199,7 +195,7 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
// to save but must be filtered out of the export meta.
const { note: outsider } = createNote("root", { title: "Outsider", content: "<p>o</p>" });
const { note } = createNote("root", { title: "Attributed", content: "<p>x</p>" });
- withContext(() => {
+ getContext().init(() => {
note.addLabel("myLabel", "labelValue");
// Relation to "root" is a named noteId and is preserved.
note.addRelation("rootRel", "root");
@@ -223,7 +219,7 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
const { note: parent } = createNote("root", { title: "WithExcluded", content: "" });
const { note: kept } = createNote(parent.noteId, { title: "Kept", content: "<p>kept</p>" });
const { note: excluded } = createNote(parent.noteId, { title: "Excluded", content: "<p>no</p>" });
- withContext(() => excluded.addLabel("excludeFromExport"));
+ getContext().init(() => excluded.addLabel("excludeFromExport"));
const branch = parent.getParentBranches()[0];
const { entries } = await exportSubtree(branch, "html");
@@ -242,7 +238,7 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
// Clone the note into a second folder inside the same exported subtree.
const cloningService = (await import("../cloning.js")).default;
- const cloneRes = withContext(() => cloningService.cloneNoteToParentNote(original.noteId, folderB.noteId));
+ const cloneRes = getContext().init(() => cloningService.cloneNoteToParentNote(original.noteId, folderB.noteId));
expect(cloneRes.success).toBe(true);
const branch = parent.getParentBranches()[0];
@@ -282,7 +278,7 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
const { note } = createNote("root", { title: "FileExport", content: "<p>to file</p>" });
const zipPath = join(tempDir, `export-${note.noteId}.zip`);
- await withContext(() => zip.exportToZipFile(note.noteId, "html", zipPath));
+ await getContext().init(() => zip.exportToZipFile(note.noteId, "html", zipPath));
const buffer = readFileSync(zipPath);
const entries = await readArchive(buffer);
@@ -296,7 +292,7 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
it("throws a ValidationError for a non-existent note", async () => {
await expect(
- withContext(() => zip.exportToZipFile("missingNoteId123", "html", join(tempDir, "never.zip")))
+ getContext().init(() => zip.exportToZipFile("missingNoteId123", "html", join(tempDir, "never.zip")))
).rejects.toThrow(/not found/);
});
});
diff --git a/packages/trilium-core/src/services/hidden_subtree.spec.ts b/packages/trilium-core/src/services/hidden_subtree.spec.ts
index 79a2fc1d4f..92d082cce0 100644
--- a/packages/trilium-core/src/services/hidden_subtree.spec.ts
+++ b/packages/trilium-core/src/services/hidden_subtree.spec.ts
@@ -21,7 +21,7 @@ import noteService from "./notes.js";
* deprecated entries live directly under "_options" in the definition.
*/
function materialiseDeprecatedNote(noteId: string) {
- withContext(() =>
+ getContext().init(() =>
noteService.createNewNote({
noteId,
title: `deprecated-${noteId}`,
@@ -33,16 +33,8 @@ function materialiseDeprecatedNote(noteId: string) {
);
}
-/**
- * Entity mutations performed by checkHiddenSubtree (createNewNote, save,
- * markAsDeleted) require an initialised CLS context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
function checkHiddenSubtree(force = false) {
- return withContext(() => hiddenSubtreeService.checkHiddenSubtree(force));
+ return getContext().init(() => hiddenSubtreeService.checkHiddenSubtree(force));
}
describe("hidden_subtree (real DB)", () => {
@@ -126,7 +118,7 @@ describe("hidden_subtree (real DB)", () => {
expect(hidden.getOwnedLabelValue("docName")).toBe("hidden");
// Inject a stray owned label, then re-run the integrity check.
- withContext(() => {
+ getContext().init(() => {
hidden.addLabel("strayLabelXyz", "should-be-removed");
});
expect(hidden.hasOwnedLabel("strayLabelXyz")).toBe(true);
@@ -144,7 +136,7 @@ describe("hidden_subtree (real DB)", () => {
const docNameAttr = hidden.getOwnedAttributes("label", "docName")[0];
expect(docNameAttr).toBeDefined();
- withContext(() => {
+ getContext().init(() => {
docNameAttr.value = "tampered";
docNameAttr.save();
});
@@ -204,7 +196,7 @@ describe("hidden_subtree (real DB)", () => {
// Declared as a book.
expect(options.type).toBe("book");
- withContext(() => {
+ getContext().init(() => {
options.type = "text";
options.save();
});
diff --git a/packages/trilium-core/src/services/image.spec.ts b/packages/trilium-core/src/services/image.spec.ts
index 9459c1428d..e82f804561 100644
--- a/packages/trilium-core/src/services/image.spec.ts
+++ b/packages/trilium-core/src/services/image.spec.ts
@@ -20,10 +20,6 @@ import protectedSessionService from "./protected_session.js";
let counter = 0;
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
const fakeBuffer = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
/**
@@ -59,7 +55,7 @@ describe("image service (real DB)", () => {
it("creates an image note under the parent and returns the upload metadata synchronously", () => {
counter++;
const originalName = `pic ${counter}.png`;
- const result = withContext(() =>
+ const result = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, originalName, false)
);
@@ -82,13 +78,13 @@ describe("image service (real DB)", () => {
it("trims an over-long file name to 'image' only when trimFilename is set", () => {
const longName = "a".repeat(45) + ".png";
- const trimmed = withContext(() =>
+ const trimmed = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, longName, false, true)
);
expect(trimmed.fileName).toBe("image");
expect(becca.getNote(trimmed.noteId)!.getOwnedLabelValue("originalFileName")).toBe("image");
- const untrimmed = withContext(() =>
+ const untrimmed = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, longName, false, false)
);
expect(untrimmed.fileName).toBe(longName);
@@ -96,7 +92,7 @@ describe("image service (real DB)", () => {
it("throws when the parent note does not exist", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
imageService.saveImage("missingParent123", fakeBuffer, "x.png", false)
)
).toThrow("Unable to find parent note.");
@@ -106,7 +102,7 @@ describe("image service (real DB)", () => {
stubProcessImage({ ext: "png" });
counter++;
- const result = withContext(() =>
+ const result = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, `async-${counter}.png`, true)
);
await flushAsync();
@@ -121,7 +117,7 @@ describe("image service (real DB)", () => {
counter++;
const baseName = `nodotsvg${counter}`;
- const result = withContext(() =>
+ const result = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, baseName, true)
);
await flushAsync();
@@ -138,7 +134,7 @@ describe("image service (real DB)", () => {
/** Reuse saveImage to obtain a real, persisted note to attach to. */
function createTargetNote(): BNote {
counter++;
- const { noteId } = withContext(() =>
+ const { noteId } = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, `host-${counter}.png`, false)
);
return becca.getNote(noteId)!;
@@ -147,7 +143,7 @@ describe("image service (real DB)", () => {
it("creates an image attachment on the note and returns its title synchronously", () => {
const host = createTargetNote();
- const att = withContext(() =>
+ const att = getContext().init(() =>
imageService.saveImageToAttachment(host.noteId, fakeBuffer, "att.png", false)
);
@@ -162,7 +158,7 @@ describe("image service (real DB)", () => {
it("throws when the owner note does not exist", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
imageService.saveImageToAttachment("missingNote123", fakeBuffer, "x.png", false)
)
).toThrow();
@@ -172,7 +168,7 @@ describe("image service (real DB)", () => {
const host = createTargetNote();
stubProcessImage({ ext: "jpg" });
- const att = withContext(() =>
+ const att = getContext().init(() =>
imageService.saveImageToAttachment(host.noteId, fakeBuffer, "nodotattach", false)
);
await flushAsync();
@@ -187,7 +183,7 @@ describe("image service (real DB)", () => {
describe("updateImage", () => {
it("throws when the note does not exist", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
imageService.updateImage("missingNote456", fakeBuffer, "x.png")
)
).toThrow("Unable to find note.");
@@ -202,7 +198,7 @@ describe("image service (real DB)", () => {
// Start from a freshly created image note we can mutate.
counter++;
- const { noteId } = withContext(() =>
+ const { noteId } = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, `update-${counter}.png`, false)
);
await flushAsync();
@@ -221,7 +217,7 @@ describe("image service (real DB)", () => {
const revisionSpy = vi.spyOn(becca.getNote(noteId)!, "saveRevision");
- withContext(() => imageService.updateImage(noteId, fakeBuffer, "renamed.png"));
+ getContext().init(() => imageService.updateImage(noteId, fakeBuffer, "renamed.png"));
await flushAsync();
const note = becca.getNote(noteId)!;
@@ -255,7 +251,7 @@ describe("image service (real DB)", () => {
// Session available -> protected parent yields a protected child.
sessionSpy.mockReturnValue(true);
counter++;
- const whenAvailable = withContext(() =>
+ const whenAvailable = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, `prot-on-${counter}.png`, false)
);
expect(becca.getNote(whenAvailable.noteId)!.isProtected).toBe(true);
@@ -268,7 +264,7 @@ describe("image service (real DB)", () => {
// unprotected child, proving the result tracks the session mock.
sessionSpy.mockReturnValue(false);
counter++;
- const whenUnavailable = withContext(() =>
+ const whenUnavailable = getContext().init(() =>
imageService.saveImage("root", fakeBuffer, `prot-off-${counter}.png`, false)
);
expect(becca.getNote(whenUnavailable.noteId)!.isProtected).toBe(false);
diff --git a/packages/trilium-core/src/services/import/opml.spec.ts b/packages/trilium-core/src/services/import/opml.spec.ts
index 53e8706b8f..768d10c551 100644
--- a/packages/trilium-core/src/services/import/opml.spec.ts
+++ b/packages/trilium-core/src/services/import/opml.spec.ts
@@ -9,15 +9,6 @@ import TaskContext from "../task_context.js";
import { decodeUtf8 } from "../utils/binary.js";
import opml from "./opml.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote) require
- * CLS to be initialised. The callback may return a Promise, which is passed
- * straight through.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -26,7 +17,7 @@ let counter = 0;
*/
function createParent(): BNote {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: `opml-spec-parent-${counter}`,
@@ -42,7 +33,7 @@ function getTaskContext() {
}
function runImport(xml: string, parent: BNote) {
- return withContext(() => opml.importOpml(getTaskContext(), xml, parent));
+ return getContext().init(() => opml.importOpml(getTaskContext(), xml, parent));
}
describe("importOpml (real DB)", () => {
diff --git a/packages/trilium-core/src/services/in_app_help.spec.ts b/packages/trilium-core/src/services/in_app_help.spec.ts
index e57da13820..0cc6f51f92 100644
--- a/packages/trilium-core/src/services/in_app_help.spec.ts
+++ b/packages/trilium-core/src/services/in_app_help.spec.ts
@@ -10,10 +10,6 @@ import {
initInAppHelp
} from "./in_app_help.js";
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
/** Minimal concrete provider so the abstract `cleanUpHelp` logic can be exercised. */
class TestHelpProvider extends InAppHelpProvider {
@@ -30,7 +26,7 @@ const noteService = (await import("./notes.js")).default;
/** Creates a note with a forced id under the given parent within the help subtree. */
function createHelpNote(noteId: string, parentNoteId: string) {
- return withContext(
+ return getContext().init(
() =>
noteService.createNewNote({
noteId,
@@ -92,7 +88,7 @@ describe("in_app_help - cleanUpHelp", () => {
}
];
- withContext(() => cleanUpHelp(definition));
+ getContext().init(() => cleanUpHelp(definition));
// The stale note is gone; the kept notes (incl. nested child and root) survive.
expect(becca.getNote("_helpStale")?.isDeleted ?? true).toBe(true);
@@ -104,10 +100,10 @@ describe("in_app_help - cleanUpHelp", () => {
it("is a no-op when the _help subtree does not exist", () => {
// Remove the whole _help subtree, so becca.getNote("_help") is null and
// the recursive flattener hits its empty-note short-circuit.
- withContext(() => becca.getNote("_help")?.deleteNote());
+ getContext().init(() => becca.getNote("_help")?.deleteNote());
expect(becca.getNote("_help")).toBeNull();
- expect(() => withContext(() => cleanUpHelp([]))).not.toThrow();
+ expect(() => getContext().init(() => cleanUpHelp([]))).not.toThrow();
});
});
diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.ts
index 35db73a7ac..76c845abbb 100644
--- a/packages/trilium-core/src/services/notes.spec.ts
+++ b/packages/trilium-core/src/services/notes.spec.ts
@@ -15,14 +15,6 @@ import { getSql } from "./sql/index.js";
* write paths (note creation, update, duplication) which that spec stubs out.
*/
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * setContent, BAttribute.save(), etc.) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -35,7 +27,7 @@ function createNote(parentNoteId: string, overrides: Partial<Parameters<typeof n
branch: BBranch;
} {
counter++;
- return withContext(() =>
+ return getContext().init(() =>
noteService.createNewNote({
parentNoteId,
title: `notes-spec-${counter}`,
@@ -97,7 +89,7 @@ describe("notes service (real DB)", () => {
it("throws when the content is null/undefined", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: "spec-null-content",
@@ -118,7 +110,7 @@ describe("notes service (real DB)", () => {
it("inherits the template's mime and adds a template relation when creating from a template", () => {
const template = createNote("root", { title: "spec-template", content: "<p>tmpl</p>" });
// Give the template a non-default mime so we can verify inheritance.
- withContext(() => {
+ getContext().init(() => {
template.note.mime = "text/special";
template.note.save();
});
@@ -138,7 +130,7 @@ describe("notes service (real DB)", () => {
it("defaults the type from the parent and creates the note for 'into'", () => {
const parent = createNote("root", { title: "spec-into-parent" });
- const { note, branch } = withContext(() =>
+ const { note, branch } = getContext().init(() =>
noteService.createNewNoteWithTarget("into", undefined, {
parentNoteId: parent.note.noteId,
title: "spec-into-child",
@@ -156,7 +148,7 @@ describe("notes service (real DB)", () => {
const parent = createNote("root", { title: "spec-after-parent" });
const first = createNote(parent.note.noteId, { title: "spec-after-first" });
- const { branch } = withContext(() =>
+ const { branch } = getContext().init(() =>
noteService.createNewNoteWithTarget("after", first.branch.branchId, {
parentNoteId: parent.note.noteId,
title: "spec-after-second",
@@ -170,7 +162,7 @@ describe("notes service (real DB)", () => {
it("throws on an unknown target", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
noteService.createNewNoteWithTarget("sideways" as "into", undefined, {
parentNoteId: "root",
title: "spec-bad-target",
@@ -189,7 +181,7 @@ describe("notes service (real DB)", () => {
const content = `<p>link <a href="http://example.com/#root/${target.note.noteId}">here</a></p>`;
- const { content: newContent } = withContext(() => saveLinks(source.note, content));
+ const { content: newContent } = getContext().init(() => saveLinks(source.note, content));
// Absolute href is rewritten to a relative #root reference.
expect(newContent).toContain(`href="#root/${target.note.noteId}"`);
@@ -205,11 +197,11 @@ describe("notes service (real DB)", () => {
const source = createNote("root", { title: "spec-unused-source" });
// First, create the link.
- withContext(() => saveLinks(source.note, `<a href="#root/${target.note.noteId}">x</a>`));
+ getContext().init(() => saveLinks(source.note, `<a href="#root/${target.note.noteId}">x</a>`));
expect(source.note.getRelations().some((r) => r.name === "internalLink")).toBe(true);
// Then save content without the link; the relation should be marked deleted.
- withContext(() => saveLinks(source.note, "<p>no links anymore</p>"));
+ getContext().init(() => saveLinks(source.note, "<p>no links anymore</p>"));
expect(source.note.getRelations().some((r) => r.name === "internalLink" && !r.isDeleted)).toBe(false);
});
@@ -222,7 +214,7 @@ describe("notes service (real DB)", () => {
});
const content = `<a href="#root/root">x</a>`;
- const res = withContext(() => saveLinks(code.note, content));
+ const res = getContext().init(() => saveLinks(code.note, content));
expect(res).toEqual({ forceFrontendReload: false, content });
expect(code.note.getRelations().some((r) => r.name === "internalLink")).toBe(false);
@@ -235,7 +227,7 @@ describe("notes service (real DB)", () => {
const pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
const content = `<p><a href="data:image/png;base64,${pngBase64}">my &amp; file.png</a></p>`;
- const { content: newContent } = withContext(() => saveLinks(source.note, content));
+ const { content: newContent } = getContext().init(() => saveLinks(source.note, content));
const attachments = source.note.getAttachments().filter((a) => a.role === "file");
expect(attachments).toHaveLength(1);
@@ -255,7 +247,7 @@ describe("notes service (real DB)", () => {
const note = createNote("root", { title: "spec-update", content: "<p>old</p>" }).note;
const content = `<p>new <a href="#root/${target.note.noteId}">link</a></p>`;
- withContext(() => noteService.updateNoteData(note.noteId, content));
+ getContext().init(() => noteService.updateNoteData(note.noteId, content));
expect(note.getContent()).toContain("new");
expect(
@@ -264,7 +256,7 @@ describe("notes service (real DB)", () => {
});
it("throws when the note is not available", () => {
- expect(() => withContext(() => noteService.updateNoteData("doesNotExist99", "<p>x</p>"))).toThrow(
+ expect(() => getContext().init(() => noteService.updateNoteData("doesNotExist99", "<p>x</p>"))).toThrow(
/not available for change/
);
});
@@ -276,9 +268,9 @@ describe("notes service (real DB)", () => {
const child = createNote(root.note.noteId, { title: "spec-dup-child" });
// Add a relation from the parent to its own child so we can verify remapping.
- withContext(() => root.note.setRelation("myRel", child.note.noteId));
+ getContext().init(() => root.note.setRelation("myRel", child.note.noteId));
- const { note: dupNote } = withContext(() => noteService.duplicateSubtree(root.note.noteId, "root"));
+ const { note: dupNote } = getContext().init(() => noteService.duplicateSubtree(root.note.noteId, "root"));
// A brand new note id is allocated.
expect(dupNote.noteId).not.toBe(root.note.noteId);
@@ -293,7 +285,7 @@ describe("notes service (real DB)", () => {
});
it("refuses to duplicate the root note", () => {
- expect(() => withContext(() => noteService.duplicateSubtree("root", "root"))).toThrow(
+ expect(() => getContext().init(() => noteService.duplicateSubtree("root", "root"))).toThrow(
/Duplicating root is not possible/
);
});
@@ -310,11 +302,11 @@ describe("notes service (real DB)", () => {
beforeAll(() => {
originalInterval = optionService.getOption("revisionSnapshotTimeInterval");
- withContext(() => optionService.setOption("revisionSnapshotTimeInterval", "0"));
+ getContext().init(() => optionService.setOption("revisionSnapshotTimeInterval", "0"));
});
afterAll(() => {
- withContext(() => optionService.setOption("revisionSnapshotTimeInterval", originalInterval));
+ getContext().init(() => optionService.setOption("revisionSnapshotTimeInterval", originalInterval));
});
function revisionCount(note: BNote): number {
@@ -328,7 +320,7 @@ describe("notes service (real DB)", () => {
}).note;
const before = revisionCount(note);
- withContext(() => noteService.saveRevisionIfNeeded(note));
+ getContext().init(() => noteService.saveRevisionIfNeeded(note));
const after = revisionCount(note);
expect(after).toBe(before + 1);
@@ -344,7 +336,7 @@ describe("notes service (real DB)", () => {
}).note;
const before = revisionCount(note);
- withContext(() => noteService.saveRevisionIfNeeded(note));
+ getContext().init(() => noteService.saveRevisionIfNeeded(note));
const after = revisionCount(note);
expect(after).toBe(before);
diff --git a/packages/trilium-core/src/services/options.spec.ts b/packages/trilium-core/src/services/options.spec.ts
index 98ace814fb..6ddaa3de64 100644
--- a/packages/trilium-core/src/services/options.spec.ts
+++ b/packages/trilium-core/src/services/options.spec.ts
@@ -5,14 +5,6 @@ import { getContext } from "./context.js";
import optionService from "./options.js";
import { getSql } from "./sql/index.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (BOption.save() via
- * setOption/createOption) emit entity-change records which require CLS.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/** Returns an option name that is guaranteed unique within this shared fixture DB. */
@@ -52,21 +44,21 @@ describe("options service (real DB)", () => {
describe("getOptionInt", () => {
it("parses an integer-valued option", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "42", false));
+ getContext().init(() => optionService.createOption(name as any, "42", false));
expect(optionService.getOptionInt(name as any)).toBe(42);
});
it("returns the supplied default when the value cannot be parsed", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "not-a-number", false));
+ getContext().init(() => optionService.createOption(name as any, "not-a-number", false));
expect(optionService.getOptionInt(name as any, 7)).toBe(7);
});
it("throws when the value cannot be parsed and no default is given", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "garbage", false));
+ getContext().init(() => optionService.createOption(name as any, "garbage", false));
expect(() => optionService.getOptionInt(name as any)).toThrow(/into integer/);
});
@@ -76,7 +68,7 @@ describe("options service (real DB)", () => {
it("parses 'true' and 'false' into booleans", () => {
const trueName = uniqueName();
const falseName = uniqueName();
- withContext(() => {
+ getContext().init(() => {
optionService.createOption(trueName as any, "true", false);
optionService.createOption(falseName as any, "false", false);
});
@@ -87,7 +79,7 @@ describe("options service (real DB)", () => {
it("throws for a value that is neither 'true' nor 'false'", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "yes", false));
+ getContext().init(() => optionService.createOption(name as any, "yes", false));
expect(() => optionService.getOptionBool(name as any)).toThrow(/into boolean/);
});
@@ -98,7 +90,7 @@ describe("options service (real DB)", () => {
const syncedName = uniqueName();
const localName = uniqueName();
- withContext(() => {
+ getContext().init(() => {
optionService.createOption(syncedName as any, "synced-value", true);
optionService.createOption(localName as any, "local-value", false);
});
@@ -115,9 +107,9 @@ describe("options service (real DB)", () => {
describe("setOption", () => {
it("updates the value of an existing option", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "initial", false));
+ getContext().init(() => optionService.createOption(name as any, "initial", false));
- withContext(() => optionService.setOption(name as any, "changed"));
+ getContext().init(() => optionService.setOption(name as any, "changed"));
expect(optionService.getOption(name as any)).toBe("changed");
expect(readFromDb(name)).toBe("changed");
@@ -126,7 +118,7 @@ describe("options service (real DB)", () => {
it("creates the option (local-only) when it does not yet exist", () => {
const name = uniqueName();
- withContext(() => optionService.setOption(name as any, "created-by-set"));
+ getContext().init(() => optionService.setOption(name as any, "created-by-set"));
expect(optionService.getOption(name as any)).toBe("created-by-set");
expect(becca.getOption(name)?.isSynced).toBe(false);
@@ -137,7 +129,7 @@ describe("options service (real DB)", () => {
describe("getOptions / getOptionMap", () => {
it("includes a freshly created option in both the list and the map", () => {
const name = uniqueName();
- withContext(() => optionService.createOption(name as any, "in-collection", false));
+ getContext().init(() => optionService.createOption(name as any, "in-collection", false));
const all = optionService.getOptions();
expect(all.some((o) => o.name === name && o.value === "in-collection")).toBe(true);
diff --git a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
index bdce882d41..c0999c1543 100644
--- a/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
+++ b/packages/trilium-core/src/services/search/expressions/ocr_content.spec.ts
@@ -9,14 +9,6 @@ import NoteSet from "../note_set.js";
import SearchContext from "../search_context.js";
import OCRContentExpression from "./ocr_content.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * saveAttachment, setContent) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/**
@@ -26,7 +18,7 @@ let counter = 0;
*/
function createNoteWithOcrText(ocrText: string): BNote {
counter++;
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
// Unique content per note: blobs are keyed by content hash, so
@@ -49,7 +41,7 @@ function createNoteWithOcrText(ocrText: string): BNote {
*/
function createNoteWithOcrAttachment(ocrText: string): BNote {
counter++;
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
noteService.createNewNote({
parentNoteId: "root",
title: `ocr-spec-${counter}`,
@@ -58,7 +50,7 @@ function createNoteWithOcrAttachment(ocrText: string): BNote {
})
);
- const attachment = withContext(() =>
+ const attachment = getContext().init(() =>
note.saveAttachment({
role: "image",
mime: "image/png",
diff --git a/packages/trilium-core/src/services/special_notes.spec.ts b/packages/trilium-core/src/services/special_notes.spec.ts
index f86969d6a7..15217e2e4d 100644
--- a/packages/trilium-core/src/services/special_notes.spec.ts
+++ b/packages/trilium-core/src/services/special_notes.spec.ts
@@ -8,14 +8,6 @@ import hoistedNoteService from "./hoisted_note.js";
import specialNotes from "./special_notes.js";
import { unwrapStringOrBuffer } from "./utils/binary.js";
-/**
- * Wraps a callback in a CLS context. Entity mutations (createNewNote,
- * note.save(), branch.markAsDeleted(), etc.) require CLS to be initialised.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
/**
* The created note must end up (transitively) under the hidden subtree of the
* given root, as the monthly parent for these special notes lives there.
@@ -30,7 +22,7 @@ describe("special_notes (core, real DB)", () => {
describe("createSqlConsole", () => {
it("creates a code SQL console note under a monthly book parent in the hidden subtree", () => {
- const note = withContext(() => specialNotes.createSqlConsole());
+ const note = getContext().init(() => specialNotes.createSqlConsole());
expect(note.type).toBe("code");
expect(note.mime).toBe("text/x-sqlite;schema=trilium");
@@ -48,8 +40,8 @@ describe("special_notes (core, real DB)", () => {
});
it("reuses the same monthly parent for consoles created in the same month", () => {
- const a = withContext(() => specialNotes.createSqlConsole());
- const b = withContext(() => specialNotes.createSqlConsole());
+ const a = getContext().init(() => specialNotes.createSqlConsole());
+ const b = getContext().init(() => specialNotes.createSqlConsole());
expect(a.getParentNotes()[0].noteId).toBe(b.getParentNotes()[0].noteId);
});
@@ -57,15 +49,15 @@ describe("special_notes (core, real DB)", () => {
describe("saveSqlConsole", () => {
it("rejects when the SQL console note does not exist", async () => {
- await expect(withContext(() => specialNotes.saveSqlConsole("doesNotExist123")))
+ await expect(getContext().init(() => specialNotes.saveSqlConsole("doesNotExist123")))
.rejects.toThrow(/SQL console note/);
});
it("clones to the day note home and removes the hidden-subtree parent branch", async () => {
- const note = withContext(() => specialNotes.createSqlConsole());
+ const note = getContext().init(() => specialNotes.createSqlConsole());
expect(note.hasAncestor("_hidden")).toBe(true);
- const result = await withContext(() => specialNotes.saveSqlConsole(note.noteId));
+ const result = await getContext().init(() => specialNotes.saveSqlConsole(note.noteId));
expect(result.success).toBe(true);
expect(result.branchId).toBeTruthy();
@@ -82,8 +74,8 @@ describe("special_notes (core, real DB)", () => {
const home = becca.getNoteOrThrow("root").getChildNotes()[0];
vi.spyOn(attributeService, "getNoteWithLabel").mockReturnValue(home);
- const note = withContext(() => specialNotes.createSqlConsole());
- const result = await withContext(() => specialNotes.saveSqlConsole(note.noteId));
+ const note = getContext().init(() => specialNotes.createSqlConsole());
+ const result = await getContext().init(() => specialNotes.saveSqlConsole(note.noteId));
expect(result.success).toBe(true);
// It was cloned under the supplied home (a descendant of root, not hidden).
@@ -94,7 +86,7 @@ describe("special_notes (core, real DB)", () => {
describe("createSearchNote", () => {
it("creates a search note carrying the search string and keepCurrentHoisting label", () => {
- const note = withContext(() => specialNotes.createSearchNote("hello world", ""));
+ const note = getContext().init(() => specialNotes.createSearchNote("hello world", ""));
expect(note.type).toBe("search");
expect(note.mime).toBe("application/json");
@@ -110,33 +102,33 @@ describe("special_notes (core, real DB)", () => {
});
it("sets the ancestor relation only when an ancestorNoteId is supplied", () => {
- const withAncestor = withContext(() => specialNotes.createSearchNote("q1", "root"));
+ const withAncestor = getContext().init(() => specialNotes.createSearchNote("q1", "root"));
expect(withAncestor.getRelationValue("ancestor")).toBe("root");
- const withoutAncestor = withContext(() => specialNotes.createSearchNote("q2", ""));
+ const withoutAncestor = getContext().init(() => specialNotes.createSearchNote("q2", ""));
expect(withoutAncestor.hasRelation("ancestor")).toBe(false);
});
});
describe("saveSearchNote", () => {
it("throws when the search note does not exist", () => {
- expect(() => withContext(() => specialNotes.saveSearchNote("doesNotExist123")))
+ expect(() => getContext().init(() => specialNotes.saveSearchNote("doesNotExist123")))
.toThrow(/search note/);
});
it("throws when there is no workspace note", () => {
vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as any);
- const note = withContext(() => specialNotes.createSearchNote("q", ""));
+ const note = getContext().init(() => specialNotes.createSearchNote("q", ""));
- expect(() => withContext(() => specialNotes.saveSearchNote(note.noteId)))
+ expect(() => getContext().init(() => specialNotes.saveSearchNote(note.noteId)))
.toThrow(/workspace note/);
});
it("clones to the search home and removes the hidden-subtree parent branch", () => {
- const note = withContext(() => specialNotes.createSearchNote("q", ""));
+ const note = getContext().init(() => specialNotes.createSearchNote("q", ""));
expect(note.hasAncestor("_hidden")).toBe(true);
- const result = withContext(() => specialNotes.saveSearchNote(note.noteId));
+ const result = getContext().init(() => specialNotes.saveSearchNote(note.noteId));
expect(result.success).toBe(true);
expect(result.branchId).toBeTruthy();
@@ -166,7 +158,7 @@ describe("special_notes (core, real DB)", () => {
vi.spyOn(attributeService, "getNoteWithLabel").mockReturnValue(null);
// getDayNote may create the day note, so it needs a CLS context.
- const result = withContext(() => specialNotes.getInboxNote("2026-05-29"));
+ const result = getContext().init(() => specialNotes.getInboxNote("2026-05-29"));
// Day note for the date is created under the calendar; it is a real note.
expect(result).toBeTruthy();
expect(result.noteId).not.toBe("root");
@@ -196,7 +188,7 @@ describe("special_notes (core, real DB)", () => {
describe("createLauncher", () => {
it("creates a note launcher with the note-launcher template", () => {
- const { success, note } = withContext(() =>
+ const { success, note } = getContext().init(() =>
specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "note" })
);
@@ -206,7 +198,7 @@ describe("special_notes (core, real DB)", () => {
});
it("creates a script launcher with the script template", () => {
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "script" })
);
@@ -215,7 +207,7 @@ describe("special_notes (core, real DB)", () => {
});
it("creates a custom widget launcher with the custom widget template", () => {
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "customWidget" })
);
@@ -223,7 +215,7 @@ describe("special_notes (core, real DB)", () => {
});
it("creates a spacer launcher with the spacer template", () => {
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "spacer" })
);
@@ -232,7 +224,7 @@ describe("special_notes (core, real DB)", () => {
it("throws on an unrecognized launcher type", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
specialNotes.createLauncher({
parentNoteId: "_lbVisibleLaunchers",
launcherType: "bogus" as any
@@ -244,12 +236,12 @@ describe("special_notes (core, real DB)", () => {
describe("resetLauncher", () => {
it("deletes a normal launcher note", () => {
- const { note } = withContext(() =>
+ const { note } = getContext().init(() =>
specialNotes.createLauncher({ parentNoteId: "_lbVisibleLaunchers", launcherType: "note" })
);
expect(note.isDeleted).toBe(false);
- withContext(() => specialNotes.resetLauncher(note.noteId));
+ getContext().init(() => specialNotes.resetLauncher(note.noteId));
expect(becca.getNote(note.noteId)?.isDeleted ?? true).toBe(true);
});
@@ -266,7 +258,7 @@ describe("special_notes (core, real DB)", () => {
};
vi.spyOn(becca, "getNote").mockReturnValue(rootNote as any);
- withContext(() => specialNotes.resetLauncher("_lbRoot"));
+ getContext().init(() => specialNotes.resetLauncher("_lbRoot"));
// The root itself must NOT be deleted; only its children are reset.
expect(rootNote.deleteNote).not.toHaveBeenCalled();
@@ -275,9 +267,9 @@ describe("special_notes (core, real DB)", () => {
});
it("is a no-op for a note that is not a launchbar config note", () => {
- const plain = withContext(() => specialNotes.createSearchNote("not-a-launcher", ""));
+ const plain = getContext().init(() => specialNotes.createSearchNote("not-a-launcher", ""));
- withContext(() => specialNotes.resetLauncher(plain.noteId));
+ getContext().init(() => specialNotes.resetLauncher(plain.noteId));
// Search notes are not launchbar config, so they are left intact.
expect(becca.getNote(plain.noteId)?.isDeleted).toBe(false);
@@ -287,7 +279,7 @@ describe("special_notes (core, real DB)", () => {
describe("createOrUpdateScriptLauncherFromApi", () => {
it("rejects non-alphanumeric ids and a missing title", () => {
expect(() =>
- withContext(() =>
+ getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "bad id!",
title: "X",
@@ -297,7 +289,7 @@ describe("special_notes (core, real DB)", () => {
).toThrow(/alphanumeric/);
expect(() =>
- withContext(() =>
+ getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "okid",
title: "",
@@ -308,7 +300,7 @@ describe("special_notes (core, real DB)", () => {
});
it("creates a new script launcher with content, mime, shortcut and icon labels", () => {
- const launcher = withContext(() =>
+ const launcher = getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "myLauncher1",
title: "My Launcher",
@@ -329,7 +321,7 @@ describe("special_notes (core, real DB)", () => {
});
it("updates the existing launcher and removes shortcut/icon labels when omitted", () => {
- withContext(() =>
+ getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "myLauncher2",
title: "First",
@@ -339,7 +331,7 @@ describe("special_notes (core, real DB)", () => {
})
);
- const updated = withContext(() =>
+ const updated = getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "myLauncher2",
title: "Second",
@@ -355,7 +347,7 @@ describe("special_notes (core, real DB)", () => {
});
it("derives an alphanumeric id from the title when no id is provided", () => {
- const launcher = withContext(() =>
+ const launcher = getContext().init(() =>
specialNotes.createOrUpdateScriptLauncherFromApi({
id: "",
title: "Hello World!",
diff --git a/packages/trilium-core/src/services/sql/sql.spec.ts b/packages/trilium-core/src/services/sql/sql.spec.ts
index 1b822cbaae..fe29bf4d3a 100644
--- a/packages/trilium-core/src/services/sql/sql.spec.ts
+++ b/packages/trilium-core/src/services/sql/sql.spec.ts
@@ -6,15 +6,6 @@ import { getSql } from "./index.js";
// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.
const isBrowserRuntime = typeof window !== "undefined";
-/**
- * Wraps a callback in a CLS context. Methods that touch `getContext()`
- * (e.g. `disableSlowQueryLogging`, `transactional`) require an initialised
- * context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let tableCounter = 0;
/**
@@ -269,7 +260,7 @@ describe("SqlService (real DB)", () => {
describe("transactional", () => {
it("commits the changes made inside the callback and returns its value", () => {
const table = createTempTable();
- const ret = withContext(() =>
+ const ret = getContext().init(() =>
getSql().transactional(() => {
getSql().insert(table, { name: "committed", val: 1 });
return "done";
@@ -285,7 +276,7 @@ describe("SqlService (real DB)", () => {
getSql().insert(table, { name: "before", val: 1 });
expect(() =>
- withContext(() =>
+ getContext().init(() =>
getSql().transactional(() => {
getSql().insert(table, { name: "doomed", val: 2 });
throw new Error("boom");
@@ -302,7 +293,7 @@ describe("SqlService (real DB)", () => {
describe("transactionalAsync", () => {
it("commits an async callback and returns its resolved value", async () => {
const table = createTempTable();
- const ret = await withContext(() =>
+ const ret = await getContext().init(() =>
getSql().transactionalAsync(async () => {
getSql().insert(table, { name: "async", val: 1 });
return 42;
@@ -318,7 +309,7 @@ describe("SqlService (real DB)", () => {
getSql().insert(table, { name: "keep", val: 1 });
await expect(
- withContext(() =>
+ getContext().init(() =>
getSql().transactionalAsync(async () => {
getSql().insert(table, { name: "discard", val: 2 });
throw new Error("async-boom");
@@ -333,7 +324,7 @@ describe("SqlService (real DB)", () => {
describe("disableSlowQueryLogging", () => {
it("sets the flag for the duration of the callback and restores the prior value", () => {
- withContext(() => {
+ getContext().init(() => {
const ctx = getContext();
expect(ctx.get("disableSlowQueryLogging")).toBeFalsy();
@@ -348,7 +339,7 @@ describe("SqlService (real DB)", () => {
});
it("restores the flag even if the callback throws", () => {
- withContext(() => {
+ getContext().init(() => {
expect(() =>
getSql().disableSlowQueryLogging(() => {
throw new Error("inner-fail");
diff --git a/packages/trilium-core/src/services/sql_init.spec.ts b/packages/trilium-core/src/services/sql_init.spec.ts
index 0ece699f79..f41ed5d681 100644
--- a/packages/trilium-core/src/services/sql_init.spec.ts
+++ b/packages/trilium-core/src/services/sql_init.spec.ts
@@ -5,14 +5,6 @@ import eventService from "./events.js";
import { getSql } from "./sql/index.js";
import sqlInit from "./sql_init.js";
-/**
- * Wraps a callback in a CLS context. Some sql_init code paths
- * (initDbConnection, optionService.setOption) require an initialised context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
describe("sql_init (real DB)", () => {
beforeAll(() => {
// The shared in-memory fixture DB is already initialised by the suite
@@ -82,7 +74,7 @@ describe("sql_init (real DB)", () => {
describe("initDbConnection", () => {
it("creates the param_list and user_data tables and resolves dbReady", async () => {
- await withContext(() => sqlInit.initDbConnection());
+ await getContext().init(() => sqlInit.initDbConnection());
// The connection setup creates these auxiliary tables idempotently.
expect(
diff --git a/packages/trilium-core/src/services/task_states.spec.ts b/packages/trilium-core/src/services/task_states.spec.ts
index 4c4a28dada..d7041f81f6 100644
--- a/packages/trilium-core/src/services/task_states.spec.ts
+++ b/packages/trilium-core/src/services/task_states.spec.ts
@@ -14,14 +14,6 @@ import { getContext } from "./context.js";
import hiddenSubtreeService from "./hidden_subtree.js";
import { createTaskStateNote, generateTaskStateCss, getTaskStates } from "./task_states.js";
-/**
- * Entity mutations (createNewNote, BAttribute.save, branch.save, markAsDeleted)
- * require an initialised CLS context.
- */
-function withContext<T>(fn: () => T): T {
- return getContext().init(fn);
-}
-
let counter = 0;
/** A self-contained, valid custom state with a unique name/symbol per call. */
@@ -42,7 +34,7 @@ describe("task_states (real DB)", () => {
beforeAll(() => {
// Materialise the _taskStates container with its none/done anchors and the
// seeded custom defaults into the shared in-memory fixture DB. Idempotent.
- withContext(() => hiddenSubtreeService.checkHiddenSubtree());
+ getContext().init(() => hiddenSubtreeService.checkHiddenSubtree());
});
describe("getTaskStates", () => {
@@ -67,10 +59,10 @@ describe("task_states (real DB)", () => {
});
it("ignores archived definition notes entirely", () => {
- const note = withContext(() =>
+ const note = getContext().init(() =>
createTaskStateNote(customState({ name: "archivedState", markdownSymbol: "@" }))
);
- withContext(() => note.addLabel("archived"));
+ getContext().init(() => note.addLabel("archived"));
expect(note.isArchived).toBe(true);
const names = getTaskStates().map((s) => s.name);
@@ -79,7 +71,7 @@ describe("task_states (real DB)", () => {
it("drops invalid custom states while keeping the valid ones", () => {
// A custom state with a name containing a space fails validation and is dropped.
- const invalid = withContext(() =>
+ const invalid = getContext().init(() =>
createTaskStateNote(customState({ name: "not valid", markdownSymbol: "!" }))
);
@@ -113,7 +105,7 @@ describe("task_states (real DB)", () => {
icon: "bx bx-search"
});
- const note = withContext(() => createTaskStateNote(state));
+ const note = getContext().init(() => createTaskStateNote(state));
expect(note.type).toBe("doc");
expect(note.title).toBe("Review");
@@ -139,7 +131,7 @@ describe("task_states (real DB)", () => {
it("honours the explicit noteId and title overrides", () => {
counter++;
const noteId = `customTaskStateSpec${counter}`;
- const note = withContext(() =>
+ const note = getContext().init(() =>
createTaskStateNote(customState({ name: `over${counter}`, markdownSymbol: "" }), {
noteId,
title: "Overridden title"
@@ -161,7 +153,7 @@ describe("task_states (real DB)", () => {
icon: "bx bx-time"
});
- const note: BNote = withContext(() => createTaskStateNote(state));
+ const note: BNote = getContext().init(() => createTaskStateNote(state));
const read = getTaskStates().find((s) => s.id === note.noteId);
expect(read).toBeDefined();
@@ -194,12 +186,12 @@ describe("task_states (real DB)", () => {
it("computes a hue var for chromatic colors and leaves grayscale colors as unset", () => {
// "maybe" is seeded without a color → no hue, color falls back to inherit.
- const maybeNote = withContext(() =>
+ const maybeNote = getContext().init(() =>
createTaskStateNote(
customState({ name: "graystate", markdownSymbol: "g", color: "#808080" })
)
);
- const colorNote = withContext(() =>
+ const colorNote = getContext().init(() =>
createTaskStateNote(
customState({ name: "colorstate", markdownSymbol: "c", color: "#ff0000" })
)
@@ -227,7 +219,7 @@ describe("task_states (real DB)", () => {
});
it("skips states whose icon cannot be resolved to a glyph", () => {
- const note = withContext(() =>
+ const note = getContext().init(() =>
createTaskStateNote(
customState({ name: "noicon", markdownSymbol: "n", icon: "bx bx-this-icon-does-not-exist" })
)