Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(core): broken tests in standalone
Elian Doran0ba5da2f956e
diff --git a/.claude/skills/writing-unit-tests/server-and-core.md b/.claude/skills/writing-unit-tests/server-and-core.mdindex d175f97274..938ae09bb1 100644--- a/.claude/skills/writing-unit-tests/server-and-core.md+++ b/.claude/skills/writing-unit-tests/server-and-core.md@@ -4,6 +4,12 @@`trilium-core` cannot run tests standalone (its `test` script just prints a note — it needs a host runtime's platform providers). Its specs run **through** `apps/server` (and `apps/standalone`), which list `../../packages/trilium-core/src/**` in their test `include`. For that core code to actually count toward coverage, each host also sets `coverage.allowExternal: true` and lists core in `coverage.include` (v8 drops out-of-root files otherwise — see the coverage rules in `SKILL.md`). Add core specs next to the core source or under `apps/server/spec` — both feed the same coverage number, reported under the `server`/`standalone` Codecov flags. A dedicated core vitest project is **not** needed.+### ⚠️ A core spec runs under BOTH runtimes — verify both before calling it done+The same `packages/trilium-core/src/**` spec executes under the **server** suite (vitest env `node`, better-sqlite3 + `NodejsCryptoProvider`) **and** the **standalone** suite (env `happy-dom`, sql.js WASM + `Browser*Provider`). Passing `pnpm --filter server exec vitest run <spec>` is **not enough** — also run `pnpm --filter standalone exec vitest run <spec>`. A spec green on server can fail on standalone because the providers differ. Known cross-runtime traps:+- **`BNote.getContent()` of a non-string note** is a `Buffer` on Node (`.toString()` → UTF-8) but a `Uint8Array` on WASM (`.toString()` → `"40,40,..."`). Decode portably: `unwrapStringOrBuffer(note.getContent())` (import from a **relative** path like `./utils/binary.js`, never `@triliumnext/core` — self-import fails inside core).+- **Provider implementation details differ** and are NOT cross-runtime contracts: e.g. better-sqlite3 caches raw vs non-raw statements as distinct objects (sql.js may not); `crypto.hmac` of `Uint8Array` vs `string` inputs differs on Node but not in the browser provider. Don't assert these — assert the portable contract.+- **Capability gaps**: `getSql().serialize()` throws on better-sqlite3 (Node) but works on sql.js (WASM); `BrowserZipProvider.createFileStream()` throws (no file streams in the browser) and its streaming/finalize model differs (Node-style `pipe`→`end` never fires). For genuinely runtime-specific behavior, gate with `const isBrowserRuntime = typeof window !== "undefined";` + `it.skipIf(isBrowserRuntime)` / `describe.skipIf(...)` and a one-line reason — but prefer a portable assertion or capability-aware branch over skipping when the behavior is actually the same.+There are **two distinct HTTP code paths** — testing one does not cover the other:- **ETAPI** (`apps/server/src/etapi/*`): basic-auth token, helpers in `spec/etapi/utils.ts`.- **Internal API** (`apps/server/src/routes/api/*` + `packages/trilium-core/src/routes/api/*`): session cookie + CSRF. **This is the large uncovered surface.**diff --git a/packages/trilium-core/src/services/encryption/crypto.spec.ts b/packages/trilium-core/src/services/encryption/crypto.spec.tsindex edb13ae213..37b7ae6058 100644--- a/packages/trilium-core/src/services/encryption/crypto.spec.ts+++ b/packages/trilium-core/src/services/encryption/crypto.spec.ts@@ -163,14 +163,15 @@ describe("CryptoProvider behaviour (wired-up provider)", () => {});it("accepts a Uint8Array secret/value and stays deterministic", () => {- // The provider stringifies its inputs via toString(); a Uint8Array- // stringifies to its comma-joined bytes, so it deliberately does NOT- // collide with the same text passed as a string. It must, however,- // still hash deterministically.+ // Whether Uint8Array inputs collide with their string equivalents is a+ // provider-specific implementation detail (they differ under Node but+ // match under the BrowserCryptoProvider), so we only assert the portable+ // contract: equal Uint8Array inputs hash deterministically to a string.const a = crypto.hmac(encodeUtf8("secret"), encodeUtf8("message"));const b = crypto.hmac(encodeUtf8("secret"), encodeUtf8("message"));expect(a).toBe(b);- expect(a).not.toBe(crypto.hmac("secret", "message"));+ expect(typeof a).toBe("string");+ expect(a.length).toBeGreaterThan(0);});});diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.tsindex 8a196db61d..5eddaa156d 100644--- a/packages/trilium-core/src/services/export/zip.spec.ts+++ b/packages/trilium-core/src/services/export/zip.spec.ts@@ -13,6 +13,9 @@ import sql_init from "../sql_init.js";import { getZipProvider } from "../zip_provider.js";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);}@@ -102,7 +105,14 @@ function parseMeta(entries: Record<string, Buffer>): NoteMetaFile {return JSON.parse(entries["!!!meta.json"].toString("utf-8"));}-describe("zip export (real DB)", () => {+// Gated to Node: these real-DB export tests rely on Node stream semantics.+// The in-memory exportToZip tests pipe into a PassThrough and await its `end`+// event, but the BrowserZipProvider.finalize() writes synchronously via+// res.send() and never ends the stream, so completion never fires (timeout).+// The exportToZipFile tests need a writable file stream, which the browser+// provider does not support (createFileStream throws). The browser zip provider+// has different streaming semantics and is validated separately.+describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {beforeAll(async () => {sql_init.initializeDb();await sql_init.dbReady;diff --git a/packages/trilium-core/src/services/special_notes.spec.ts b/packages/trilium-core/src/services/special_notes.spec.tsindex 81e20eab87..f86969d6a7 100644--- a/packages/trilium-core/src/services/special_notes.spec.ts+++ b/packages/trilium-core/src/services/special_notes.spec.ts@@ -6,6 +6,7 @@ import attributeService from "./attributes.js";import { getContext } from "./context.js";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,@@ -33,7 +34,7 @@ describe("special_notes (core, real DB)", () => {expect(note.type).toBe("code");expect(note.mime).toBe("text/x-sqlite;schema=trilium");- expect(note.getContent().toString()).toContain("SELECT");+ expect(unwrapStringOrBuffer(note.getContent())).toContain("SELECT");expect(note.getLabelValue("iconClass")).toBe("bx bx-data");expect(note.hasLabel("keepCurrentHoisting")).toBe(true);expect(note.title).toContain("SQL Console");@@ -320,7 +321,7 @@ describe("special_notes (core, real DB)", () => {expect(launcher.noteId).toBe("myLauncher1");expect(launcher.title).toBe("My Launcher");expect(launcher.mime).toBe("application/javascript;env=frontend");- expect(launcher.getContent().toString()).toBe("(() => console.log(1))()");+ expect(unwrapStringOrBuffer(launcher.getContent())).toBe("(() => console.log(1))()");expect(launcher.hasLabel("scriptInLauncherContent")).toBe(true);expect(launcher.getLabelValue("keyboardShortcut")).toBe("ctrl+m");expect(launcher.getLabelValue("iconClass")).toBe("bx bx-rocket");@@ -348,7 +349,7 @@ describe("special_notes (core, real DB)", () => {expect(updated.noteId).toBe("myLauncher2");expect(updated.title).toBe("Second");- expect(updated.getContent().toString()).toBe("(() => 2)()");+ expect(unwrapStringOrBuffer(updated.getContent())).toBe("(() => 2)()");expect(updated.hasLabel("keyboardShortcut")).toBe(false);expect(updated.hasLabel("iconClass")).toBe(false);});diff --git a/packages/trilium-core/src/services/sql/sql.spec.ts b/packages/trilium-core/src/services/sql/sql.spec.tsindex 38bfbe3031..1b822cbaae 100644--- a/packages/trilium-core/src/services/sql/sql.spec.ts+++ b/packages/trilium-core/src/services/sql/sql.spec.ts@@ -3,6 +3,9 @@ import { beforeAll, describe, expect, it } from "vitest";import { getContext } from "../context.js";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@@ -163,7 +166,11 @@ describe("SqlService (real DB)", () => {expect(a).toBe(b);});- it("keeps raw and non-raw statements as distinct cache entries", () => {+ // Node's better-sqlite3 provider prepares a fresh statement object per+ // cache key, so raw vs non-raw yield distinct instances. The WASM+ // (sql.js) provider may hand back the same object for identical SQL, so+ // this distinctness is a Node-provider impl detail, not a portable contract.+ it.skipIf(isBrowserRuntime)("keeps raw and non-raw statements as distinct cache entries", () => {const sql = getSql();const plain = sql.stmt("SELECT 2");const raw = sql.stmt("SELECT 2", true);@@ -353,9 +360,16 @@ describe("SqlService (real DB)", () => {});describe("serialize", () => {- it("throws when the underlying provider does not support serialization", () => {- // The server's better-sqlite3 provider has no serialize() method.- expect(() => getSql().serialize()).toThrow("does not support serialization");+ it("either throws (provider unsupported) or returns the serialized bytes", () => {+ // Capability-aware: the server's better-sqlite3 provider has no+ // serialize() and throws, while the WASM (sql.js) provider supports+ // it and returns the database as a Uint8Array.+ if (isBrowserRuntime) {+ const bytes = getSql().serialize();+ expect(bytes).toBeInstanceOf(Uint8Array);+ } else {+ expect(() => getSql().serialize()).toThrow("does not support serialization");+ }});});});