Skip to content

Build your personal knowledge base with Trilium Notes

test(standalone): improve coverage

Elian Doranb542b09d904e
diff --git a/apps/standalone/src/lightweight/backup_provider.spec.ts b/apps/standalone/src/lightweight/backup_provider.spec.ts
new file mode 100644
index 0000000000..fb12ef2398
--- /dev/null
+++ b/apps/standalone/src/lightweight/backup_provider.spec.ts
@@ -0,0 +1,184 @@
+import { options } from "@triliumnext/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import StandaloneBackupService from "./backup_provider.js";
+
+interface NavWithStorage {
+ storage?: { getDirectory?: () => Promise<unknown> };
+}
+
+const realStorageDescriptor = Object.getOwnPropertyDescriptor(navigator, "storage");
+
+/** Build an in-memory OPFS directory handle backed by a Map. */
+function makeOpfs(seed: Record<string, { data: Uint8Array; lastModified: number }> = {}) {
+ const files = new Map(Object.entries(seed));
+
+ function fileHandle(name: string) {
+ return {
+ kind: "file" as const,
+ async getFile() {
+ const entry = files.get(name);
+ return {
+ lastModified: entry?.lastModified ?? 0,
+ async arrayBuffer() {
+ return (entry?.data ?? new Uint8Array()).buffer;
+ }
+ };
+ },
+ async createWritable() {
+ let chunk = new Uint8Array();
+ return {
+ async write(d: Uint8Array) { chunk = d; },
+ async close() { files.set(name, { data: chunk, lastModified: 1000 }); }
+ };
+ }
+ };
+ }
+
+ const dir = {
+ async getFileHandle(name: string, opts?: { create?: boolean }) {
+ if (!files.has(name) && opts?.create) {
+ files.set(name, { data: new Uint8Array(), lastModified: 0 });
+ }
+ if (!files.has(name)) {
+ throw new Error(`missing ${name}`);
+ }
+ return fileHandle(name);
+ },
+ async removeEntry(name: string) { files.delete(name); },
+ async *entries(): AsyncGenerator<[string, unknown]> {
+ // include a directory entry and a non-matching file to exercise filtering
+ yield ["nested", { kind: "directory" }];
+ for (const [name, entry] of files) {
+ yield [name, {
+ kind: "file",
+ async getFile() { return { lastModified: entry.lastModified }; }
+ }];
+ }
+ }
+ };
+
+ return { dir, files, root: { async getDirectoryHandle() { return dir; } } };
+}
+
+function installOpfs(getDirectory: () => Promise<unknown>) {
+ Object.defineProperty(navigator, "storage", { value: { getDirectory }, configurable: true });
+}
+
+afterEach(() => {
+ if (realStorageDescriptor) {
+ Object.defineProperty(navigator, "storage", realStorageDescriptor);
+ } else {
+ delete (navigator as unknown as NavWithStorage).storage;
+ }
+ vi.restoreAllMocks();
+});
+
+describe("StandaloneBackupService without OPFS", () => {
+ function serviceWithoutOpfs() {
+ delete (navigator as unknown as NavWithStorage).storage;
+ return new StandaloneBackupService(options);
+ }
+
+ it("scheduleBackups is a no-op", () => {
+ expect(() => serviceWithoutOpfs().scheduleBackups()).not.toThrow();
+ });
+
+ it("backupNow warns and returns the nominal path", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const service = serviceWithoutOpfs();
+ expect(await service.backupNow("now")).toBe("/backups/backup-now.db");
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("listing, deleting and reading return empty results", async () => {
+ const service = serviceWithoutOpfs();
+ expect(await service.getExistingBackups()).toEqual([]);
+ await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();
+ expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();
+ });
+
+ it("ensureBackupDirectory resolves to null when OPFS is unavailable", async () => {
+ const service = serviceWithoutOpfs();
+ const ensure = (service as unknown as { ensureBackupDirectory(): Promise<unknown> }).ensureBackupDirectory();
+ expect(await ensure).toBeNull();
+ });
+});
+
+describe("StandaloneBackupService with OPFS", () => {
+ it("writes a serialized backup and reports the path", async () => {
+ const fs = makeOpfs();
+ installOpfs(async () => fs.root);
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ const service = new StandaloneBackupService(options);
+ const path = await service.backupNow("daily");
+ expect(path).toBe("/backups/backup-daily.db");
+ expect(fs.files.get("backup-daily.db")?.data.byteLength).toBeGreaterThan(0);
+ });
+
+ it("lists matching backups newest-first and ignores non-backup entries", async () => {
+ const fs = makeOpfs({
+ "backup-old.db": { data: new Uint8Array(), lastModified: 100 },
+ "backup-new.db": { data: new Uint8Array(), lastModified: 200 },
+ "notes.txt": { data: new Uint8Array(), lastModified: 300 }
+ });
+ installOpfs(async () => fs.root);
+
+ const backups = await new StandaloneBackupService(options).getExistingBackups();
+ expect(backups.map(b => b.fileName)).toEqual(["backup-new.db", "backup-old.db"]);
+ expect(backups[0].filePath).toBe("/backups/backup-new.db");
+ });
+
+ it("reads and deletes a backup by path/name", async () => {
+ const fs = makeOpfs({ "backup-keep.db": { data: new Uint8Array([1, 2, 3]), lastModified: 1 } });
+ installOpfs(async () => fs.root);
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ const service = new StandaloneBackupService(options);
+ const content = await service.getBackupContent("/backups/backup-keep.db");
+ expect(content && Array.from(content)).toEqual([1, 2, 3]);
+
+ await service.deleteBackup("backup-keep.db");
+ expect(fs.files.has("backup-keep.db")).toBe(false);
+ });
+
+ it("returns null when the requested file name is not a backup", async () => {
+ installOpfs(async () => makeOpfs().root);
+ const service = new StandaloneBackupService(options);
+ expect(await service.getBackupContent("/backups/secrets.txt")).toBeNull();
+ });
+
+ it("handles a missing backup directory handle gracefully", async () => {
+ // root.getDirectoryHandle resolves to undefined → ensureBackupDirectory() returns null.
+ const root = { async getDirectoryHandle() { return undefined; } };
+ installOpfs(async () => root);
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const service = new StandaloneBackupService(options);
+ expect(await service.backupNow("x")).toBe("/backups/backup-x.db");
+ expect(await service.getExistingBackups()).toEqual([]);
+ await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();
+ expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();
+ });
+
+ it("swallows OPFS errors on every operation", async () => {
+ const boom = async () => { throw new Error("opfs down"); };
+ installOpfs(boom);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const service = new StandaloneBackupService(options);
+ expect(await service.backupNow("x")).toBe("/backups/backup-x.db");
+ expect(await service.getExistingBackups()).toEqual([]);
+ await expect(service.deleteBackup("backup-x.db")).resolves.toBeUndefined();
+ expect(await service.getBackupContent("/backups/backup-x.db")).toBeNull();
+ });
+
+ it("caches the OPFS availability probe", async () => {
+ installOpfs(async () => makeOpfs().root);
+ const service = new StandaloneBackupService(options);
+ // Two calls; the second should reuse the cached availability flag.
+ await service.getExistingBackups();
+ await service.getExistingBackups();
+ });
+});
diff --git a/apps/standalone/src/lightweight/bridged_request_provider.spec.ts b/apps/standalone/src/lightweight/bridged_request_provider.spec.ts
new file mode 100644
index 0000000000..f9d1716cf1
--- /dev/null
+++ b/apps/standalone/src/lightweight/bridged_request_provider.spec.ts
@@ -0,0 +1,188 @@
+import type { ExecOpts } from "@triliumnext/core";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import BridgedRequestProvider from "./bridged_request_provider.js";
+
+interface PostedMessage {
+ type: string;
+ id: string;
+ request: {
+ method: string;
+ url: string;
+ headers: Record<string, string>;
+ body?: string;
+ responseType?: string;
+ };
+}
+
+let postSpy: ReturnType<typeof vi.spyOn>;
+
+function lastPosted(): PostedMessage {
+ return postSpy.mock.calls.at(-1)?.[0] as PostedMessage;
+}
+
+/** Deliver a worker HTTP_RESPONSE for the most recently posted request id. */
+function respond(fields: Record<string, unknown>) {
+ const id = lastPosted().id;
+ self.dispatchEvent(new MessageEvent("message", { data: { type: "HTTP_RESPONSE", id, ...fields } }));
+}
+
+beforeEach(() => {
+ postSpy = vi.spyOn(self, "postMessage").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe("BridgedRequestProvider.exec", () => {
+ it("posts an HTTP_REQUEST and resolves with the parsed JSON body", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec<{ ok: boolean }>({ method: "GET", url: "http://x/api" } as ExecOpts);
+
+ const posted = lastPosted();
+ expect(posted.type).toBe("HTTP_REQUEST");
+ expect(posted.request.method).toBe("GET");
+ expect(posted.request.headers["Content-Type"]).toBe("application/json");
+
+ respond({ status: 200, body: JSON.stringify({ ok: true }), headers: {} });
+ await expect(promise).resolves.toEqual({ ok: true });
+ });
+
+ it("returns null for an empty 204 body", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ status: 204, body: "" });
+ await expect(promise).resolves.toBeNull();
+ });
+
+ it("forwards the cookie jar header and captures set-cookie from the response", async () => {
+ const provider = new BridgedRequestProvider();
+ const cookieJar = { header: "session=abc" };
+ const promise = provider.exec({ method: "GET", url: "http://x", cookieJar } as unknown as ExecOpts);
+
+ expect(lastPosted().request.headers["Cookie"]).toBe("session=abc");
+
+ respond({ status: 200, body: "{}", headers: { "set-cookie": "session=def" } });
+ await promise;
+ expect(cookieJar.header).toBe("session=def");
+ });
+
+ it("adds auth, multi-page and serialized-body fields", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({
+ method: "POST",
+ url: "http://x",
+ auth: { password: "pw" },
+ body: { a: 1 },
+ paging: { pageCount: 2, pageIndex: 0, requestId: "r" }
+ } as ExecOpts);
+
+ const posted = lastPosted();
+ expect(posted.request.headers["trilium-cred"]).toBe(btoa("dummy:pw"));
+ expect(posted.request.headers["Content-Type"]).toBe("text/plain");
+ expect(posted.request.body).toBe(JSON.stringify({ a: 1 }));
+
+ respond({ status: 200, body: "{}" });
+ await promise;
+ });
+
+ it("throws with the error message from a non-2xx JSON body", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ status: 500, body: JSON.stringify({ message: "server boom" }) });
+ await expect(promise).rejects.toThrow("server boom");
+ });
+
+ it("throws with truncated raw text when the error body is not JSON", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ status: 400, body: "not json" });
+ await expect(promise).rejects.toThrow("400 GET http://x: not json");
+ });
+
+ it("passes a string body through unchanged", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "POST", url: "http://x", body: "raw-string" } as ExecOpts);
+ expect(lastPosted().request.body).toBe("raw-string");
+ respond({ status: 200, body: "{}" });
+ await promise;
+ });
+
+ it("clears the timeout when a response resolves in time", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec<{ ok: boolean }>({ method: "GET", url: "http://x", timeout: 1000 } as ExecOpts);
+ respond({ status: 200, body: JSON.stringify({ ok: true }) });
+ await expect(promise).resolves.toEqual({ ok: true });
+ });
+
+ it("clears the timeout when the response carries an error", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x", timeout: 1000 } as ExecOpts);
+ respond({ error: "worker failed" });
+ await expect(promise).rejects.toThrow("worker failed");
+ });
+
+ it("throws with an empty message when the error body has no message field", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ status: 500, body: JSON.stringify({ code: "X" }) });
+ await expect(promise).rejects.toThrow("500 GET");
+ });
+
+ it("handles a non-2xx response that has no body", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ status: 500 });
+ await expect(promise).rejects.toThrow("500 GET");
+ });
+
+ it("rejects when the worker reports an error", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x" } as ExecOpts);
+ respond({ error: "worker failed" });
+ await expect(promise).rejects.toThrow("worker failed");
+ });
+
+ it("rejects with a timeout when no response arrives", async () => {
+ vi.useFakeTimers();
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec({ method: "GET", url: "http://x", timeout: 100 } as ExecOpts);
+ const rejection = expect(promise).rejects.toThrow("timeout after 100ms");
+ vi.advanceTimersByTime(100);
+ await rejection;
+ });
+
+ it("ignores irrelevant or unknown-id messages", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.exec<{ ok: boolean }>({ method: "GET", url: "http://x" } as ExecOpts);
+
+ self.dispatchEvent(new MessageEvent("message", { data: null }));
+ self.dispatchEvent(new MessageEvent("message", { data: { type: "OTHER" } }));
+ self.dispatchEvent(new MessageEvent("message", { data: { type: "HTTP_RESPONSE", id: "does-not-exist" } }));
+
+ respond({ status: 200, body: JSON.stringify({ ok: true }) });
+ await expect(promise).resolves.toEqual({ ok: true });
+ });
+});
+
+describe("BridgedRequestProvider.getImage", () => {
+ it("decodes a base64 body into an ArrayBuffer", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.getImage("http://x/img.png");
+
+ expect(lastPosted().request.responseType).toBe("arraybuffer");
+
+ respond({ status: 200, body: btoa("ABC") });
+ const buffer = await promise;
+ expect(Array.from(new Uint8Array(buffer))).toEqual([65, 66, 67]);
+ });
+
+ it("throws for a non-2xx image response", async () => {
+ const provider = new BridgedRequestProvider();
+ const promise = provider.getImage("http://x/missing.png");
+ respond({ status: 404, body: "" });
+ await expect(promise).rejects.toThrow("404 GET");
+ });
+});
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.ts
new file mode 100644
index 0000000000..156d02619c
--- /dev/null
+++ b/apps/standalone/src/lightweight/browser_router.spec.ts
@@ -0,0 +1,256 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { BrowserRouter, createRouter } from "./browser_router.js";
+
+const RAW_RESPONSE = Symbol.for("RAW_RESPONSE");
+const encoder = new TextEncoder();
+
+function decodeBody(body: ArrayBuffer | null): string {
+ return body ? new TextDecoder().decode(body) : "";
+}
+
+function json(obj: unknown): ArrayBuffer {
+ return encoder.encode(JSON.stringify(obj)).buffer as ArrayBuffer;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("BrowserRouter routing", () => {
+ it("dispatches by method and exposes a convenience method per verb", async () => {
+ const router = createRouter();
+ const seen: string[] = [];
+ for (const verb of ["get", "post", "put", "patch", "delete"] as const) {
+ router[verb]("/r", () => { seen.push(verb); return { verb }; });
+ }
+ for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE"]) {
+ const res = await router.dispatch(method, "http://localhost/r");
+ expect(res.status).toBe(200);
+ }
+ expect(seen).toEqual(["get", "post", "put", "patch", "delete"]);
+ });
+
+ it("extracts and decodes path parameters and parses the query string", async () => {
+ const router = new BrowserRouter();
+ let captured: { params: Record<string, string>; query: Record<string, string | undefined> } | undefined;
+ router.get("/api/notes/:noteId/branches/:branchId", (req) => {
+ captured = { params: req.params, query: req.query };
+ return {};
+ });
+ await router.dispatch("GET", "http://localhost/api/notes/a%20b/branches/xyz?expand=true&depth=2");
+ expect(captured?.params).toEqual({ noteId: "a b", branchId: "xyz" });
+ expect(captured?.query).toEqual({ expand: "true", depth: "2" });
+ });
+
+ it("returns 404 text for an unmatched route", async () => {
+ const router = new BrowserRouter();
+ const res = await router.dispatch("GET", "http://localhost/missing");
+ expect(res.status).toBe(404);
+ expect(res.headers["content-type"]).toContain("text/plain");
+ expect(decodeBody(res.body)).toBe("Not found: GET /missing");
+ });
+});
+
+describe("BrowserRouter body parsing", () => {
+ it("parses a JSON body from an ArrayBuffer", async () => {
+ const router = new BrowserRouter();
+ let body: unknown;
+ router.post("/echo", (req) => { body = req.body; return {}; });
+ await router.dispatch("POST", "http://localhost/echo", json({ a: 1 }), { "content-type": "application/json" });
+ expect(body).toEqual({ a: 1 });
+ });
+
+ it("leaves an empty JSON body as the raw buffer", async () => {
+ const router = new BrowserRouter();
+ let body: unknown;
+ router.post("/echo", (req) => { body = req.body; return {}; });
+ const raw = encoder.encode(" ").buffer as ArrayBuffer;
+ await router.dispatch("POST", "http://localhost/echo", raw, { "content-type": "application/json" });
+ expect(body).toBe(raw);
+ });
+
+ it("warns and keeps the raw buffer on invalid JSON", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ let body: unknown;
+ router.post("/echo", (req) => { body = req.body; return {}; });
+ const raw = encoder.encode("{not json").buffer as ArrayBuffer;
+ await router.dispatch("POST", "http://localhost/echo", raw, { "Content-Type": "application/json" });
+ expect(body).toBe(raw);
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("passes through a non-ArrayBuffer body unchanged", async () => {
+ const router = new BrowserRouter();
+ let body: unknown;
+ router.post("/echo", (req) => { body = req.body; return {}; });
+ await router.dispatch("POST", "http://localhost/echo", { already: "parsed" });
+ expect(body).toEqual({ already: "parsed" });
+ });
+
+ it("leaves an ArrayBuffer body untouched when no content-type is given", async () => {
+ const router = new BrowserRouter();
+ let body: unknown;
+ router.post("/echo", (req) => { body = req.body; return {}; });
+ const raw = encoder.encode("opaque").buffer as ArrayBuffer;
+ await router.dispatch("POST", "http://localhost/echo", raw, { "x-other": "1" });
+ expect(body).toBe(raw);
+ });
+
+ it("uses the declared part content-type, falling back to octet-stream otherwise", async () => {
+ const router = new BrowserRouter();
+ let file: { mimetype: string } | undefined;
+ router.post("/u2", (r) => { file = r.file; return {}; });
+
+ async function uploadMimetype(partContentType: string | null): Promise<string | undefined> {
+ const boundary = "----triliumtest";
+ const typeLine = partContentType ? `Content-Type: ${partContentType}\r\n` : "";
+ const body =
+ `--${boundary}\r\n` +
+ `Content-Disposition: form-data; name="upload"; filename="f.dat"\r\n` +
+ typeLine +
+ `\r\n` +
+ `data\r\n` +
+ `--${boundary}--\r\n`;
+ const buffer = encoder.encode(body).buffer as ArrayBuffer;
+ await router.dispatch("POST", "http://localhost/u2", buffer, { "content-type": `multipart/form-data; boundary=${boundary}` });
+ return file?.mimetype;
+ }
+
+ // Declared content-type is used; absent type falls back to octet-stream.
+ expect(await uploadMimetype("text/plain")).toBe("text/plain");
+ expect(await uploadMimetype(null)).toBe("application/octet-stream");
+ });
+
+ it("parses multipart/form-data into fields and an uploaded file", async () => {
+ const fd = new FormData();
+ fd.append("title", "hello");
+ fd.append("upload", new File([new Uint8Array([1, 2, 3])], "f.bin", { type: "application/octet-stream" }));
+ const request = new Request("http://localhost/u", { method: "POST", body: fd });
+ const contentType = request.headers.get("content-type") ?? "";
+ const buffer = await request.arrayBuffer();
+
+ const router = new BrowserRouter();
+ let req: { body?: unknown; file?: { originalname: string; mimetype: string; buffer: Uint8Array } } | undefined;
+ router.post("/u", (r) => { req = r; return {}; });
+ await router.dispatch("POST", "http://localhost/u", buffer, { "content-type": contentType });
+
+ expect(req?.body).toEqual({ title: "hello" });
+ expect(typeof req?.file?.originalname).toBe("string");
+ expect(req?.file && Array.from(req.file.buffer)).toEqual([1, 2, 3]);
+ });
+
+ it("warns when multipart parsing fails", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.post("/u", () => ({}));
+ // A multipart content-type with no boundary makes Response.formData() throw.
+ const raw = encoder.encode("garbage").buffer as ArrayBuffer;
+ await router.dispatch("POST", "http://localhost/u", raw, { "content-type": "multipart/form-data" });
+ expect(warn).toHaveBeenCalled();
+ });
+});
+
+describe("BrowserRouter result formatting", () => {
+ it("returns 204 with no body for undefined results", async () => {
+ const router = new BrowserRouter();
+ router.get("/void", () => undefined);
+ const res = await router.dispatch("GET", "http://localhost/void");
+ expect(res.status).toBe(204);
+ expect(res.body).toBeNull();
+ });
+
+ it("honors a [statusCode, response] tuple", async () => {
+ const router = new BrowserRouter();
+ router.get("/created", () => [201, { id: "x" }]);
+ const res = await router.dispatch("GET", "http://localhost/created");
+ expect(res.status).toBe(201);
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ id: "x" });
+ });
+
+ it("serializes a plain object as a 200 JSON response", async () => {
+ const router = new BrowserRouter();
+ router.get("/obj", () => ({ ok: true }));
+ const res = await router.dispatch("GET", "http://localhost/obj");
+ expect(res.status).toBe(200);
+ expect(res.headers["content-type"]).toContain("application/json");
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ ok: true });
+ });
+
+ it("passes raw responses through, handling each body type", async () => {
+ const router = new BrowserRouter();
+ router.get("/raw-ab", () => ({ [RAW_RESPONSE]: true, status: 200, headers: { "x": "1" }, body: encoder.encode("ab").buffer }));
+ router.get("/raw-u8", () => ({ [RAW_RESPONSE]: true, status: 200, headers: {}, body: new Uint8Array([65, 66]) }));
+ router.get("/raw-str", () => ({ [RAW_RESPONSE]: true, status: 206, headers: {}, body: "hello" }));
+ router.get("/raw-null", () => ({ [RAW_RESPONSE]: true, status: 304, headers: {}, body: null }));
+
+ expect(decodeBody((await router.dispatch("GET", "http://localhost/raw-ab")).body)).toBe("ab");
+ expect(decodeBody((await router.dispatch("GET", "http://localhost/raw-u8")).body)).toBe("AB");
+
+ const strRes = await router.dispatch("GET", "http://localhost/raw-str");
+ expect(strRes.status).toBe(206);
+ expect(decodeBody(strRes.body)).toBe("hello");
+
+ const nullRes = await router.dispatch("GET", "http://localhost/raw-null");
+ expect(nullRes.status).toBe(304);
+ expect(nullRes.body).toBeNull();
+ });
+});
+
+describe("BrowserRouter error formatting", () => {
+ class NotFoundError extends Error {}
+ class ValidationError extends Error {}
+
+ it("maps NotFoundError to 404", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/nf", () => { throw new NotFoundError("gone"); });
+ const res = await router.dispatch("GET", "http://localhost/nf");
+ expect(res.status).toBe(404);
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "gone" });
+ });
+
+ it("maps ValidationError to 400", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/ve", () => { throw new ValidationError("bad"); });
+ const res = await router.dispatch("GET", "http://localhost/ve");
+ expect(res.status).toBe(400);
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "bad" });
+ });
+
+ it("maps an unknown error to 500", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/boom", () => { throw new Error("kaput"); });
+ const res = await router.dispatch("GET", "http://localhost/boom");
+ expect(res.status).toBe(500);
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "kaput" });
+ });
+
+ it("falls back to a default message for NotFoundError without a message", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/nf2", () => { throw new NotFoundError(); });
+ const res = await router.dispatch("GET", "http://localhost/nf2");
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "Not found" });
+ });
+
+ it("falls back to a default message for ValidationError without a message", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/ve2", () => { throw new ValidationError(); });
+ const res = await router.dispatch("GET", "http://localhost/ve2");
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "Validation error" });
+ });
+
+ it("stringifies a thrown non-Error value", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const router = new BrowserRouter();
+ router.get("/str", () => { throw "plain string"; });
+ const res = await router.dispatch("GET", "http://localhost/str");
+ expect(res.status).toBe(500);
+ expect(JSON.parse(decodeBody(res.body))).toEqual({ message: "plain string" });
+ });
+});
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
new file mode 100644
index 0000000000..2664f4f0e3
--- /dev/null
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -0,0 +1,172 @@
+import { routes, sql_init } from "@triliumnext/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { BrowserRouter } from "./browser_router.js";
+import { createConfiguredRouter, registerRoutes } from "./browser_routes.js";
+
+const decoder = new TextDecoder();
+
+function parseJson(body: ArrayBuffer | null): unknown {
+ return body ? JSON.parse(decoder.decode(body)) : null;
+}
+
+function text(body: ArrayBuffer | null): string {
+ return body ? decoder.decode(body) : "";
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("registerRoutes (real wiring)", () => {
+ const router = createConfiguredRouter();
+
+ it("registers routes onto a provided router", async () => {
+ const fresh = new BrowserRouter();
+ registerRoutes(fresh);
+ const res = await fresh.dispatch("GET", "http://localhost/api/system-checks");
+ expect(parseJson(res.body)).toEqual({ isCpuArchMismatch: false });
+ });
+
+ it("serves the compatibility dummy routes", async () => {
+ expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/widgets")).body)).toEqual([]);
+ expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/startup")).body)).toEqual([]);
+ });
+
+ it("runs a real transactional apiRoute handler with context headers", async () => {
+ const res = await router.dispatch("GET", "http://localhost/api/options", undefined, {
+ "trilium-component-id": "comp-1",
+ "trilium-hoisted-note-id": "root"
+ });
+ expect(res.status).toBe(200);
+ expect(parseJson(res.body)).toBeTypeOf("object");
+ });
+
+ it("returns the full bootstrap payload when the database is initialized", async () => {
+ const data = parseJson((await router.dispatch("GET", "http://localhost/bootstrap")).body) as Record<string, unknown>;
+ expect(data.isStandalone).toBe(true);
+ expect(data.isElectron).toBe(false);
+ expect(data.csrfToken).toBe("dummy-csrf-token");
+ expect(typeof data.triliumVersion).toBe("string");
+ });
+
+ it("returns the setup payload when the database is not initialized", async () => {
+ vi.spyOn(sql_init, "isDbInitialized").mockReturnValue(false);
+ const data = parseJson((await router.dispatch("GET", "http://localhost/bootstrap")).body) as Record<string, unknown>;
+ expect(data.isProtectedSessionAvailable).toBe(false);
+ expect(data.csrfToken).toBeUndefined();
+ });
+});
+
+// The route-wrapping helpers are private; the only way to drive every branch is
+// through buildSharedApiRoutes. Mock it so we can register handlers that hit each
+// path deterministically instead of relying on specific core routes + fixtures.
+describe("route wrapper branches (via controlled handlers)", () => {
+ type RouteCtx = Parameters<typeof routes.buildSharedApiRoutes>[0];
+ let ctx: RouteCtx;
+
+ function buildRouter(): BrowserRouter {
+ vi.spyOn(routes, "buildSharedApiRoutes").mockImplementation((received: RouteCtx) => {
+ ctx = received;
+ const { route, asyncRoute, apiRoute, asyncApiRoute, apiResultHandler } = received;
+
+ apiRoute("get", "/t/api", (req: { originalUrl: string }) => ({ url: req.originalUrl }));
+ asyncApiRoute("get", "/t/asyncapi", () => ({ ok: true }));
+
+ route("get", "/t/r-obj", [], () => ({ a: 1 }), apiResultHandler);
+ route("get", "/t/r-tuple", [], () => [201, { created: true }], apiResultHandler);
+ route("get", "/t/r-undef", [], () => undefined, apiResultHandler);
+ route("get", "/t/r-noresult", [], () => ({ plain: true }));
+ route("get", "/t/r-res", [], (_req: unknown, res: MockRes) => {
+ res.set("A", "1").setHeader("B", "2").removeHeader("A").status(206).send("body");
+ });
+ route("get", "/t/r-sendstatus", [], (_req: unknown, res: MockRes) => { res.sendStatus(204); });
+ route("get", "/t/r-stream", [], (_req: unknown, res: MockRes) => { res.write("chunk1"); res.write("chunk2"); res.end(); });
+ route("get", "/t/r-customrh", [], () => ({ x: 1 }), (_req: unknown, res: { setHeader(n: string, v: string): void; result: unknown }, result: unknown) => {
+ res.setHeader("X-Custom", "y");
+ res.result = result;
+ });
+
+ asyncRoute("get", "/t/async-obj", [], async () => ({ z: 9 }), apiResultHandler);
+ asyncRoute("get", "/t/async-res", [], async (_req: unknown, res: MockRes) => { res.send("async-body"); });
+ asyncRoute("get", "/t/async-noresult", [], async () => ({ done: true }));
+ });
+ return createConfiguredRouter();
+ }
+
+ interface MockRes {
+ set(n: string, v: string): MockRes;
+ setHeader(n: string, v: string): MockRes;
+ removeHeader(n: string): MockRes;
+ status(c: number): MockRes;
+ send(b: unknown): MockRes;
+ sendStatus(c: number): MockRes;
+ write(c: string): boolean;
+ end(): MockRes;
+ }
+
+ it("runs transactional and non-transactional api routes (and reads originalUrl)", async () => {
+ const router = buildRouter();
+ const apiRes = await router.dispatch("GET", "http://localhost/t/api");
+ expect((parseJson(apiRes.body) as { url: string }).url).toBe("http://localhost/t/api");
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/asyncapi")).body)).toEqual({ ok: true });
+ });
+
+ it("formats route() results through apiResultHandler (object, tuple, undefined)", async () => {
+ const router = buildRouter();
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/r-obj")).body)).toEqual({ a: 1 });
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/r-tuple")).body)).toEqual({ created: true });
+
+ const undefRes = await router.dispatch("GET", "http://localhost/t/r-undef");
+ expect(text(undefRes.body)).toBe('""');
+ });
+
+ it("returns a plain route() result when no result handler is supplied", async () => {
+ const router = buildRouter();
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/r-noresult")).body)).toEqual({ plain: true });
+ });
+
+ it("passes raw (res.*) route() responses through, covering every mock response method", async () => {
+ const router = buildRouter();
+ const res = await router.dispatch("GET", "http://localhost/t/r-res");
+ expect(res.status).toBe(206);
+ expect(res.headers).toEqual({ B: "2" });
+ expect(text(res.body)).toBe("body");
+
+ expect((await router.dispatch("GET", "http://localhost/t/r-sendstatus")).status).toBe(204);
+ expect(text((await router.dispatch("GET", "http://localhost/t/r-stream")).body)).toBe("chunk1chunk2");
+ });
+
+ it("invokes a custom result handler that sets a header", async () => {
+ const router = buildRouter();
+ const res = await router.dispatch("GET", "http://localhost/t/r-customrh");
+ expect(parseJson(res.body)).toEqual({ x: 1 });
+ });
+
+ it("handles asyncRoute() result-handler, raw and plain paths", async () => {
+ const router = buildRouter();
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/async-obj")).body)).toEqual({ z: 9 });
+ expect(text((await router.dispatch("GET", "http://localhost/t/async-res")).body)).toBe("async-body");
+ expect(parseJson((await router.dispatch("GET", "http://localhost/t/async-noresult")).body)).toEqual({ done: true });
+ });
+
+ it("serves the dummy compatibility routes (which real routes would otherwise shadow)", async () => {
+ const router = buildRouter();
+ expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/widgets")).body)).toEqual([]);
+ expect(parseJson((await router.dispatch("GET", "http://localhost/api/script/startup")).body)).toEqual([]);
+ expect(parseJson((await router.dispatch("GET", "http://localhost/api/system-checks")).body)).toEqual({ isCpuArchMismatch: false });
+ });
+
+ it("provides no-op middleware and an init guard", async () => {
+ buildRouter();
+ // No-op middleware stubs do nothing and never throw.
+ for (const mw of [ctx.checkApiAuth, ctx.checkApiAuthOrElectron, ctx.checkCredentials, ctx.loginRateLimiter, ctx.uploadMiddlewareWithErrorHandling, ctx.csrfMiddleware]) {
+ expect(() => (mw as () => void)()).not.toThrow();
+ }
+ // checkAppNotInitialized throws while the DB is initialized...
+ expect(() => (ctx.checkAppNotInitialized as () => void)()).toThrow("App already initialized");
+ // ...and is a no-op once the DB is reported uninitialized.
+ vi.spyOn(sql_init, "isDbInitialized").mockReturnValue(false);
+ expect(() => (ctx.checkAppNotInitialized as () => void)()).not.toThrow();
+ });
+});
diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.ts
index 556eaf9ce7..98e18e56c8 100644
--- a/apps/standalone/src/lightweight/browser_routes.ts
+++ b/apps/standalone/src/lightweight/browser_routes.ts
@@ -33,6 +33,7 @@ function toExpressLikeReq(req: BrowserRequest) {
params: req.params,
query: req.query,
body: req.body,
+ /* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */
headers: req.headers ?? {},
method: req.method,
file: req.file,
@@ -45,6 +46,7 @@ function toExpressLikeReq(req: BrowserRequest) {
* mirroring what the server does in route_api.ts.
*/
function setContextFromHeaders(req: BrowserRequest) {
+ /* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */
const headers = req.headers ?? {};
const ctx = getContext();
ctx.set("componentId", headers["trilium-component-id"]);
diff --git a/apps/standalone/src/lightweight/cls_provider.spec.ts b/apps/standalone/src/lightweight/cls_provider.spec.ts
new file mode 100644
index 0000000000..f85e602022
--- /dev/null
+++ b/apps/standalone/src/lightweight/cls_provider.spec.ts
@@ -0,0 +1,70 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import BrowserExecutionContext from "./cls_provider.js";
+
+describe("BrowserExecutionContext", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("returns undefined from get() when no context is active", () => {
+ const ctx = new BrowserExecutionContext();
+ expect(ctx.get("anything")).toBeUndefined();
+ });
+
+ it("throws from set() when no context is active", () => {
+ const ctx = new BrowserExecutionContext();
+ expect(() => ctx.set("k", "v")).toThrow("ExecutionContext not initialized");
+ });
+
+ it("exposes get/set within a synchronous init() scope and cleans up after the grace period", () => {
+ const ctx = new BrowserExecutionContext();
+ const result = ctx.init(() => {
+ ctx.set("k", 42);
+ expect(ctx.get<number>("k")).toBe(42);
+ return "done";
+ });
+ expect(result).toBe("done");
+
+ // Still readable during the grace period.
+ expect(ctx.get<number>("k")).toBe(42);
+
+ // After the grace period the context is popped off the stack.
+ vi.advanceTimersByTime(1000);
+ expect(ctx.get("k")).toBeUndefined();
+ });
+
+ it("cleans up after an async init() resolves", async () => {
+ const ctx = new BrowserExecutionContext();
+ const promise = ctx.init(async () => {
+ ctx.set("async", "yes");
+ return "ok";
+ });
+ await expect(promise).resolves.toBe("ok");
+
+ vi.advanceTimersByTime(1000);
+ expect(ctx.get("async")).toBeUndefined();
+ });
+
+ it("schedules cleanup and rethrows when the synchronous callback throws", () => {
+ const ctx = new BrowserExecutionContext();
+ expect(() => ctx.init(() => { throw new Error("kaboom"); })).toThrow("kaboom");
+
+ // The errored context is still cleaned up after the grace period (no throw).
+ expect(() => vi.advanceTimersByTime(1000)).not.toThrow();
+ });
+
+ it("reset() empties the stack, leaving a pending cleanup timer a no-op", () => {
+ const ctx = new BrowserExecutionContext();
+ ctx.init(() => "x");
+ ctx.reset();
+ expect(ctx.get("anything")).toBeUndefined();
+
+ // The cleanup timer fires but the context is already gone (index === -1).
+ expect(() => vi.advanceTimersByTime(1000)).not.toThrow();
+ });
+});
diff --git a/apps/standalone/src/lightweight/cls_provider.ts b/apps/standalone/src/lightweight/cls_provider.ts
index d4336967db..51b66b4154 100644
--- a/apps/standalone/src/lightweight/cls_provider.ts
+++ b/apps/standalone/src/lightweight/cls_provider.ts
@@ -39,6 +39,7 @@ export default class BrowserExecutionContext implements ExecutionContext {
// Cancel any pending cleanup timer for this context
const existingTimer = this.cleanupTimers.get(context);
+ /* v8 ignore next 3 -- @preserve: `context` is freshly created above, so it can never already have a pending cleanup timer; guard kept defensively. */
if (existingTimer) {
clearTimeout(existingTimer);
this.cleanupTimers.delete(context);
diff --git a/apps/standalone/src/lightweight/crypto_provider.spec.ts b/apps/standalone/src/lightweight/crypto_provider.spec.ts
new file mode 100644
index 0000000000..dfbf65e1d6
--- /dev/null
+++ b/apps/standalone/src/lightweight/crypto_provider.spec.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+import aesjs from "aes-js";
+
+import BrowserCryptoProvider from "./crypto_provider.js";
+
+const provider = new BrowserCryptoProvider();
+
+describe("BrowserCryptoProvider hashing", () => {
+ it("produces fixed-length digests for md5/sha1/sha512", () => {
+ expect(provider.createHash("md5", "hello")).toHaveLength(16);
+ expect(provider.createHash("sha1", "hello")).toHaveLength(20);
+ expect(provider.createHash("sha512", "hello")).toHaveLength(64);
+ });
+
+ it("accepts Uint8Array input", () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ expect(provider.createHash("md5", bytes)).toHaveLength(16);
+ });
+
+ it("hmac returns a base64 string", () => {
+ const mac = provider.hmac("secret", "value");
+ expect(typeof mac).toBe("string");
+ // base64 of a 32-byte sha256 digest is 44 chars
+ expect(mac).toHaveLength(44);
+ });
+});
+
+describe("BrowserCryptoProvider random helpers", () => {
+ it("randomBytes returns the requested size", () => {
+ expect(provider.randomBytes(8)).toHaveLength(8);
+ });
+
+ it("randomString returns the requested length using the allowed alphabet", () => {
+ const str = provider.randomString(20);
+ expect(str).toHaveLength(20);
+ expect(str).toMatch(/^[0-9A-Za-z]+$/);
+ });
+});
+
+describe("BrowserCryptoProvider constantTimeCompare", () => {
+ it("returns true for equal arrays", () => {
+ expect(provider.constantTimeCompare(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3]))).toBe(true);
+ });
+
+ it("returns false for different lengths", () => {
+ expect(provider.constantTimeCompare(new Uint8Array([1, 2]), new Uint8Array([1, 2, 3]))).toBe(false);
+ });
+
+ it("returns false for same-length differing content", () => {
+ expect(provider.constantTimeCompare(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 4]))).toBe(false);
+ });
+});
+
+describe("BrowserCryptoProvider scrypt", () => {
+ it("derives a key of the requested length", async () => {
+ const key = await provider.scrypt("password", "salt", 16, { N: 16, r: 1, p: 1 });
+ expect(key).toHaveLength(16);
+ });
+
+ it("uses default scrypt parameters when none are supplied", async () => {
+ const key = await provider.scrypt(new Uint8Array([1]), new Uint8Array([2]), 8, { N: 2 });
+ expect(key).toHaveLength(8);
+ });
+});
+
+describe("AesJsCipher (via createCipheriv/createDecipheriv)", () => {
+ const key = new Uint8Array(16).fill(7);
+ const iv = new Uint8Array(16).fill(9);
+
+ it("round-trips data through encryption and decryption", () => {
+ const plain = new TextEncoder().encode("the quick brown fox");
+
+ const cipher = provider.createCipheriv("aes-128-cbc", key, iv);
+ cipher.update(plain);
+ const encrypted = cipher.final();
+
+ const decipher = provider.createDecipheriv("aes-128-cbc", key, iv);
+ decipher.update(encrypted);
+ const decrypted = decipher.final();
+
+ expect(new TextDecoder().decode(decrypted)).toBe("the quick brown fox");
+ });
+
+ it("throws when update() is called after final()", () => {
+ const cipher = provider.createCipheriv("aes-128-cbc", key, iv);
+ cipher.update(new Uint8Array([1]));
+ cipher.final();
+ expect(() => cipher.update(new Uint8Array([2]))).toThrow("Cipher has already been finalized");
+ });
+
+ it("throws when final() is called twice", () => {
+ const cipher = provider.createCipheriv("aes-128-cbc", key, iv);
+ cipher.final();
+ expect(() => cipher.final()).toThrow("Cipher has already been finalized");
+ });
+
+ it("returns decrypted bytes unchanged when the trailing padding byte is invalid", () => {
+ // Craft a single raw block whose decrypted last byte is 0 (an invalid
+ // PKCS7 padding length), exercising the non-stripping branch in final().
+ const plain = new Uint8Array(16).fill(65);
+ plain[15] = 0;
+ const rawCipher = new Uint8Array(
+ new aesjs.ModeOfOperation.cbc(Array.from(key), Array.from(iv)).encrypt(plain)
+ );
+
+ const decipher = provider.createDecipheriv("aes-128-cbc", key, iv);
+ decipher.update(rawCipher);
+ const out = decipher.final();
+
+ expect(out).toHaveLength(16);
+ expect(out[15]).toBe(0);
+ });
+});
diff --git a/apps/standalone/src/lightweight/log_provider.spec.ts b/apps/standalone/src/lightweight/log_provider.spec.ts
new file mode 100644
index 0000000000..0abfebde64
--- /dev/null
+++ b/apps/standalone/src/lightweight/log_provider.spec.ts
@@ -0,0 +1,238 @@
+import type { LogFileInfo } from "@triliumnext/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import StandaloneLogService from "./log_provider.js";
+
+interface NavWithStorage {
+ storage?: { getDirectory?: () => Promise<unknown> };
+}
+
+interface LogInternals {
+ readonly eol: string;
+ ensureLogDirectory(): Promise<void>;
+ openLogFile(fileName: string): Promise<void>;
+ closeLogFile(): void;
+ writeEntry(entry: string): void;
+ readLogFile(fileName: string): string | null;
+ listLogFiles(): Promise<LogFileInfo[]>;
+ deleteLogFile(fileName: string): Promise<void>;
+ getRetentionDays(): number;
+ currentFile: unknown;
+ currentFileName: string;
+ logDir: unknown;
+}
+
+const realStorageDescriptor = Object.getOwnPropertyDescriptor(navigator, "storage");
+
+/** A fake FileSystemSyncAccessHandle backed by a growable byte array. */
+function makeSyncHandle() {
+ let data = new Uint8Array();
+ const close = vi.fn();
+ return {
+ getSize: () => data.length,
+ truncate: (n: number) => { data = data.slice(0, n); },
+ write: (chunk: ArrayBufferView, opts?: { at?: number }) => {
+ const at = opts?.at ?? 0;
+ const incoming = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
+ if (at + incoming.length > data.length) {
+ const grown = new Uint8Array(at + incoming.length);
+ grown.set(data);
+ data = grown;
+ }
+ data.set(incoming, at);
+ return incoming.length;
+ },
+ read: (view: ArrayBufferView, opts?: { at?: number }) => {
+ const at = opts?.at ?? 0;
+ const out = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
+ const slice = data.subarray(at, at + out.length);
+ out.set(slice);
+ return slice.length;
+ },
+ flush: vi.fn(),
+ close
+ };
+}
+
+/** Install an OPFS root whose log directory uses the given file handle + entries. */
+function installOpfs(opts: {
+ createSyncAccessHandle?: () => Promise<unknown>;
+ entries?: () => AsyncGenerator<[string, unknown]>;
+ removeEntry?: (name: string) => Promise<void>;
+}) {
+ const dir = {
+ async getFileHandle() {
+ return { createSyncAccessHandle: opts.createSyncAccessHandle ?? (async () => makeSyncHandle()) };
+ },
+ async *entries() {
+ if (opts.entries) {
+ yield* opts.entries();
+ }
+ },
+ removeEntry: opts.removeEntry ?? (async () => {})
+ };
+ Object.defineProperty(navigator, "storage", {
+ value: { getDirectory: async () => ({ async getDirectoryHandle() { return dir; } }) },
+ configurable: true
+ });
+ return dir;
+}
+
+function internalsOf(service: StandaloneLogService): LogInternals {
+ return service as unknown as LogInternals;
+}
+
+afterEach(() => {
+ if (realStorageDescriptor) {
+ Object.defineProperty(navigator, "storage", realStorageDescriptor);
+ } else {
+ delete (navigator as unknown as NavWithStorage).storage;
+ }
+ vi.restoreAllMocks();
+});
+
+describe("StandaloneLogService basics", () => {
+ it("uses LF line endings and the default 7-day retention", () => {
+ const internal = internalsOf(new StandaloneLogService());
+ expect(internal.eol).toBe("\n");
+ expect(internal.getRetentionDays()).toBe(7);
+ });
+});
+
+describe("StandaloneLogService file handling", () => {
+ it("opens, writes, reads back, and closes the current log file", async () => {
+ const handle = makeSyncHandle();
+ installOpfs({ createSyncAccessHandle: async () => handle });
+
+ const service = new StandaloneLogService();
+ const internal = internalsOf(service);
+ await internal.ensureLogDirectory();
+ await internal.openLogFile("trilium-2024-01-15.log");
+ expect(internal.currentFileName).toBe("trilium-2024-01-15.log");
+
+ internal.writeEntry("hello world\n");
+ expect(internal.readLogFile("trilium-2024-01-15.log")).toBe("hello world\n");
+
+ // A different file name cannot be read via the sync handle.
+ expect(internal.readLogFile("trilium-2024-01-14.log")).toBeNull();
+
+ internal.closeLogFile();
+ expect(handle.close).toHaveBeenCalled();
+ expect(internal.currentFile).toBeNull();
+ });
+
+ it("opens the directory lazily and replaces an already-open file", async () => {
+ installOpfs({ createSyncAccessHandle: async () => makeSyncHandle() });
+ const service = new StandaloneLogService();
+ const internal = internalsOf(service);
+
+ // No ensureLogDirectory() call first → openLogFile creates the directory.
+ await internal.openLogFile("trilium-2024-02-01.log");
+ await internal.openLogFile("trilium-2024-02-02.log");
+ expect(internal.currentFileName).toBe("trilium-2024-02-02.log");
+ });
+
+ it("retries acquiring the sync handle and recovers", async () => {
+ let attempts = 0;
+ installOpfs({
+ createSyncAccessHandle: async () => {
+ attempts++;
+ if (attempts === 1) {
+ throw new Error("locked");
+ }
+ return makeSyncHandle();
+ }
+ });
+ const internal = internalsOf(new StandaloneLogService());
+ await internal.ensureLogDirectory();
+ await internal.openLogFile("trilium-2024-03-01.log");
+ expect(attempts).toBe(2);
+ expect(internal.currentFileName).toBe("trilium-2024-03-01.log");
+ });
+
+ it("falls back to console-only logging when the handle never opens", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ installOpfs({ createSyncAccessHandle: async () => { throw new Error("always locked"); } });
+ const internal = internalsOf(new StandaloneLogService());
+ await internal.ensureLogDirectory();
+ await internal.openLogFile("trilium-2024-04-01.log");
+ expect(internal.currentFile).toBeNull();
+ expect(internal.currentFileName).toBe("");
+ });
+
+ it("writeEntry logs to the console when no file is open", () => {
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ internalsOf(new StandaloneLogService()).writeEntry("console fallback");
+ expect(logSpy).toHaveBeenCalledWith("console fallback");
+ });
+
+ it("closeLogFile is a no-op when nothing is open", () => {
+ expect(() => internalsOf(new StandaloneLogService()).closeLogFile()).not.toThrow();
+ });
+
+ it("readLogFile returns null without a directory and swallows read errors", async () => {
+ const service = new StandaloneLogService();
+ const internal = internalsOf(service);
+ expect(internal.readLogFile("trilium-2024-01-15.log")).toBeNull();
+
+ // With an open current file whose read throws → caught, returns null.
+ const handle = makeSyncHandle();
+ handle.read = () => { throw new Error("read fail"); };
+ installOpfs({ createSyncAccessHandle: async () => handle });
+ await internal.openLogFile("trilium-2024-05-01.log");
+ expect(internal.readLogFile("trilium-2024-05-01.log")).toBeNull();
+ });
+});
+
+describe("StandaloneLogService listing and deletion", () => {
+ it("lists only well-formed log files with parsed dates", async () => {
+ installOpfs({
+ entries: async function* () {
+ yield ["nested", { kind: "directory" }];
+ yield ["trilium-2024-01-15.log", { kind: "file" }];
+ yield ["not-a-log.txt", { kind: "file" }];
+ }
+ });
+ const internal = internalsOf(new StandaloneLogService());
+ await internal.ensureLogDirectory();
+ const files = await internal.listLogFiles();
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe("trilium-2024-01-15.log");
+ expect(files[0].mtime.getFullYear()).toBe(2024);
+ });
+
+ it("returns an empty list when there is no directory", async () => {
+ expect(await internalsOf(new StandaloneLogService()).listLogFiles()).toEqual([]);
+ });
+
+ it("deletes other files, skips the current file, and ignores removal errors", async () => {
+ const removeEntry = vi.fn(async () => {});
+ installOpfs({ createSyncAccessHandle: async () => makeSyncHandle(), removeEntry });
+ const internal = internalsOf(new StandaloneLogService());
+
+ // No directory yet → early return.
+ await internal.deleteLogFile("trilium-2024-01-01.log");
+ expect(removeEntry).not.toHaveBeenCalled();
+
+ await internal.ensureLogDirectory();
+ await internal.openLogFile("trilium-2024-06-01.log");
+
+ // Skips the current file.
+ await internal.deleteLogFile("trilium-2024-06-01.log");
+ expect(removeEntry).not.toHaveBeenCalled();
+
+ // Deletes a different file.
+ await internal.deleteLogFile("trilium-2024-05-01.log");
+ expect(removeEntry).toHaveBeenCalledWith("trilium-2024-05-01.log");
+ });
+
+ it("swallows errors thrown by removeEntry", async () => {
+ installOpfs({
+ createSyncAccessHandle: async () => makeSyncHandle(),
+ removeEntry: async () => { throw new Error("locked"); }
+ });
+ const internal = internalsOf(new StandaloneLogService());
+ await internal.ensureLogDirectory();
+ await expect(internal.deleteLogFile("trilium-2024-05-01.log")).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/standalone/src/lightweight/log_provider.ts b/apps/standalone/src/lightweight/log_provider.ts
index 7eddc54c33..eef89a007d 100644
--- a/apps/standalone/src/lightweight/log_provider.ts
+++ b/apps/standalone/src/lightweight/log_provider.ts
@@ -131,6 +131,7 @@ export default class StandaloneLogService extends FileBasedLogService {
// OPFS doesn't provide mtime directly, so we parse from filename
const match = name.match(/trilium-(\d{4})-(\d{2})-(\d{2})\.log/);
+ /* v8 ignore next -- @preserve: `name` already matched LOG_FILE_PATTERN above, so this equivalent regex always matches. */
if (match) {
const mtime = new Date(
parseInt(match[1]),
diff --git a/apps/standalone/src/lightweight/messaging_provider.spec.ts b/apps/standalone/src/lightweight/messaging_provider.spec.ts
new file mode 100644
index 0000000000..ca0553d6e5
--- /dev/null
+++ b/apps/standalone/src/lightweight/messaging_provider.spec.ts
@@ -0,0 +1,145 @@
+import type { WebSocketMessage } from "@triliumnext/commons";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import WorkerMessagingProvider from "./messaging_provider.js";
+
+const created: WorkerMessagingProvider[] = [];
+
+function makeProvider(): WorkerMessagingProvider {
+ const provider = new WorkerMessagingProvider();
+ created.push(provider);
+ return provider;
+}
+
+function dispatch(data: unknown) {
+ self.dispatchEvent(new MessageEvent("message", { data }));
+}
+
+const wsMessage = { type: "frontend-update", data: {} } as unknown as WebSocketMessage;
+
+afterEach(() => {
+ while (created.length) {
+ created.pop()?.dispose();
+ }
+ vi.restoreAllMocks();
+});
+
+describe("WorkerMessagingProvider inbound", () => {
+ it("dispatches WS_MESSAGE to the client handler and all registered handlers", () => {
+ const provider = makeProvider();
+ const clientHandler = vi.fn();
+ const handlerA = vi.fn();
+ const handlerB = vi.fn();
+ provider.setClientMessageHandler(clientHandler);
+ provider.onMessage(handlerA);
+ provider.onMessage(handlerB);
+
+ dispatch({ type: "WS_MESSAGE", message: wsMessage });
+
+ expect(clientHandler).toHaveBeenCalledWith("main-thread", wsMessage);
+ expect(handlerA).toHaveBeenCalledWith(wsMessage);
+ expect(handlerB).toHaveBeenCalledWith(wsMessage);
+ });
+
+ it("ignores non-WS_MESSAGE and empty events", () => {
+ const provider = makeProvider();
+ const handler = vi.fn();
+ provider.onMessage(handler);
+
+ dispatch({ type: "SOMETHING_ELSE", message: wsMessage });
+ dispatch(undefined);
+ dispatch({ type: "WS_MESSAGE" });
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("does nothing once disposed", () => {
+ const provider = makeProvider();
+ const handler = vi.fn();
+ provider.onMessage(handler);
+ provider.dispose();
+
+ // dispose() also removes the event listener, so a normal dispatch never
+ // reaches the handler. Invoke it directly to exercise the in-handler
+ // disposed guard as well.
+ dispatch({ type: "WS_MESSAGE", message: wsMessage });
+ const internal = provider as unknown as { handleIncomingMessage(e: MessageEvent): void };
+ internal.handleIncomingMessage(new MessageEvent("message", { data: { type: "WS_MESSAGE", message: wsMessage } }));
+
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("isolates errors thrown by the client handler and message handlers", () => {
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const provider = makeProvider();
+ provider.setClientMessageHandler(() => { throw new Error("client boom"); });
+ provider.onMessage(() => { throw new Error("handler boom"); });
+
+ expect(() => dispatch({ type: "WS_MESSAGE", message: wsMessage })).not.toThrow();
+ expect(consoleSpy).toHaveBeenCalledTimes(2);
+ });
+
+ it("onMessage returns an unsubscribe function", () => {
+ const provider = makeProvider();
+ const handler = vi.fn();
+ const unsubscribe = provider.onMessage(handler);
+ unsubscribe();
+
+ dispatch({ type: "WS_MESSAGE", message: wsMessage });
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
+
+describe("WorkerMessagingProvider outbound", () => {
+ it("posts WS_MESSAGE envelopes to all clients", () => {
+ const postSpy = vi.spyOn(self, "postMessage").mockImplementation(() => {});
+ const provider = makeProvider();
+
+ provider.sendMessageToAllClients(wsMessage);
+ expect(postSpy).toHaveBeenCalledWith({ type: "WS_MESSAGE", message: wsMessage });
+ });
+
+ it("sendMessageToClient delegates to sendMessageToAllClients and returns true", () => {
+ const postSpy = vi.spyOn(self, "postMessage").mockImplementation(() => {});
+ const provider = makeProvider();
+
+ expect(provider.sendMessageToClient("ignored", wsMessage)).toBe(true);
+ expect(postSpy).toHaveBeenCalledWith({ type: "WS_MESSAGE", message: wsMessage });
+ });
+
+ it("warns and skips sending when disposed", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const postSpy = vi.spyOn(self, "postMessage").mockImplementation(() => {});
+ const provider = makeProvider();
+ provider.dispose();
+
+ provider.sendMessageToAllClients(wsMessage);
+ expect(provider.sendMessageToClient("x", wsMessage)).toBe(false);
+ expect(postSpy).not.toHaveBeenCalled();
+ expect(warnSpy).toHaveBeenCalled();
+ });
+
+ it("isolates errors thrown while posting", () => {
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.spyOn(self, "postMessage").mockImplementation(() => { throw new Error("post boom"); });
+ const provider = makeProvider();
+
+ expect(() => provider.sendMessageToAllClients(wsMessage)).not.toThrow();
+ expect(consoleSpy).toHaveBeenCalled();
+ });
+});
+
+describe("WorkerMessagingProvider lifecycle", () => {
+ it("reports a single client until disposed, then zero", () => {
+ const provider = makeProvider();
+ expect(provider.getClientCount()).toBe(1);
+ provider.dispose();
+ expect(provider.getClientCount()).toBe(0);
+ });
+
+ it("dispose() is idempotent", () => {
+ const provider = makeProvider();
+ provider.dispose();
+ expect(() => provider.dispose()).not.toThrow();
+ });
+});
diff --git a/apps/standalone/src/lightweight/platform_provider.spec.ts b/apps/standalone/src/lightweight/platform_provider.spec.ts
new file mode 100644
index 0000000000..a46da8e631
--- /dev/null
+++ b/apps/standalone/src/lightweight/platform_provider.spec.ts
@@ -0,0 +1,44 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import StandalonePlatformProvider from "./platform_provider.js";
+
+describe("StandalonePlatformProvider", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("exposes the standalone platform flags", () => {
+ const provider = new StandalonePlatformProvider("");
+ expect(provider.isElectron).toBe(false);
+ expect(provider.isMac).toBe(false);
+ expect(provider.isWindows).toBe(false);
+ });
+
+ it("maps known query parameters to TRILIUM_ env vars", () => {
+ const provider = new StandalonePlatformProvider("?safeMode=1&startNoteId=abc123");
+ expect(provider.getEnv("TRILIUM_SAFE_MODE")).toBe("1");
+ expect(provider.getEnv("TRILIUM_START_NOTE_ID")).toBe("abc123");
+ });
+
+ it("defaults a valueless query flag to \"true\"", () => {
+ const provider = new StandalonePlatformProvider("?safeMode");
+ expect(provider.getEnv("TRILIUM_SAFE_MODE")).toBe("true");
+ });
+
+ it("ignores unknown query parameters and returns undefined for unset env", () => {
+ const provider = new StandalonePlatformProvider("?unknown=x");
+ expect(provider.getEnv("TRILIUM_SAFE_MODE")).toBeUndefined();
+ expect(provider.getEnv("TRILIUM_START_NOTE_ID")).toBeUndefined();
+ });
+
+ it("crash() logs and posts a FATAL_ERROR message", () => {
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const postSpy = vi.spyOn(self, "postMessage").mockImplementation(() => {});
+
+ const provider = new StandalonePlatformProvider("");
+ provider.crash("boom");
+
+ expect(consoleSpy).toHaveBeenCalledWith("[Standalone] FATAL:", "boom");
+ expect(postSpy).toHaveBeenCalledWith({ type: "FATAL_ERROR", message: "boom" });
+ });
+});
diff --git a/apps/standalone/src/lightweight/platform_provider.ts b/apps/standalone/src/lightweight/platform_provider.ts
index 9c5e2f1186..6e97f283ae 100644
--- a/apps/standalone/src/lightweight/platform_provider.ts
+++ b/apps/standalone/src/lightweight/platform_provider.ts
@@ -23,6 +23,7 @@ export default class StandalonePlatformProvider implements PlatformProvider {
this.envMap[envKey] = params.get(queryKey) || "true";
}
}
+ /* v8 ignore next 3 -- @preserve: __TRILIUM_INTEGRATION_TEST__ is inlined empty outside integration builds, so this branch is unreachable under the standard (CI) build. */
if (__TRILIUM_INTEGRATION_TEST__) {
this.envMap["TRILIUM_INTEGRATION_TEST"] = __TRILIUM_INTEGRATION_TEST__;
}
diff --git a/apps/standalone/src/lightweight/request_provider.spec.ts b/apps/standalone/src/lightweight/request_provider.spec.ts
new file mode 100644
index 0000000000..3cfa07badc
--- /dev/null
+++ b/apps/standalone/src/lightweight/request_provider.spec.ts
@@ -0,0 +1,152 @@
+import type { ExecOpts } from "@triliumnext/core";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import FetchRequestProvider from "./request_provider.js";
+
+const provider = new FetchRequestProvider();
+
+interface FakeResponse {
+ status?: number;
+ ok?: boolean;
+ text?: () => Promise<string>;
+ arrayBuffer?: () => Promise<ArrayBuffer>;
+}
+
+function mockFetch(response: FakeResponse | Error) {
+ const impl = response instanceof Error
+ ? vi.fn().mockRejectedValue(response)
+ : vi.fn().mockResolvedValue(response);
+ return vi.spyOn(globalThis, "fetch").mockImplementation(impl as unknown as typeof fetch);
+}
+
+function lastInit(spy: ReturnType<typeof mockFetch>): RequestInit {
+ return spy.mock.calls[0][1] as RequestInit;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe("FetchRequestProvider.exec", () => {
+ it("sends a JSON request and parses a 200 response", async () => {
+ const spy = mockFetch({ status: 200, text: async () => JSON.stringify({ value: 1 }) });
+
+ const result = await provider.exec<{ value: number }>({ method: "GET", url: `${location.origin}/api/x` } as ExecOpts);
+
+ expect(result).toEqual({ value: 1 });
+ const init = lastInit(spy);
+ const headers = init.headers as Record<string, string>;
+ expect(headers["Content-Type"]).toBe("application/json");
+ expect(init.credentials).toBe("include");
+ });
+
+ it("uses text/plain and paging headers for multi-page requests", async () => {
+ const spy = mockFetch({ status: 200, text: async () => "" });
+
+ await provider.exec({
+ method: "POST",
+ url: `${location.origin}/api/x`,
+ paging: { pageCount: 3, pageIndex: 1, requestId: "req-1" }
+ } as ExecOpts);
+
+ const headers = lastInit(spy).headers as Record<string, string>;
+ expect(headers["Content-Type"]).toBe("text/plain");
+ expect(headers["pageCount"]).toBe("3");
+ expect(headers["pageIndex"]).toBe("1");
+ expect(headers["requestId"]).toBe("req-1");
+ });
+
+ it("returns null for an empty/whitespace 204 body", async () => {
+ mockFetch({ status: 204, text: async () => " " });
+ const result = await provider.exec({ method: "GET", url: `${location.origin}/api/x` } as ExecOpts);
+ expect(result).toBeNull();
+ });
+
+ it("adds a trilium-cred header when auth is provided", async () => {
+ const spy = mockFetch({ status: 200, text: async () => "{}" });
+ await provider.exec({ method: "GET", url: `${location.origin}/x`, auth: { password: "pw" } } as ExecOpts);
+ const headers = lastInit(spy).headers as Record<string, string>;
+ expect(headers["trilium-cred"]).toBe(btoa("dummy:pw"));
+ });
+
+ it("serializes object bodies as JSON and passes string bodies through", async () => {
+ const spy = mockFetch({ status: 200, text: async () => "{}" });
+ await provider.exec({ method: "POST", url: `${location.origin}/x`, body: { a: 1 } } as ExecOpts);
+ expect(lastInit(spy).body).toBe(JSON.stringify({ a: 1 }));
+
+ spy.mockClear();
+ await provider.exec({ method: "POST", url: `${location.origin}/x`, body: "raw" } as ExecOpts);
+ expect(lastInit(spy).body).toBe("raw");
+ });
+
+ it("throws with the JSON error message for non-2xx responses", async () => {
+ mockFetch({ status: 500, text: async () => JSON.stringify({ message: "boom" }) });
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts))
+ .rejects.toThrow("500 GET");
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts))
+ .rejects.toThrow("boom");
+ });
+
+ it("falls back to the raw text (truncated) when the error body is not JSON", async () => {
+ mockFetch({ status: 400, text: async () => "x".repeat(200) });
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts))
+ .rejects.toThrow(/400 GET .*x{100}/);
+ });
+
+ it("reports a timeout when the request is aborted", async () => {
+ const abortErr = Object.assign(new Error("aborted"), { name: "AbortError" });
+ mockFetch(abortErr);
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x`, timeout: 50 } as ExecOpts))
+ .rejects.toThrow("timeout after 50ms");
+ });
+
+ it("aborts the in-flight request once the timeout elapses", async () => {
+ vi.useFakeTimers();
+ const abortErr = Object.assign(new Error("aborted"), { name: "AbortError" });
+ vi.spyOn(globalThis, "fetch").mockImplementation((_url, init) => new Promise<Response>((_resolve, reject) => {
+ (init?.signal as AbortSignal).addEventListener("abort", () => reject(abortErr));
+ }));
+ const promise = provider.exec({ method: "GET", url: `${location.origin}/x`, timeout: 50 } as ExecOpts);
+ const rejection = expect(promise).rejects.toThrow("timeout after 50ms");
+ await vi.advanceTimersByTimeAsync(50);
+ await rejection;
+ });
+
+ it("throws with an empty message when the error body has no message field", async () => {
+ mockFetch({ status: 500, text: async () => JSON.stringify({ code: "X" }) });
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts)).rejects.toThrow(/500 GET/);
+ });
+
+ it("gives a CORS-specific message for cross-origin fetch failures", async () => {
+ mockFetch(new TypeError("Failed to fetch"));
+ await expect(provider.exec({ method: "GET", url: "https://other.example.com/x" } as ExecOpts))
+ .rejects.toThrow(/blocked.*CORS/);
+ });
+
+ it("gives a generic unreachable message for same-origin fetch failures", async () => {
+ mockFetch(new TypeError("Failed to fetch"));
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts))
+ .rejects.toThrow(/may be unreachable/);
+ });
+
+ it("rethrows unrecognized errors", async () => {
+ mockFetch(new Error("something else"));
+ await expect(provider.exec({ method: "GET", url: `${location.origin}/x` } as ExecOpts))
+ .rejects.toThrow("something else");
+ });
+});
+
+describe("FetchRequestProvider.getImage", () => {
+ it("returns the image bytes for a successful response", async () => {
+ const buf = new Uint8Array([1, 2, 3]).buffer;
+ mockFetch({ ok: true, status: 200, arrayBuffer: async () => buf });
+ const result = await provider.getImage(`${location.origin}/img.png`);
+ expect(result).toBe(buf);
+ });
+
+ it("throws when the image response is not ok", async () => {
+ mockFetch({ ok: false, status: 404, arrayBuffer: async () => new ArrayBuffer(0) });
+ await expect(provider.getImage(`${location.origin}/missing.png`)).rejects.toThrow("404 GET");
+ });
+});
diff --git a/apps/standalone/src/lightweight/sql_provider.spec.ts b/apps/standalone/src/lightweight/sql_provider.spec.ts
new file mode 100644
index 0000000000..0b1520f0d8
--- /dev/null
+++ b/apps/standalone/src/lightweight/sql_provider.spec.ts
@@ -0,0 +1,519 @@
+import { getSql } from "@triliumnext/core";
+import type { Statement } from "@triliumnext/core";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+import BrowserSqlProvider from "./sql_provider.js";
+
+// The sqlite-wasm module can only be initialized once per worker (test_setup.ts
+// already does it for core). Reuse that initialized module rather than calling
+// initWasm() again, which would fail to re-locate the .wasm file.
+type WithSqlite3 = { sqlite3: unknown };
+
+/** The runtime statement exposes finalize(), which the core interface omits. */
+type FinalizableStatement = Statement & { finalize(): void };
+
+/** The runtime transaction is callable and exposes better-sqlite3-style variants. */
+type FullTransaction = (() => unknown) & {
+ deferred: () => unknown;
+ immediate: () => unknown;
+ exclusive: () => unknown;
+ default: () => unknown;
+};
+
+function coreProvider(): BrowserSqlProvider {
+ return (getSql() as unknown as { dbConnection: BrowserSqlProvider }).dbConnection;
+}
+
+function newProviderWithModule(): BrowserSqlProvider {
+ const p = new BrowserSqlProvider();
+ (p as unknown as WithSqlite3).sqlite3 = (coreProvider() as unknown as WithSqlite3).sqlite3;
+ return p;
+}
+
+let provider: BrowserSqlProvider;
+
+/** Pluck a single scalar from a parameterless query. */
+function scalar(query: string): unknown {
+ return provider.prepare(query).pluck().get([]);
+}
+
+function makeTx(fn: () => unknown): FullTransaction {
+ return provider.transaction(fn) as unknown as FullTransaction;
+}
+
+beforeAll(() => {
+ provider = newProviderWithModule();
+ provider.loadFromMemory();
+ provider.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT, val INTEGER)");
+});
+
+afterAll(() => {
+ provider.close();
+});
+
+describe("BrowserSqlProvider initialization", () => {
+ it("reports initialization state and version", () => {
+ expect(provider.isInitialized).toBe(true);
+ expect(provider.version?.libVersion).toMatch(/^\d/);
+ });
+
+ it("initWasm() resolves immediately when already initialized", async () => {
+ // Hits the early `if (this.initPromise) return this.initPromise` path
+ // without re-running the (one-shot) WASM module loader.
+ await expect(coreProvider().initWasm()).resolves.toBeUndefined();
+ });
+
+ it("re-throws a previous initialization error", async () => {
+ const failed = new BrowserSqlProvider();
+ (failed as unknown as { initError: Error }).initError = new Error("prior init failure");
+ await expect(failed.initWasm()).rejects.toThrow("prior init failure");
+ });
+
+ it("throws from ensureSqlite3 before initialization", () => {
+ const fresh = new BrowserSqlProvider();
+ expect(fresh.isInitialized).toBe(false);
+ expect(fresh.version).toBeUndefined();
+ expect(() => fresh.loadFromMemory()).toThrow("SQLite WASM module not initialized");
+ });
+
+ it("throws from ensureDb when initialized but no database is open", () => {
+ const noDb = newProviderWithModule();
+ expect(noDb.isOpen()).toBe(false);
+ expect(() => noDb.exec("SELECT 1")).toThrow("Database not opened");
+ });
+});
+
+describe("BrowserSqlProvider unsupported operations", () => {
+ it("loadFromFile and backup are not supported in the browser", () => {
+ expect(() => provider.loadFromFile("/x", false)).toThrow("loadFromFile is not supported");
+ expect(() => provider.backup("/x")).toThrow("backup to file is not supported");
+ });
+});
+
+// Statements are cached by SQL string and raw()/pluck() flags are sticky on the
+// cached instance, so each mode-sensitive assertion uses a distinct query string.
+describe("WasmStatement reads and writes", () => {
+ beforeAll(() => {
+ provider.exec("DELETE FROM t");
+ provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("alice", 1);
+ provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("bob", 2);
+ });
+
+ it("run() reports changes and lastInsertRowid", () => {
+ const result = provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("carol", 3);
+ expect(result.changes).toBe(1);
+ expect(typeof result.lastInsertRowid).toBe("number");
+ expect(result.lastInsertRowid).toBeGreaterThan(0);
+ provider.prepare("DELETE FROM t WHERE name = ?").run("carol");
+ });
+
+ it("get() returns a single row as an object, or undefined when missing", () => {
+ const row = provider.prepare("SELECT name, val FROM t WHERE name = ? /* obj */").get("alice");
+ expect(row).toEqual({ name: "alice", val: 1 });
+ expect(provider.prepare("SELECT id FROM t WHERE name = ? /* miss */").get("nobody")).toBeUndefined();
+ });
+
+ it("get() with raw mode returns an array row", () => {
+ const row = provider.prepare("SELECT name, val FROM t WHERE name = ? /* raw */").raw().get("alice");
+ expect(row).toEqual(["alice", 1]);
+ });
+
+ it("get() with pluck mode returns the first column", () => {
+ const value = provider.prepare("SELECT name FROM t WHERE name = ? /* pluck */").pluck().get("bob");
+ expect(value).toBe("bob");
+ });
+
+ it("all() returns every row, honoring raw and pluck modes", () => {
+ expect(provider.prepare("SELECT name FROM t ORDER BY name /* all-obj */").all()).toEqual([{ name: "alice" }, { name: "bob" }]);
+ expect(provider.prepare("SELECT name FROM t ORDER BY name /* all-pluck */").pluck().all()).toEqual(["alice", "bob"]);
+ expect(provider.prepare("SELECT name FROM t ORDER BY name /* all-raw */").raw().all()).toEqual([["alice"], ["bob"]]);
+ });
+
+ it("iterate() yields rows in object, raw and pluck modes", () => {
+ expect([...provider.prepare("SELECT name FROM t ORDER BY name /* it-obj */").iterate()])
+ .toEqual([{ name: "alice" }, { name: "bob" }]);
+ expect([...provider.prepare("SELECT name FROM t ORDER BY name /* it-raw */").raw().iterate()])
+ .toEqual([["alice"], ["bob"]]);
+ expect([...provider.prepare("SELECT name FROM t ORDER BY name /* it-pluck */").pluck().iterate()])
+ .toEqual(["alice", "bob"]);
+ });
+
+ it("toggling raw/pluck off restores object rows", () => {
+ const stmt = provider.prepare("SELECT name FROM t WHERE name = ? /* toggle */").raw().pluck();
+ stmt.raw(false).pluck(false);
+ expect(stmt.get("alice")).toEqual({ name: "alice" });
+ });
+
+ it("caches prepared statements per query string", () => {
+ const a = provider.prepare("SELECT 1 AS one");
+ const b = provider.prepare("SELECT 1 AS one");
+ expect(a).toBe(b);
+ });
+});
+
+describe("WasmStatement parameter binding", () => {
+ beforeAll(() => {
+ provider.exec("DELETE FROM t");
+ provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("alice", 1);
+ });
+
+ it("binds named parameters with :, @ and $ prefixes", () => {
+ expect(provider.prepare("SELECT val FROM t WHERE name = :name").pluck().get({ name: "alice" })).toBe(1);
+ expect(provider.prepare("SELECT val FROM t WHERE name = @name").pluck().get({ name: "alice" })).toBe(1);
+ expect(provider.prepare("SELECT val FROM t WHERE name = $name").pluck().get({ name: "alice" })).toBe(1);
+ });
+
+ it("accepts already-prefixed parameter keys", () => {
+ expect(provider.prepare("SELECT val FROM t WHERE name = :name /* prefixed */").pluck().get({ ":name": "alice" })).toBe(1);
+ });
+
+ it("binds positional parameters, including nested arrays", () => {
+ const rows = provider.prepare("SELECT name FROM t WHERE name IN (?, ?)").pluck().all(["alice", "missing"]);
+ expect(rows).toEqual(["alice"]);
+ });
+
+ it("runs a statement with no parameters", () => {
+ expect(scalar("SELECT COUNT(*) AS c FROM t")).toBe(1);
+ });
+});
+
+describe("WasmStatement finalization", () => {
+ it("rejects all operations after finalize()", () => {
+ const stmt = provider.prepare("SELECT 1 AS one WHERE 1 = ?") as FinalizableStatement;
+ stmt.finalize();
+ stmt.finalize(); // idempotent
+ expect(() => stmt.run(1)).toThrow("finalized");
+ expect(() => stmt.get(1)).toThrow("finalized");
+ expect(() => stmt.all(1)).toThrow("finalized");
+ expect(() => stmt.iterate(1)).toThrow("finalized");
+ });
+});
+
+describe("BrowserSqlProvider transactions", () => {
+ beforeAll(() => {
+ provider.exec("DELETE FROM t");
+ });
+
+ it("commits a successful transaction and tracks inTransaction", () => {
+ expect(provider.inTransaction).toBe(false);
+ const result = makeTx(() => {
+ expect(provider.inTransaction).toBe(true);
+ provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("tx1", 1);
+ return "ok";
+ })();
+ expect(result).toBe("ok");
+ expect(provider.inTransaction).toBe(false);
+ expect(scalar("SELECT COUNT(*) AS c FROM t")).toBe(1);
+ });
+
+ it("rolls back when the transaction throws", () => {
+ expect(() => makeTx(() => {
+ provider.prepare("INSERT INTO t (name, val) VALUES (?, ?)").run("doomed", 9);
+ throw new Error("rollback me");
+ })()).toThrow("rollback me");
+ expect(provider.prepare("SELECT COUNT(*) AS c FROM t WHERE name = ?").pluck().get("doomed")).toBe(0);
+ });
+
+ it("supports deferred, immediate, exclusive and default variants", () => {
+ provider.exec("DELETE FROM t");
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("d")).deferred();
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("i")).immediate();
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("e")).exclusive();
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("x")).default();
+ expect(scalar("SELECT COUNT(*) AS c FROM t")).toBe(4);
+ });
+
+ it("nests via SAVEPOINT and releases / rolls back independently", () => {
+ provider.exec("DELETE FROM t");
+ makeTx(() => {
+ provider.prepare("INSERT INTO t (name) VALUES (?)").run("outer");
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("inner-ok"))();
+ expect(() => makeTx(() => {
+ provider.prepare("INSERT INTO t (name) VALUES (?)").run("inner-bad");
+ throw new Error("inner boom");
+ })()).toThrow("inner boom");
+ return undefined;
+ })();
+
+ expect(provider.prepare("SELECT name FROM t ORDER BY name /* names */").pluck().all()).toEqual(["inner-ok", "outer"]);
+ });
+
+ it("uses SAVEPOINT when a manual BEGIN is already active", () => {
+ provider.exec("DELETE FROM t");
+ provider.exec("BEGIN");
+ try {
+ expect(provider.inTransaction).toBe(false); // not started via transaction()
+ makeTx(() => provider.prepare("INSERT INTO t (name) VALUES (?)").run("manual"))();
+ provider.exec("COMMIT");
+ } catch (e) {
+ provider.exec("ROLLBACK");
+ throw e;
+ }
+ expect(scalar("SELECT COUNT(*) AS c FROM t")).toBe(1);
+ });
+});
+
+describe("BrowserSqlProvider serialize / load / lifecycle", () => {
+ it("serializes and reloads the database from a buffer", () => {
+ const local = newProviderWithModule();
+ local.loadFromMemory();
+ local.exec("CREATE TABLE notes (noteId TEXT)");
+ local.exec("INSERT INTO notes VALUES ('hello')");
+ expect(local.isDbInitialized()).toBe(true);
+
+ const bytes = local.serialize();
+ expect(bytes).toBeInstanceOf(Uint8Array);
+
+ const reloaded = newProviderWithModule();
+ reloaded.loadFromBuffer(bytes);
+ expect(reloaded.prepare("SELECT noteId FROM notes").pluck().get([])).toBe("hello");
+ reloaded.close();
+ local.close();
+ });
+
+ it("isDbInitialized() is false for a database without the notes table", () => {
+ const empty = newProviderWithModule();
+ empty.loadFromMemory();
+ expect(empty.isDbInitialized()).toBe(false);
+ empty.close();
+ });
+
+ it("normalizes a Node Buffer passed to loadFromBuffer", () => {
+ const seed = newProviderWithModule();
+ seed.loadFromMemory();
+ seed.exec("CREATE TABLE notes (noteId TEXT)");
+ const bytes = seed.serialize();
+ seed.close();
+
+ const reloaded = newProviderWithModule();
+ reloaded.loadFromBuffer(Buffer.from(bytes));
+ expect(reloaded.isDbInitialized()).toBe(true);
+ reloaded.close();
+ });
+
+ it("close() drops the connection and is idempotent", () => {
+ const local = newProviderWithModule();
+ local.loadFromMemory();
+ expect(local.isOpen()).toBe(true);
+ local.close();
+ expect(local.isOpen()).toBe(false);
+ local.close();
+ });
+
+ it("changes() reflects the last write", () => {
+ const local = newProviderWithModule();
+ local.loadFromMemory();
+ local.exec("CREATE TABLE c (id INTEGER)");
+ local.prepare("INSERT INTO c VALUES (1)").run([]);
+ expect(local.changes()).toBe(1);
+ local.close();
+ });
+});
+
+describe("BrowserSqlProvider SAHPool VFS", () => {
+ interface FakeUtil {
+ reserveMinimumCapacity: (n: number) => Promise<void>;
+ getCapacity: () => number;
+ getFileCount: () => number;
+ OpfsSAHPoolDb: new (name: string) => { exec: (sql: string) => void; close: () => void };
+ }
+
+ function fakeUtil(dbThrows = false): FakeUtil {
+ return {
+ reserveMinimumCapacity: vi.fn(async () => {}),
+ getCapacity: () => 6,
+ getFileCount: () => 0,
+ OpfsSAHPoolDb: class {
+ constructor(_name: string) {
+ if (dbThrows) {
+ throw new Error("cannot open SAHPool db");
+ }
+ }
+ exec() {}
+ close() {}
+ }
+ };
+ }
+
+ function providerWith(installImpl: () => Promise<FakeUtil>): BrowserSqlProvider {
+ const p = new BrowserSqlProvider();
+ (p as unknown as WithSqlite3).sqlite3 = { installOpfsSAHPoolVfs: installImpl };
+ return p;
+ }
+
+ it("reports SAHPool getters as inactive before installation", () => {
+ const p = newProviderWithModule();
+ expect(p.isSahPoolInstalled).toBe(false);
+ expect(p.sahPool).toBeUndefined();
+ expect(p.isUsingSahPool).toBe(false);
+ expect(p.isUsingOpfs).toBe(false);
+ expect(p.currentOpfsPath).toBeUndefined();
+ });
+
+ it("installs the SAHPool VFS and loads a database from it", async () => {
+ const util = fakeUtil();
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const p = providerWith(async () => util);
+
+ await p.installSahPool({ directory: "/pool", initialCapacity: 8 });
+ expect(p.isSahPoolInstalled).toBe(true);
+ expect(p.sahPool).toBe(util);
+
+ p.loadFromSahPool("/trilium.db");
+ expect(p.isUsingSahPool).toBe(true);
+ expect(p.isUsingOpfs).toBe(true);
+ expect(p.currentOpfsPath).toBe("/trilium.db");
+ vi.restoreAllMocks();
+ });
+
+ it("installs with default options", async () => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const p = providerWith(async () => fakeUtil());
+ await p.installSahPool();
+ expect(p.isSahPoolInstalled).toBe(true);
+ vi.restoreAllMocks();
+ });
+
+ it("throws from loadFromSahPool when the VFS is not installed", () => {
+ const p = newProviderWithModule();
+ expect(() => p.loadFromSahPool("/trilium.db")).toThrow("SAHPool VFS not installed");
+ });
+
+ it("re-throws (and logs) when opening the SAHPool database fails", async () => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const p = providerWith(async () => fakeUtil(true));
+ await p.installSahPool();
+ expect(() => p.loadFromSahPool("/trilium.db")).toThrow("cannot open SAHPool db");
+ vi.restoreAllMocks();
+ });
+
+ it("propagates errors thrown while installing the VFS", async () => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const p = providerWith(async () => { throw new Error("no OPFS here"); });
+ await expect(p.installSahPool()).rejects.toThrow("no OPFS here");
+ vi.restoreAllMocks();
+ });
+
+ it("wraps a non-Error thrown while opening the SAHPool database", async () => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const p = providerWith(async () => ({
+ reserveMinimumCapacity: vi.fn(async () => {}),
+ getCapacity: () => 6,
+ getFileCount: () => 0,
+ OpfsSAHPoolDb: class {
+ constructor() { throw "string failure"; }
+ exec() {}
+ close() {}
+ }
+ }));
+ await p.installSahPool();
+ expect(() => p.loadFromSahPool("/x.db")).toThrow("string failure");
+ vi.restoreAllMocks();
+ });
+});
+
+describe("BrowserSqlProvider error and defensive paths", () => {
+ it("resets the statement and rethrows when run() fails", () => {
+ provider.exec("DELETE FROM t");
+ const insert = provider.prepare("INSERT INTO t (id, name) VALUES (?, ?)");
+ insert.run(1, "first");
+ // Re-inserting the same primary key violates the UNIQUE constraint inside step().
+ expect(() => insert.run(1, "dup")).toThrow();
+ // The statement is reusable afterwards (it was reset in the catch block).
+ expect(insert.run(2, "second").changes).toBe(1);
+ });
+
+ it("falls back to the ':' parameter prefix for names absent from the SQL", () => {
+ // detectParamPrefix() returns ':' for a name with no prefixed match in the
+ // SQL; binding an unknown parameter then fails inside sqlite-wasm.
+ expect(() => provider.prepare("SELECT 1 AS x /* ghost */").get({ ghost: 1 })).toThrow();
+ });
+
+ it("treats an explicit undefined parameter as no bindings", () => {
+ expect(provider.prepare("SELECT 1 AS one /* undef */").pluck().get(undefined as unknown as [])).toBe(1);
+ });
+
+ it("warns but does not throw when the underlying statement fails to finalize", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const stmt = provider.prepare("SELECT 42 AS answer /* bad-finalize */") as unknown as { stmt: { finalize(): void }; finalize(): void };
+ stmt.stmt = { finalize() { throw new Error("cannot finalize"); } };
+ expect(() => stmt.finalize()).not.toThrow();
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("swallows errors from cached statements during clearStatementCache()", () => {
+ const local = newProviderWithModule();
+ local.loadFromMemory();
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const cache = (local as unknown as { statementCache: Map<string, { finalize(): void }> }).statementCache;
+ cache.set("boom", { finalize() { throw new Error("cleanup failure"); } });
+ expect(() => local.close()).not.toThrow();
+ expect(warn).toHaveBeenCalled();
+ vi.restoreAllMocks();
+ });
+
+ it("deallocates and rethrows when deserialization fails", () => {
+ const dealloc = vi.fn();
+ const fakeSqlite3 = {
+ wasm: { allocFromTypedArray: () => 999, dealloc },
+ oo1: { DB: class { pointer = 1; close() {} } },
+ capi: {
+ sqlite3_deserialize: () => 1,
+ SQLITE_DESERIALIZE_FREEONCLOSE: 1,
+ SQLITE_DESERIALIZE_RESIZEABLE: 2
+ }
+ };
+ const p = new BrowserSqlProvider();
+ (p as unknown as WithSqlite3).sqlite3 = fakeSqlite3;
+ expect(() => p.loadFromBuffer(new Uint8Array([1, 2, 3]))).toThrow("Failed to deserialize database: 1");
+ expect(dealloc).toHaveBeenCalledWith(999);
+ });
+
+ it("run() tolerates a missing db pointer and converts bigint rowids", () => {
+ const ws = provider.prepare("INSERT INTO t (name) VALUES (?) /* rowid-defensive */") as unknown as {
+ stmt: unknown; db: unknown; sqlite3: unknown;
+ run(...p: unknown[]): { lastInsertRowid: number };
+ };
+ const original = { stmt: ws.stmt, db: ws.db, sqlite3: ws.sqlite3 };
+ const fakeStmt = { clearBindings() {}, bind() {}, step() { return false; }, reset() {} };
+ ws.stmt = fakeStmt;
+
+ // db.pointer falsy → rowid defaults to 0
+ ws.db = { pointer: 0, changes: () => 1 };
+ ws.sqlite3 = { capi: { sqlite3_last_insert_rowid: () => 0 } };
+ expect(ws.run("a").lastInsertRowid).toBe(0);
+
+ // bigint rowid → coerced to a number
+ ws.db = { pointer: 1, changes: () => 1 };
+ ws.sqlite3 = { capi: { sqlite3_last_insert_rowid: () => 7n } };
+ expect(ws.run("b").lastInsertRowid).toBe(7);
+
+ Object.assign(ws, original);
+ });
+
+ it("pluck mode yields undefined / skips rows that have no columns", () => {
+ const fakeStmt = (rowsLeft: number) => {
+ let remaining = rowsLeft;
+ return {
+ clearBindings() {}, bind() {},
+ step() { return remaining-- > 0; },
+ get() { return []; },
+ reset() {}
+ };
+ };
+
+ const getStmt = provider.prepare("SELECT 1 /* pluck-empty-get */").pluck() as unknown as { stmt: unknown; get(p: unknown): unknown };
+ getStmt.stmt = fakeStmt(1);
+ expect(getStmt.get([])).toBeUndefined();
+
+ const allStmt = provider.prepare("SELECT 1 /* pluck-empty-all */").pluck() as unknown as { stmt: unknown; all(...p: unknown[]): unknown[] };
+ allStmt.stmt = fakeStmt(1);
+ expect(allStmt.all()).toEqual([]);
+
+ const iterStmt = provider.prepare("SELECT 1 /* pluck-empty-iter */").pluck() as unknown as { stmt: unknown; iterate(...p: unknown[]): IterableIterator<unknown> };
+ iterStmt.stmt = fakeStmt(1);
+ expect([...iterStmt.iterate()]).toEqual([undefined]);
+ });
+});
diff --git a/apps/standalone/src/lightweight/sql_provider.ts b/apps/standalone/src/lightweight/sql_provider.ts
index 3cf299eda6..9a73266596 100644
--- a/apps/standalone/src/lightweight/sql_provider.ts
+++ b/apps/standalone/src/lightweight/sql_provider.ts
@@ -274,11 +274,13 @@ export default class BrowserSqlProvider implements DatabaseProvider {
`[BrowserSqlProvider] SQLite WASM initialized in ${initTime.toFixed(2)}ms:`,
this.sqlite3.version.libVersion
);
+ /* v8 ignore start -- @preserve: sqlite3InitModule loads once per worker and cannot be made to fail deterministically in the test harness. */
} catch (e) {
this.initError = e instanceof Error ? e : new Error(String(e));
console.error("[BrowserSqlProvider] SQLite WASM initialization failed:", this.initError);
throw this.initError;
}
+ /* v8 ignore stop */
}
/**
diff --git a/apps/standalone/src/lightweight/translation_provider.spec.ts b/apps/standalone/src/lightweight/translation_provider.spec.ts
new file mode 100644
index 0000000000..7be8fb068d
--- /dev/null
+++ b/apps/standalone/src/lightweight/translation_provider.spec.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it, vi } from "vitest";
+import type i18next from "i18next";
+
+import translationProvider from "./translation_provider.js";
+
+describe("translationProvider", () => {
+ it("wires up the HTTP backend and initializes i18next for the locale", async () => {
+ const init = vi.fn().mockResolvedValue(undefined);
+ const use = vi.fn().mockReturnValue({ init });
+ const fakeInstance = { use } as unknown as typeof i18next;
+
+ await translationProvider(fakeInstance, "en");
+
+ expect(use).toHaveBeenCalledTimes(1);
+ expect(init).toHaveBeenCalledTimes(1);
+
+ const config = init.mock.calls[0][0];
+ expect(config.lng).toBe("en");
+ expect(config.fallbackLng).toBe("en");
+ expect(config.ns).toBe("server");
+ expect(config.returnEmptyString).toBe(false);
+ expect(config.backend.loadPath).toContain("/{{lng}}/{{ns}}.json");
+ });
+});
diff --git a/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts
new file mode 100644
index 0000000000..a6d7527dcd
--- /dev/null
+++ b/apps/standalone/src/lightweight/zip_export_provider_factory.spec.ts
@@ -0,0 +1,35 @@
+import type { ZipExportProviderData } from "@triliumnext/core";
+import { describe, expect, it } from "vitest";
+
+import BrowserZipProvider from "./zip_provider.js";
+import { standaloneZipExportProviderFactory } from "./zip_export_provider_factory.js";
+
+function makeData(): ZipExportProviderData {
+ return {
+ branch: { branchId: "test" },
+ getNoteTargetUrl: () => null,
+ archive: new BrowserZipProvider().createZipArchive(),
+ zipExportOptions: undefined,
+ rewriteFn: (content: string) => content
+ } as unknown as ZipExportProviderData;
+}
+
+describe("standaloneZipExportProviderFactory", () => {
+ it("creates an HTML export provider", async () => {
+ const data = makeData();
+ const provider = await standaloneZipExportProviderFactory("html", data);
+ expect(provider.constructor.name).toBe("HtmlExportProvider");
+ expect(provider.branch).toBe(data.branch);
+ });
+
+ it("creates a Markdown export provider", async () => {
+ const provider = await standaloneZipExportProviderFactory("markdown", makeData());
+ expect(provider.constructor.name).toBe("MarkdownExportProvider");
+ });
+
+ it("throws for an unsupported format", async () => {
+ await expect(
+ standaloneZipExportProviderFactory("pdf" as never, makeData())
+ ).rejects.toThrow("Unsupported export format: 'pdf'");
+ });
+});
diff --git a/apps/standalone/src/lightweight/zip_provider.spec.ts b/apps/standalone/src/lightweight/zip_provider.spec.ts
new file mode 100644
index 0000000000..24f0ec471d
--- /dev/null
+++ b/apps/standalone/src/lightweight/zip_provider.spec.ts
@@ -0,0 +1,177 @@
+import type { ZipEntry } from "@triliumnext/core/src/services/zip_provider.js";
+import { strToU8, unzipSync, zipSync } from "fflate";
+import { describe, expect, it } from "vitest";
+
+import BrowserZipProvider from "./zip_provider.js";
+
+const provider = new BrowserZipProvider();
+
+function makeZip(files: Record<string, string>): Uint8Array {
+ const entries: Record<string, Uint8Array> = {};
+ for (const [name, content] of Object.entries(files)) {
+ entries[name] = strToU8(content);
+ }
+ return zipSync(entries);
+}
+
+async function readAll(buffer: Uint8Array, encoding?: string): Promise<Record<string, string>> {
+ const out: Record<string, string> = {};
+ await provider.readZipFile(buffer, async (entry: ZipEntry, readContent) => {
+ out[entry.fileName] = new TextDecoder().decode(await readContent());
+ }, encoding);
+ return out;
+}
+
+async function readNames(buffer: Uint8Array, encoding?: string): Promise<string[]> {
+ const names: string[] = [];
+ await provider.readZipFile(buffer, async (entry: ZipEntry) => { names.push(entry.fileName); }, encoding);
+ return names;
+}
+
+describe("BrowserZipArchive", () => {
+ it("appends string and binary entries and sends them to a send()-style destination", async () => {
+ const archive = provider.createZipArchive();
+ archive.append("hello", { name: "a.txt" });
+ archive.append(new Uint8Array([1, 2, 3]), { name: "b.bin" });
+
+ let sent: Uint8Array | undefined;
+ archive.pipe({ send: (body: unknown) => { sent = body as Uint8Array; } });
+ await archive.finalize();
+
+ expect(sent).toBeInstanceOf(Uint8Array);
+ const unzipped = unzipSync(sent ?? new Uint8Array());
+ expect(new TextDecoder().decode(unzipped["a.txt"])).toBe("hello");
+ expect(Array.from(unzipped["b.bin"])).toEqual([1, 2, 3]);
+ });
+
+ it("uses write()+end() when the destination is a stream", async () => {
+ const archive = provider.createZipArchive();
+ archive.append("x", { name: "f.txt" });
+
+ const chunks: Uint8Array[] = [];
+ let ended = false;
+ archive.pipe({
+ write: (chunk: Uint8Array) => { chunks.push(chunk); },
+ end: () => { ended = true; }
+ });
+ await archive.finalize();
+
+ expect(ended).toBe(true);
+ expect(chunks).toHaveLength(1);
+ });
+
+ it("uses end(content) when only end() is available", async () => {
+ const archive = provider.createZipArchive();
+ archive.append("x", { name: "f.txt" });
+
+ let body: Uint8Array | undefined;
+ archive.pipe({ end: (chunk?: Uint8Array) => { body = chunk; } });
+ await archive.finalize();
+
+ expect(body).toBeInstanceOf(Uint8Array);
+ });
+
+ it("throws when finalized without a destination", async () => {
+ const archive = provider.createZipArchive();
+ await expect(archive.finalize()).rejects.toThrow("ZIP output destination not set.");
+ });
+
+ it("throws for an unsupported destination", async () => {
+ const archive = provider.createZipArchive();
+ archive.pipe({});
+ await expect(archive.finalize()).rejects.toThrow("Unsupported ZIP output destination.");
+ });
+});
+
+describe("BrowserZipProvider.createFileStream", () => {
+ it("is unsupported in the browser", () => {
+ expect(() => provider.createFileStream("/tmp/x")).toThrow("File stream creation is not supported");
+ });
+});
+
+describe("BrowserZipProvider.readZipFile", () => {
+ it("reads entries and decodes their names", async () => {
+ const zip = makeZip({ "one.txt": "first", "dir/two.txt": "second" });
+ const result = await readAll(zip);
+ expect(result).toEqual({ "one.txt": "first", "dir/two.txt": "second" });
+ });
+
+ it("rejects on a corrupt archive", async () => {
+ const garbage = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+ await expect(provider.readZipFile(garbage, async () => {})).rejects.toBeDefined();
+ });
+
+ it("propagates errors thrown while processing an entry", async () => {
+ const zip = makeZip({ "one.txt": "first" });
+ await expect(
+ provider.readZipFile(zip, async () => { throw new Error("processing failed"); })
+ ).rejects.toThrow("processing failed");
+ });
+});
+
+describe("BrowserZipProvider.detectFilenameEncoding", () => {
+ it("returns utf-8 when all filenames are valid UTF-8", async () => {
+ const zip = makeZip({ "plain.txt": "x" });
+ expect(await provider.detectFilenameEncoding(zip)).toBe("utf-8");
+ });
+
+ it("detects GBK when a filename's raw bytes are a valid GBK pair", async () => {
+ // "°¡" round-trips through fflate as char codes 0xB0/0xA1, whose raw bytes
+ // [0xB0, 0xA1] are invalid UTF-8 but a valid GBK character.
+ const zip = makeZip({ "°¡.txt": "x" });
+ expect(await provider.detectFilenameEncoding(zip)).toBe("gbk");
+ });
+
+ it("skips a failing candidate and detects a later one", async () => {
+ // "°.txt" → raw bytes [0xB0, 0x2E, ...]: 0x2E is an invalid GBK trail
+ // (so GBK is skipped), but 0xB0 is a valid single-byte Shift_JIS katakana.
+ const zip = makeZip({ "°.txt": "x" });
+ expect(await provider.detectFilenameEncoding(zip)).toBe("shift_jis");
+ });
+
+ it("falls back to utf-8 when no candidate encoding matches", async () => {
+ // Raw byte 0xFE is invalid UTF-8 and an incomplete/invalid lead byte in
+ // every CJK candidate (GBK/Shift_JIS/EUC-KR/Big5), so detection gives up.
+ const zip = makeZip({ [String.fromCharCode(0xfe)]: "x" });
+ expect(await provider.detectFilenameEncoding(zip)).toBe("utf-8");
+ });
+
+ it("rejects when the archive cannot be read during detection", async () => {
+ await expect(provider.detectFilenameEncoding(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))).rejects.toBeDefined();
+ });
+
+ it("skips a candidate encoding that TextDecoder cannot construct", async () => {
+ const RealTextDecoder = globalThis.TextDecoder;
+ globalThis.TextDecoder = function (label?: string, opts?: TextDecoderOptions) {
+ if (label === "gbk") {
+ throw new RangeError("unsupported encoding");
+ }
+ return new RealTextDecoder(label, opts);
+ } as unknown as typeof TextDecoder;
+ try {
+ const zip = makeZip({ [String.fromCharCode(0xfe)]: "x" });
+ expect(await provider.detectFilenameEncoding(zip)).toBe("utf-8");
+ } finally {
+ globalThis.TextDecoder = RealTextDecoder;
+ }
+ });
+});
+
+describe("BrowserZipProvider filename re-decoding", () => {
+ it("retries with utf-8 when the requested encoding cannot be constructed", async () => {
+ // An unknown encoding makes the primary TextDecoder throw; the ASCII name
+ // is then recovered via the utf-8 fallback.
+ const names = await readNames(makeZip({ "plain.txt": "x" }), "x-unknown-encoding");
+ expect(names).toEqual(["plain.txt"]);
+ });
+
+ it("returns the raw name when both the requested encoding and utf-8 fail", async () => {
+ const names = await readNames(makeZip({ "þ.txt": "x" }), "x-unknown-encoding");
+ expect(names).toEqual(["þ.txt"]);
+ });
+
+ it("returns the raw name when no encoding is given and utf-8 fails", async () => {
+ const names = await readNames(makeZip({ "þ.txt": "x" }));
+ expect(names).toEqual(["þ.txt"]);
+ });
+});
diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.ts
new file mode 100644
index 0000000000..7f57a24f23
--- /dev/null
+++ b/apps/standalone/src/local-bridge.spec.ts
@@ -0,0 +1,283 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// A controllable stand-in for the bundled local-server-worker. vi.hoisted lets the
+// (hoisted) vi.mock factory share the instance registry with the test body.
+const { workerInstances } = vi.hoisted(() => ({ workerInstances: [] as MockWorker[] }));
+
+class MockWorker {
+ postMessage = vi.fn();
+ terminate = vi.fn();
+ onmessage: ((e: { data: unknown }) => void) | null = null;
+ onerror: ((e: { message: string }) => void) | null = null;
+ constructor() { workerInstances.push(this); }
+}
+
+vi.mock("./local-server-worker?worker", () => ({ default: MockWorker }));
+
+type LocalBridge = typeof import("./local-bridge.js");
+
+interface NavServiceWorker {
+ serviceWorker?: { addEventListener: ReturnType<typeof vi.fn> } | undefined;
+}
+
+let swHandler: ((event: unknown) => unknown) | undefined;
+
+async function freshBridge(withServiceWorker = true): Promise<LocalBridge> {
+ vi.resetModules();
+ workerInstances.length = 0;
+ swHandler = undefined;
+ if (withServiceWorker) {
+ Object.defineProperty(navigator, "serviceWorker", {
+ value: { addEventListener: vi.fn((_type: string, handler: (e: unknown) => void) => { swHandler = handler; }) },
+ configurable: true
+ });
+ } else {
+ Object.defineProperty(navigator, "serviceWorker", { value: undefined, configurable: true });
+ }
+ return import("./local-bridge.js");
+}
+
+function lastWorker(): MockWorker {
+ const worker = workerInstances.at(-1);
+ if (!worker) {
+ throw new Error("no worker created");
+ }
+ return worker;
+}
+
+afterEach(() => {
+ delete (navigator as unknown as NavServiceWorker).serviceWorker;
+ vi.restoreAllMocks();
+});
+
+describe("startLocalServerWorker", () => {
+ it("creates the worker once and sends an INIT message", async () => {
+ const bridge = await freshBridge();
+ const worker = bridge.startLocalServerWorker();
+ expect(workerInstances).toHaveLength(1);
+ expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "INIT", useNativeHttp: false }));
+
+ // Second call returns the same instance without creating another worker.
+ expect(bridge.startLocalServerWorker()).toBe(worker);
+ expect(workerInstances).toHaveLength(1);
+ });
+
+ it("flags native HTTP when a handler was registered first", async () => {
+ const bridge = await freshBridge();
+ bridge.registerNativeHttpHandler(vi.fn());
+ bridge.startLocalServerWorker();
+ expect(lastWorker().postMessage).toHaveBeenCalledWith(expect.objectContaining({ useNativeHttp: true }));
+ });
+});
+
+describe("worker message handling", () => {
+ it("shows a dialog on FATAL_ERROR", async () => {
+ const alertSpy = vi.fn();
+ vi.stubGlobal("alert", alertSpy);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ lastWorker().onmessage?.({ data: { type: "FATAL_ERROR", message: "boom" } });
+ expect(alertSpy).toHaveBeenCalledWith("boom");
+ vi.unstubAllGlobals();
+ });
+
+ it("dispatches a window event for WS_MESSAGE", async () => {
+ const dispatchSpy = vi.spyOn(window, "dispatchEvent");
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ lastWorker().onmessage?.({ data: { type: "WS_MESSAGE", message: { kind: "x" } } });
+ const event = dispatchSpy.mock.calls.at(-1)?.[0] as CustomEvent;
+ expect(event.type).toBe("trilium:ws-message");
+ expect(event.detail).toEqual({ kind: "x" });
+ });
+
+ it("relays HTTP_REQUEST to the native handler and posts the response", async () => {
+ const bridge = await freshBridge();
+ const handler = vi.fn().mockResolvedValue({ status: 200, headers: {}, body: "ok" });
+ bridge.registerNativeHttpHandler(handler);
+ bridge.startLocalServerWorker();
+ const worker = lastWorker();
+ worker.postMessage.mockClear();
+
+ worker.onmessage?.({ data: { type: "HTTP_REQUEST", id: "1", request: { method: "GET", url: "u", headers: {} } } });
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "HTTP_RESPONSE", id: "1", status: 200 })));
+ });
+
+ it("posts an error when the native handler rejects", async () => {
+ const bridge = await freshBridge();
+ bridge.registerNativeHttpHandler(vi.fn().mockRejectedValue(new Error("net down")));
+ bridge.startLocalServerWorker();
+ const worker = lastWorker();
+ worker.postMessage.mockClear();
+
+ worker.onmessage?.({ data: { type: "HTTP_REQUEST", id: "2", request: {} } });
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "HTTP_RESPONSE", id: "2", error: "net down" })));
+ });
+
+ it("stringifies a non-Error rejection from the native handler", async () => {
+ const bridge = await freshBridge();
+ bridge.registerNativeHttpHandler(vi.fn().mockRejectedValue("plain rejection"));
+ bridge.startLocalServerWorker();
+ const worker = lastWorker();
+ worker.postMessage.mockClear();
+
+ worker.onmessage?.({ data: { type: "HTTP_REQUEST", id: "3", request: {} } });
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "HTTP_RESPONSE", id: "3", error: "plain rejection" })));
+ });
+
+ it("rejects pending requests on WORKER_ERROR and on worker onerror", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ const worker = lastWorker();
+
+ // WORKER_ERROR path
+ worker.onmessage?.({ data: { type: "WORKER_ERROR", error: { message: "crash" } } });
+ // onerror path
+ expect(() => worker.onerror?.({ message: "fatal" })).not.toThrow();
+ });
+
+ it("ignores messages without a recognized type", async () => {
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ expect(() => lastWorker().onmessage?.({ data: { type: "NOPE" } })).not.toThrow();
+ expect(() => lastWorker().onmessage?.({ data: null })).not.toThrow();
+ });
+});
+
+describe("attachServiceWorkerBridge", () => {
+ it("warns and skips when service workers are unavailable", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const bridge = await freshBridge(false);
+ bridge.attachServiceWorkerBridge();
+ expect(warn).toHaveBeenCalled();
+ });
+
+ it("forwards a LOCAL_FETCH request to the worker and replies through the port", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ expect(swHandler).toBeDefined();
+
+ const port = { postMessage: vi.fn() };
+ const body = new TextEncoder().encode("req").buffer;
+ const pending = swHandler?.({
+ data: { type: "LOCAL_FETCH", id: "42", request: { method: "POST", url: "/x", headers: {}, body } },
+ ports: [port]
+ });
+
+ // The bridge posts a LOCAL_REQUEST to the worker; simulate its reply.
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_REQUEST", id: "42" }), expect.anything()));
+ const responseBody = new TextEncoder().encode("resp").buffer;
+ worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: "42", response: { status: 200, headers: {}, body: responseBody } } });
+
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH_RESPONSE", id: "42" }), expect.anything());
+ });
+
+ it("replies with a 500 when forwarding throws", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const port = { postMessage: vi.fn() };
+
+ // No body and a worker whose postMessage throws → the try block fails.
+ bridge.startLocalServerWorker();
+ lastWorker().postMessage.mockImplementation(() => { throw new Error("post failed"); });
+
+ await swHandler?.({ data: { type: "LOCAL_FETCH", id: "7", request: { method: "GET", url: "/y", headers: {} } }, ports: [port] });
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH_RESPONSE", id: "7", response: expect.objectContaining({ status: 500 }) }));
+ });
+
+ it("ignores non-LOCAL_FETCH messages and messages without a port", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ expect(() => swHandler?.({ data: { type: "OTHER" } })).not.toThrow();
+ expect(() => swHandler?.({ data: { type: "LOCAL_FETCH", id: "1", request: {} }, ports: [] })).not.toThrow();
+ });
+
+ it("replies without a transferable body when the worker omits one", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const port = { postMessage: vi.fn() };
+ const pending = swHandler?.({ data: { type: "LOCAL_FETCH", id: "33", request: { method: "GET", url: "/z", headers: {} } }, ports: [port] });
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "33" }), expect.anything()));
+ worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: "33", response: { status: 204, headers: {} } } });
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "33" }), []);
+ });
+
+ it("stringifies a non-Error thrown while forwarding", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ bridge.startLocalServerWorker();
+ lastWorker().postMessage.mockImplementation(() => { throw "string failure"; });
+ const port = { postMessage: vi.fn() };
+ await swHandler?.({ data: { type: "LOCAL_FETCH", id: "9", request: { method: "GET", url: "/y", headers: {} } }, ports: [port] });
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ response: expect.objectContaining({ status: 500 }) }));
+ });
+});
+
+describe("pending request rejection", () => {
+ function startFetch(id: string): { port: { postMessage: ReturnType<typeof vi.fn> }; pending: unknown } {
+ const port = { postMessage: vi.fn() };
+ const pending = swHandler?.({ data: { type: "LOCAL_FETCH", id, request: { method: "GET", url: "/p", headers: {} } }, ports: [port] });
+ return { port, pending };
+ }
+
+ it("rejects in-flight requests when the worker reports WORKER_ERROR", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const { port, pending } = startFetch("71");
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "71" }), expect.anything()));
+ worker.onmessage?.({ data: { type: "WORKER_ERROR", error: { message: "crash" } } });
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ response: expect.objectContaining({ status: 500 }) }));
+ });
+
+ it("rejects in-flight requests when the worker fires onerror", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const { port, pending } = startFetch("51");
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "51" }), expect.anything()));
+ worker.onerror?.({ message: "fatal" });
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ response: expect.objectContaining({ status: 500 }) }));
+ });
+
+ it("rejects a request when its LOCAL_RESPONSE carries an error", async () => {
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const { port, pending } = startFetch("114");
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "114" }), expect.anything()));
+ worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: "114", error: "boom" } });
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ response: expect.objectContaining({ status: 500 }) }));
+ });
+
+ it("falls back to a default message when WORKER_ERROR omits one", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.attachServiceWorkerBridge();
+ const { port, pending } = startFetch("u1");
+ const worker = lastWorker();
+ await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ id: "u1" }), expect.anything()));
+ worker.onmessage?.({ data: { type: "WORKER_ERROR" } });
+ await pending;
+ expect(port.postMessage).toHaveBeenCalledWith(expect.objectContaining({ response: expect.objectContaining({ status: 500 }) }));
+ });
+
+ it("ignores a LOCAL_RESPONSE for an unknown id and HTTP_REQUEST without a native handler", async () => {
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+ const worker = lastWorker();
+ expect(() => worker.onmessage?.({ data: { type: "LOCAL_RESPONSE", id: "ghost", response: {} } })).not.toThrow();
+ expect(() => worker.onmessage?.({ data: { type: "HTTP_REQUEST", id: "1", request: {} } })).not.toThrow();
+ });
+});
diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.ts
new file mode 100644
index 0000000000..c67ed79969
--- /dev/null
+++ b/apps/standalone/src/main.spec.ts
@@ -0,0 +1,123 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ startLocalServerWorker: vi.fn(),
+ attachServiceWorkerBridge: vi.fn(),
+ registerNativeHttpHandler: vi.fn(),
+ capacitorHttpHandler: vi.fn()
+}));
+
+vi.mock("./local-bridge.js", () => ({
+ startLocalServerWorker: mocks.startLocalServerWorker,
+ attachServiceWorkerBridge: mocks.attachServiceWorkerBridge,
+ registerNativeHttpHandler: mocks.registerNativeHttpHandler
+}));
+vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));
+// Avoid pulling the entire client bundle when loadScripts() runs.
+vi.mock("../../client/src/index.js", () => ({}));
+
+interface ServiceWorkerLike {
+ controller: unknown;
+ register: ReturnType<typeof vi.fn>;
+ ready: Promise<unknown>;
+}
+
+interface WindowWithCapacitor { Capacitor?: unknown }
+
+function setServiceWorker(sw: ServiceWorkerLike | undefined) {
+ Object.defineProperty(navigator, "serviceWorker", { value: sw, configurable: true });
+}
+
+let reloadSpy: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ Object.values(mocks).forEach((m) => m.mockReset());
+ document.body.innerHTML = "";
+ delete (window as unknown as WindowWithCapacitor).Capacitor;
+ reloadSpy = vi.fn();
+ Object.defineProperty(window, "location", {
+ value: { ...window.location, protocol: "https:", hostname: "localhost", reload: reloadSpy, search: "" },
+ configurable: true
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+async function runBootstrap() {
+ vi.resetModules();
+ await import("./main.js");
+}
+
+describe("bootstrap", () => {
+ it("starts the worker, bridges the SW, and loads scripts when already controlling", async () => {
+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });
+ await runBootstrap();
+ await vi.waitFor(() => expect(mocks.startLocalServerWorker).toHaveBeenCalled());
+ expect(mocks.attachServiceWorkerBridge).toHaveBeenCalled();
+ expect(document.body.innerHTML).toBe("");
+ });
+
+ it("registers the native HTTP handler under Capacitor", async () => {
+ (window as unknown as WindowWithCapacitor).Capacitor = {};
+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });
+ await runBootstrap();
+ await vi.waitFor(() => expect(mocks.registerNativeHttpHandler).toHaveBeenCalledWith(mocks.capacitorHttpHandler));
+ });
+
+ it("registers and waits for the SW, then loads scripts once it controls", async () => {
+ const sw: ServiceWorkerLike = { controller: null, register: vi.fn(), ready: Promise.resolve() };
+ // The SW takes control once registration completes (after the first check).
+ sw.register.mockImplementation(async () => { sw.controller = {}; });
+ setServiceWorker(sw);
+ await runBootstrap();
+ await vi.waitFor(() => expect(sw.register).toHaveBeenCalledWith("./sw.js", { scope: "/" }));
+ expect(reloadSpy).not.toHaveBeenCalled();
+ expect(document.body.innerHTML).toBe("");
+ });
+
+ it("reloads the page when the SW installs but does not take control", async () => {
+ setServiceWorker({ controller: null, register: vi.fn().mockResolvedValue(undefined), ready: Promise.resolve() });
+ await runBootstrap();
+ await vi.waitFor(() => expect(reloadSpy).toHaveBeenCalled());
+ // The reload path throws "Reloading..." which bootstrap swallows (no error UI).
+ expect(document.body.innerHTML).toBe("");
+ });
+
+ it("shows an error screen when service workers are unavailable (insecure context)", async () => {
+ setServiceWorker(undefined);
+ Object.defineProperty(window, "location", {
+ value: { protocol: "http:", hostname: "example.com", reload: reloadSpy, search: "" },
+ configurable: true
+ });
+ Object.defineProperty(window, "isSecureContext", { value: false, configurable: true });
+ await runBootstrap();
+ await vi.waitFor(() => expect(document.body.innerHTML).toContain("Failed to Initialize"));
+ expect(document.body.innerHTML).toContain("not a secure context");
+ });
+
+ it("omits the secure-context hints when the context is already secure", async () => {
+ setServiceWorker(undefined);
+ Object.defineProperty(window, "isSecureContext", { value: true, configurable: true });
+ await runBootstrap();
+ await vi.waitFor(() => expect(document.body.innerHTML).toContain("Failed to Initialize"));
+ expect(document.body.innerHTML).not.toContain("Possible cause");
+ });
+
+ it("shows an error screen for a generic failure with the error message", async () => {
+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });
+ mocks.attachServiceWorkerBridge.mockImplementation(() => { throw new Error("bridge exploded"); });
+ await runBootstrap();
+ await vi.waitFor(() => expect(document.body.innerHTML).toContain("bridge exploded"));
+ });
+
+ it("stringifies a non-Error failure in the error screen", async () => {
+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });
+ mocks.attachServiceWorkerBridge.mockImplementation(() => { throw "plain failure"; });
+ await runBootstrap();
+ await vi.waitFor(() => expect(document.body.innerHTML).toContain("plain failure"));
+ });
+});
diff --git a/apps/standalone/src/services/capacitor_http_handler.spec.ts b/apps/standalone/src/services/capacitor_http_handler.spec.ts
new file mode 100644
index 0000000000..d348997c3e
--- /dev/null
+++ b/apps/standalone/src/services/capacitor_http_handler.spec.ts
@@ -0,0 +1,74 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { capacitorHttpHandler } from "./capacitor_http_handler.js";
+
+interface CapacitorWindow {
+ Capacitor?: unknown;
+}
+
+function installCapacitor(request: ReturnType<typeof vi.fn>) {
+ (window as unknown as CapacitorWindow).Capacitor = {
+ Plugins: { CapacitorHttp: { request } }
+ };
+}
+
+describe("capacitorHttpHandler", () => {
+ afterEach(() => {
+ delete (window as unknown as CapacitorWindow).Capacitor;
+ vi.restoreAllMocks();
+ });
+
+ it("throws when the CapacitorHttp plugin is unavailable", async () => {
+ await expect(
+ capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} })
+ ).rejects.toThrow("CapacitorHttp plugin is not available");
+ });
+
+ it("forwards the request and lowercases response header keys (object body)", async () => {
+ const request = vi.fn().mockResolvedValue({
+ status: 200,
+ headers: { "Content-Type": "application/json", "X-Custom": "v" },
+ data: { ok: true }
+ });
+ installCapacitor(request);
+
+ const result = await capacitorHttpHandler({
+ method: "POST",
+ url: "https://api/test",
+ headers: { Authorization: "token" },
+ body: "{}"
+ });
+
+ expect(request).toHaveBeenCalledWith({
+ method: "POST",
+ url: "https://api/test",
+ headers: { Authorization: "token" },
+ data: "{}",
+ responseType: undefined
+ });
+ expect(result.status).toBe(200);
+ expect(result.headers).toEqual({ "content-type": "application/json", "x-custom": "v" });
+ expect(result.body).toBe(JSON.stringify({ ok: true }));
+ });
+
+ it("passes string response data through unchanged", async () => {
+ const request = vi.fn().mockResolvedValue({ status: 201, headers: {}, data: "plain text" });
+ installCapacitor(request);
+
+ const result = await capacitorHttpHandler({ method: "GET", url: "https://x", headers: {} });
+ expect(result.body).toBe("plain text");
+ });
+
+ it("passes arraybuffer responses through as the raw base64 string", async () => {
+ const request = vi.fn().mockResolvedValue({ status: 200, headers: {}, data: "QUJD" });
+ installCapacitor(request);
+
+ const result = await capacitorHttpHandler({
+ method: "GET",
+ url: "https://x/image",
+ headers: {},
+ responseType: "arraybuffer"
+ });
+ expect(result.body).toBe("QUJD");
+ });
+});
diff --git a/apps/standalone/src/services/image_provider.spec.ts b/apps/standalone/src/services/image_provider.spec.ts
new file mode 100644
index 0000000000..a772a6dfc8
--- /dev/null
+++ b/apps/standalone/src/services/image_provider.spec.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+
+import { standaloneImageProvider } from "./image_provider.js";
+
+/** Build a 12+ byte buffer starting with the given magic bytes. */
+function withMagic(magic: number[], totalLength = 16): Uint8Array {
+ const buf = new Uint8Array(totalLength);
+ buf.set(magic);
+ return buf;
+}
+
+function fromString(str: string): Uint8Array {
+ const buf = new Uint8Array(Math.max(str.length, 16));
+ for (let i = 0; i < str.length; i++) {
+ buf[i] = str.charCodeAt(i);
+ }
+ return buf;
+}
+
+describe("standaloneImageProvider.getImageType", () => {
+ it("returns null for buffers shorter than 12 bytes", () => {
+ expect(standaloneImageProvider.getImageType(new Uint8Array([0xff, 0xd8, 0xff]))).toBeNull();
+ });
+
+ it("detects JPEG", () => {
+ expect(standaloneImageProvider.getImageType(withMagic([0xff, 0xd8, 0xff]))).toEqual({ ext: "jpg", mime: "image/jpeg" });
+ });
+
+ it("detects PNG", () => {
+ expect(standaloneImageProvider.getImageType(withMagic([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toEqual({ ext: "png", mime: "image/png" });
+ });
+
+ it("detects GIF", () => {
+ expect(standaloneImageProvider.getImageType(withMagic([0x47, 0x49, 0x46]))).toEqual({ ext: "gif", mime: "image/gif" });
+ });
+
+ it("detects WebP (RIFF....WEBP)", () => {
+ const buf = withMagic([0x52, 0x49, 0x46, 0x46]);
+ buf[8] = 0x57; buf[9] = 0x45; buf[10] = 0x42; buf[11] = 0x50;
+ expect(standaloneImageProvider.getImageType(buf)).toEqual({ ext: "webp", mime: "image/webp" });
+ });
+
+ it("detects BMP", () => {
+ expect(standaloneImageProvider.getImageType(withMagic([0x42, 0x4d]))).toEqual({ ext: "bmp", mime: "image/bmp" });
+ });
+
+ it("detects SVG starting with <svg", () => {
+ expect(standaloneImageProvider.getImageType(fromString("<svg width='1'></svg>"))).toEqual({ ext: "svg", mime: "image/svg+xml" });
+ });
+
+ it("detects SVG declared via XML prolog", () => {
+ expect(standaloneImageProvider.getImageType(fromString("<?xml version='1.0'?><svg></svg>"))).toEqual({ ext: "svg", mime: "image/svg+xml" });
+ });
+
+ it("does not treat a plain XML prolog without <svg as SVG", () => {
+ expect(standaloneImageProvider.getImageType(fromString("<?xml version='1.0'?><html></html>"))).toBeNull();
+ });
+
+ it("returns null for unrecognized content", () => {
+ expect(standaloneImageProvider.getImageType(new Uint8Array(16))).toBeNull();
+ });
+});
+
+describe("standaloneImageProvider.processImage", () => {
+ it("returns the original buffer with the detected format", async () => {
+ const buffer = withMagic([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ const result = await standaloneImageProvider.processImage(buffer, "x.png", true);
+ expect(result.buffer).toBe(buffer);
+ expect(result.format).toEqual({ ext: "png", mime: "image/png" });
+ });
+
+ it("falls back to octet-stream for unrecognized content", async () => {
+ const buffer = new Uint8Array(16);
+ const result = await standaloneImageProvider.processImage(buffer, "x.bin", false);
+ expect(result.buffer).toBe(buffer);
+ expect(result.format).toEqual({ ext: "dat", mime: "application/octet-stream" });
+ });
+});
diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.ts
new file mode 100644
index 0000000000..197799010c
--- /dev/null
+++ b/apps/standalone/src/sw.spec.ts
@@ -0,0 +1,236 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type EventHandler = (event: unknown) => void;
+
+interface SwGlobals {
+ skipWaiting?: () => void;
+ clients?: { claim: ReturnType<typeof vi.fn>; matchAll: ReturnType<typeof vi.fn> };
+}
+
+const origin = self.location.origin;
+
+let channels: MockMessageChannel[] = [];
+
+class MockMessageChannel {
+ port1: { onmessage: EventHandler | null; onmessageerror: (() => void) | null } = { onmessage: null, onmessageerror: null };
+ port2 = { tag: "port2" };
+ constructor() { channels.push(this); }
+}
+
+async function loadSw(): Promise<Record<string, EventHandler>> {
+ vi.resetModules();
+ const handlers: Record<string, EventHandler> = {};
+ vi.spyOn(self, "addEventListener").mockImplementation((type: string, handler: EventListenerOrEventListenerObject) => {
+ handlers[type] = handler as EventHandler;
+ });
+ // sw.ts is a side-effect-only service worker script (no exports); importing it
+ // runs its addEventListener registrations, which the spy above captures.
+ // @ts-expect-error - sw.ts has no module exports
+ await import("./sw.js");
+ return handlers;
+}
+
+async function awaitResponse(event: { _response?: Promise<Response> }): Promise<Response> {
+ const res = await event._response;
+ if (!res) {
+ throw new Error("respondWith was not called");
+ }
+ return res;
+}
+
+function fetchEvent(url: string, init: { method?: string; mode?: string; headers?: [string, string][] } = {}): { request: unknown; clientId: string; respondWith(p: Promise<Response>): void; _response?: Promise<Response> } {
+ const request = {
+ url,
+ method: init.method ?? "GET",
+ mode: init.mode ?? "cors",
+ headers: { entries: () => (init.headers ?? [])[Symbol.iterator]() },
+ arrayBuffer: async () => new TextEncoder().encode("body").buffer
+ };
+ const event = { request, clientId: "c1" } as ReturnType<typeof fetchEvent>;
+ event.respondWith = (p: Promise<Response>) => { event._response = p; };
+ return event;
+}
+
+beforeEach(() => {
+ channels = [];
+ (self as unknown as SwGlobals).skipWaiting = vi.fn();
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(async () => {}), matchAll: vi.fn(async () => []) };
+ vi.stubGlobal("caches", {
+ open: vi.fn(async () => ({ addAll: vi.fn(), match: vi.fn(), put: vi.fn() })),
+ keys: vi.fn(async () => ["static-old", "static-localserver-v1.4"]),
+ delete: vi.fn(async () => true)
+ });
+ vi.stubGlobal("MessageChannel", MockMessageChannel);
+ vi.stubGlobal("crypto", { ...globalThis.crypto, randomUUID: () => "uuid-1" });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("network")));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete (self as unknown as SwGlobals).skipWaiting;
+ delete (self as unknown as SwGlobals).clients;
+});
+
+describe("service worker lifecycle", () => {
+ it("skips waiting on install", async () => {
+ const handlers = await loadSw();
+ let waited: Promise<unknown> | undefined;
+ handlers.install({ waitUntil: (p: Promise<unknown>) => { waited = p; } } as unknown);
+ await waited;
+ expect((self as unknown as SwGlobals).skipWaiting).toHaveBeenCalled();
+ });
+
+ it("clears stale caches and claims clients on activate", async () => {
+ const handlers = await loadSw();
+ let waited: Promise<unknown> | undefined;
+ handlers.activate({ waitUntil: (p: Promise<unknown>) => { waited = p; } } as unknown);
+ await waited;
+ const caches = (globalThis as unknown as { caches: { delete: ReturnType<typeof vi.fn> } }).caches;
+ expect(caches.delete).toHaveBeenCalledWith("static-old");
+ expect(caches.delete).not.toHaveBeenCalledWith("static-localserver-v1.4");
+ expect((self as unknown as SwGlobals).clients?.claim).toHaveBeenCalled();
+ });
+});
+
+describe("fetch routing", () => {
+ it("ignores cross-origin requests", async () => {
+ const handlers = await loadSw();
+ const event = fetchEvent("https://elsewhere.example.com/api/x");
+ handlers.fetch(event);
+ expect(event._response).toBeUndefined();
+ });
+
+ it("routes local-first prefixes to the client bridge", async () => {
+ const handlers = await loadSw();
+ const event = fetchEvent(`${origin}/api/notes`);
+ handlers.fetch(event);
+ expect(event._response).toBeDefined();
+ });
+
+ it("serves navigations and .html network-first (which bypasses cache in dev)", async () => {
+ const handlers = await loadSw();
+ const navEvent = fetchEvent(`${origin}/index.html`, { mode: "navigate" });
+ handlers.fetch(navEvent);
+ await navEvent._response;
+ const htmlEvent = fetchEvent(`${origin}/page.html`);
+ handlers.fetch(htmlEvent);
+ await htmlEvent._response;
+ expect(fetch).toHaveBeenCalled();
+ });
+
+ it("serves other GETs cache-first (which bypasses cache in dev)", async () => {
+ const handlers = await loadSw();
+ const event = fetchEvent(`${origin}/app.js`);
+ handlers.fetch(event);
+ const res = await awaitResponse(event);
+ expect(res).toBeInstanceOf(Response);
+ });
+
+ it("passes non-GET, non-local requests straight to the network", async () => {
+ const handlers = await loadSw();
+ const event = fetchEvent(`${origin}/app.js`, { method: "POST" });
+ handlers.fetch(event);
+ await event._response;
+ expect(fetch).toHaveBeenCalled();
+ });
+});
+
+describe("forwardToClientLocalServer", () => {
+ function mainClient() {
+ return { url: `${origin}/`, postMessage: vi.fn() };
+ }
+
+ async function dispatchLocal(handlers: Record<string, EventHandler>, method = "POST") {
+ const event = fetchEvent(`${origin}/api/notes`, { method, headers: [["x-test", "1"]] });
+ handlers.fetch(event);
+ return event;
+ }
+
+ it("forwards to the main app window and returns its response", async () => {
+ const client = mainClient();
+ (self as unknown as SwGlobals).clients = {
+ claim: vi.fn(),
+ matchAll: vi.fn(async () => [{ url: `${origin}/pdfjs/viewer.html`, postMessage: vi.fn() }, client])
+ };
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers);
+
+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());
+ const channel = channels.at(-1);
+ channel?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 201, headers: { "content-type": "application/json" }, body: new TextEncoder().encode("ok").buffer } } } as unknown);
+
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(201);
+ expect(await res.text()).toBe("ok");
+ });
+
+ it("falls back to any client when no main window is found", async () => {
+ const onlyPdf = { url: `${origin}/pdfjs/viewer.html`, postMessage: vi.fn() };
+ // Both candidates are pdfjs; find() yields none, so it falls back to all[0].
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [onlyPdf]) };
+ // Make the only client pdfjs so the main-window filter rejects it.
+ onlyPdf.url = `${origin}/pdfjs/web/viewer.html`;
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers, "GET");
+ await vi.waitFor(() => expect(onlyPdf.postMessage).toHaveBeenCalled());
+ const channel = channels.at(-1);
+ channel?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(200);
+ });
+
+ it("falls back to the network when there are no clients", async () => {
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => []) };
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers, "GET");
+ await event._response;
+ expect(fetch).toHaveBeenCalled();
+ });
+
+ it("defaults status and omits headers when the response is sparse", async () => {
+ const client = mainClient();
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers, "GET");
+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());
+ // No status, no headers, no body → status falls back to 200, headers stay empty.
+ channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: {} } } as unknown);
+ const res = await awaitResponse(event);
+ expect(res.status).toBe(200);
+ });
+
+ it("falls back to the network on a protocol mismatch", async () => {
+ const client = mainClient();
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers, "GET");
+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());
+ channels.at(-1)?.port1.onmessage?.({ data: { type: "WRONG", id: "uuid-1" } } as unknown);
+ await event._response;
+ expect(fetch).toHaveBeenCalled();
+ });
+
+ it("rejects on a message error", async () => {
+ const client = mainClient();
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
+ const handlers = await loadSw();
+ const event = await dispatchLocal(handlers, "GET");
+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());
+ channels.at(-1)?.port1.onmessageerror?.();
+ await expect(event._response).rejects.toThrow("Local server message error");
+ });
+
+ it("times out when the client never responds", async () => {
+ const client = mainClient();
+ const handlers = await loadSw();
+ vi.useFakeTimers();
+ (self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };
+ const event = await dispatchLocal(handlers, "GET");
+ const rejection = expect(event._response).rejects.toThrow("Local server timeout");
+ // Flushes the pending matchAll microtask, then fires the 30s timeout.
+ await vi.advanceTimersByTimeAsync(30_000);
+ await rejection;
+ vi.useRealTimers();
+ });
+});
diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.ts
index 4e5b5831f7..dde5c4268e 100644
--- a/apps/standalone/src/sw.ts
+++ b/apps/standalone/src/sw.ts
@@ -5,6 +5,7 @@ const STATIC_CACHE = `static-${VERSION}`;
// Check if running in dev mode (passed via URL parameter)
const isDev = true;
+/* v8 ignore next 3 -- @preserve: isDev is hardcoded true, so the dev-mode log always runs and has no testable alternate branch. */
if (isDev) {
console.log('[Service Worker] Running in DEV mode - caching disabled');
}
@@ -28,10 +29,12 @@ const PRECACHE_URLS = [
self.addEventListener("install", (event) => {
event.waitUntil((async () => {
// Skip precaching in dev mode
+ /* v8 ignore start -- @preserve: isDev is hardcoded true, so precaching never runs. */
if (!isDev) {
const cache = await caches.open(STATIC_CACHE);
await cache.addAll(PRECACHE_URLS);
}
+ /* v8 ignore stop */
self.skipWaiting();
})());
});
@@ -50,6 +53,7 @@ function isLocalFirst(url) {
}
async function cacheFirst(request) {
+ /* v8 ignore start -- @preserve: isDev is hardcoded true, so only the dev bypass executes; the cache implementation is dead code. */
// In dev mode, always bypass cache
if (isDev) {
return fetch(request);
@@ -63,9 +67,11 @@ async function cacheFirst(request) {
// Cache only successful GETs
if (request.method === "GET" && fresh.ok) cache.put(request, fresh.clone());
return fresh;
+ /* v8 ignore stop */
}
async function networkFirst(request) {
+ /* v8 ignore start -- @preserve: isDev is hardcoded true, so only the dev bypass executes; the cache implementation is dead code. */
// In dev mode, always bypass cache
if (isDev) {
return fetch(request);
@@ -83,6 +89,7 @@ async function networkFirst(request) {
if (cached) return cached;
throw error;
}
+ /* v8 ignore stop */
}
async function forwardToClientLocalServer(request, _clientId) {
diff --git a/apps/standalone/tsconfig.spec.json b/apps/standalone/tsconfig.spec.json
index 856955c7fc..ebb32db60e 100644
--- a/apps/standalone/tsconfig.spec.json
+++ b/apps/standalone/tsconfig.spec.json
@@ -1,6 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "outDir": "./out-tsc/vitest",
"lib": [
"ES2022",
"dom",
@@ -8,11 +11,19 @@
],
"types": [
"vitest/globals",
- "happy-dom"
+ "happy-dom",
+ "vite/client"
]
},
"include": [
+ "vite.config.mts",
"src/**/*.spec.ts",
- "src/**/*.test.ts"
+ "src/**/*.test.ts",
+ "src/**/*.d.ts"
+ ],
+ "references": [
+ {
+ "path": "./tsconfig.app.json"
+ }
]
-}
\ No newline at end of file
+}
diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mts
index f45fb89ae7..b77bec568a 100644
--- a/apps/standalone/vite.config.mts
+++ b/apps/standalone/vite.config.mts
@@ -341,7 +341,20 @@ export default defineConfig(() => ({
// Vite `root` above is `src`, so coverage include globs resolve relative to src/.
// `../../../` walks src -> standalone -> apps -> repo root to reach the core package.
include: ["**/*.{ts,tsx}", "../../../packages/trilium-core/src/**/*.{ts,tsx}"],
- exclude: ["**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}", "**/*.d.ts"],
+ exclude: [
+ "**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}",
+ "**/*.d.ts",
+ // Build/E2E config, not unit-testable.
+ "**/playwright.config.ts",
+ // Test harness, not product code.
+ "**/test_setup.ts",
+ // Thin re-export entry (forwards the client desktop entry).
+ "**/desktop.ts",
+ // The web-worker entry boots @triliumnext/core (and a second SQLite
+ // WASM init) on load, which conflicts with the unit-test harness's own
+ // core initialization; it is exercised by the Playwright e2e suite instead.
+ "**/local-server-worker.ts"
+ ],
reporter: ["text", "html", "lcov"]
},
server: {