Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(web-clipper): cover the background, content and offscreen scripts
Elian Doran93a10d6d2eb6
diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsnew file mode 100644index 0000000000..61a1385550--- /dev/null+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -0,0 +1,508 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fakeBrowser } from "wxt/testing/fake-browser";++const facade = vi.hoisted(() => ({+ callService: vi.fn<(method: string, path: string, body?: unknown) => Promise<any>>(),+ triggerSearchForTrilium: vi.fn(),+ sendTriliumSearchStatusToPopup: vi.fn(),+ triggerSearchNoteByUrl: vi.fn()+}));++vi.mock("./trilium_server_facade", () => ({+ default: class {++ callService = facade.callService;+ triggerSearchForTrilium = facade.triggerSearchForTrilium;+ sendTriliumSearchStatusToPopup = facade.sendTriliumSearchStatusToPopup;+ triggerSearchNoteByUrl = facade.triggerSearchNoteByUrl;++ }+}));++import background from "./index";++type Tab = { id?: number, title?: string, url?: string };+type ContextMenuClick = {+ menuItemId: string,+ pageUrl?: string,+ srcUrl?: string,+ linkUrl?: string,+ linkText?: string+};++const PNG = "data:image/png;base64,iVBORw0KGgo=";+const CROPPED_PNG = "data:image/png;base64,Q1JPUA==";+const PNG_DATA_URL = /^data:image\/png;base64,/;+const PAGE_URL = "https://example.com/page";+const MENU_URL = "https://example.com/menu";+const ACTIVE_TAB: Tab = { id: 7, title: "Active page", url: PAGE_URL };++let onCommand: (command: string) => Promise<void>;+let onContextMenuClicked: (info: ContextMenuClick) => Promise<void>;+let tabs: Tab[];+let tabMessageHandler: (message: { name: string }) => unknown;+const tabsSendMessage = vi.fn(+ (_tabId: number, message: { name: string }) => Promise.resolve(tabMessageHandler(message)));+const contextMenusCreate = vi.fn();+const contextMenusRemoveAll = vi.fn(async () => {});+const getContexts = vi.fn(async (): Promise<unknown[]> => []);+const createDocument = vi.fn(async () => {});+const runtimeSendMessage = vi.fn(async (_message: unknown): Promise<unknown> => PNG);+const fetchMock = vi.fn(+ async (_url: string) => new Response(new Blob([ "img" ], { type: "image/png" })));++describe("background", () => {+ beforeEach(async () => {+ fakeBrowser.reset();+ tabs = [ ACTIVE_TAB ];+ tabMessageHandler = () => undefined;+ facade.callService.mockResolvedValue({ noteId: "saved" });+ vi.stubGlobal("fetch", fetchMock);+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});++ Object.assign(fakeBrowser.commands.onCommand, {+ addListener: (listener: typeof onCommand) => {+ onCommand = listener;+ }+ });+ Object.assign(fakeBrowser.contextMenus, {+ create: contextMenusCreate,+ removeAll: contextMenusRemoveAll,+ onClicked: {+ addListener: (listener: typeof onContextMenuClicked) => {+ onContextMenuClicked = listener;+ }+ }+ });+ Object.assign(fakeBrowser.tabs, {+ query: async ({ active }: { active?: boolean }) => (active ? tabs.slice(0, 1) : tabs),+ sendMessage: tabsSendMessage,+ getZoom: async () => 1.5,+ captureVisibleTab: async () => PNG+ });+ Object.assign(fakeBrowser.runtime, { getContexts, sendMessage: runtimeSendMessage });+ Object.assign(fakeBrowser, { offscreen: { createDocument } });++ background.main();+ await vi.waitFor(() => expect(contextMenusCreate).toHaveBeenCalledTimes(6));+ });++ afterEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("registers the context menu items once", () => {+ expect(contextMenusRemoveAll).toHaveBeenCalledBefore(contextMenusCreate);+ expect(contextMenusCreate.mock.calls.map(([ item ]) => item.id)).toEqual([+ "trilium-save-selection",+ "trilium-save-cropped-screenshot",+ "trilium-save-whole-screenshot",+ "trilium-save-page",+ "trilium-save-link",+ "trilium-save-image"+ ]);+ });++ describe("saving the selection", () => {+ it("inlines the images, saves a clipping and shows a toast", async () => {+ fetchMock.mockRejectedValueOnce(new Error("blocked"));+ tabMessageHandler = () => ({+ title: "Page",+ content: "<p>Selected</p>",+ images: [+ { imageId: "i1", src: "https://example.com/missing.png" },+ { imageId: "i2", src: "https://example.com/a.png" },+ { imageId: "i3", src: "data:image/jpeg;base64,/9j/4AAQ" },+ { imageId: "i4", src: "data:image/;base64,AAAA" }+ ]+ });++ await onContextMenuClicked({ menuItemId: "trilium-save-selection" });++ expect(tabsSendMessage).toHaveBeenCalledWith(7, { name: "trilium-save-selection" });+ expect(facade.callService).toHaveBeenCalledWith("POST", "clippings", {+ title: "Page",+ content: "<p>Selected</p>",+ images: [+ { imageId: "i1", src: "https://example.com/missing.png" },+ {+ imageId: "i2",+ src: "https://example.com/a.png",+ dataUrl: expect.stringMatching(PNG_DATA_URL)+ },+ {+ imageId: "i3",+ src: "inline.jpeg",+ dataUrl: "data:image/jpeg;base64,/9j/4AAQ"+ },+ {+ imageId: "i4",+ src: "data:image/;base64,AAAA",+ dataUrl: "data:image/;base64,AAAA"+ }+ ]+ });+ expect(console.error).toHaveBeenCalledOnce();+ expect(await lastToast())+ .toMatchObject({ name: "toast", noteId: "saved", tabIds: null });+ });++ it("is bound to the keyboard shortcut and shows no toast when saving fails", async () => {+ tabMessageHandler = () => ({ title: "Page", content: "x" });+ facade.callService.mockResolvedValue(null);++ await onCommand("saveSelection");++ expect(facade.callService)+ .toHaveBeenCalledWith("POST", "clippings", { title: "Page", content: "x" });+ expect(await lastToast()).toBeUndefined();+ });++ it("fails when there is no active tab", async () => {+ tabs = [];+ await expect(onCommand("saveSelection")).rejects.toThrow("No active tab.");++ tabs = [ { title: "Tab without id" } ];+ await expect(onCommand("saveSelection")).rejects.toThrow("No active tab.");+ expect(facade.callService).not.toHaveBeenCalled();+ });+ });++ describe("saving the whole page", () => {+ it("saves the readable page from the shortcut, the menu and the popup", async () => {+ const page = { title: "Article", content: "<p>Body</p>", images: [], clipType: "page" };+ tabMessageHandler = () => page;++ await onCommand("saveWholePage");+ await onContextMenuClicked({ menuItemId: "trilium-save-page" });+ await sendRuntimeMessage({ name: "save-whole-page" });++ expect(facade.callService).toHaveBeenCalledTimes(3);+ expect(facade.callService).toHaveBeenLastCalledWith("POST", "notes", page);+ expect(await lastToast()).toMatchObject({ noteId: "saved" });++ facade.callService.mockResolvedValue(null);+ tabsSendMessage.mockClear();+ await onCommand("saveWholePage");+ expect(await lastToast()).toBeUndefined();+ });+ });++ describe("screenshots", () => {+ it("crops the screenshot in an offscreen document and saves it as an image", async () => {+ tabMessageHandler = () => ({+ rect: { x: 10, y: 20, width: 100, height: 50 },+ devicePixelRatio: 2+ });++ await onCommand("saveCroppedScreenshot");++ expect(createDocument).toHaveBeenCalledOnce();+ expect(runtimeSendMessage).toHaveBeenCalledWith({+ type: "CROP_IMAGE",+ dataUrl: PNG,+ cropRect: { x: 30, y: 60, width: 300, height: 150 }+ });+ const [ method, path, payload ] = facade.callService.mock.calls[0] ?? [];+ expect([ method, path ]).toEqual([ "POST", "clippings" ]);+ expect(payload).toEqual({+ title: "Active page",+ content: expect.stringMatching(/^<img src="[A-Za-z0-9]{20}">$/),+ images: [ { imageId: expect.any(String), src: "inline.png", dataUrl: PNG } ],+ pageUrl: PAGE_URL+ });+ const { content, images } = payload as {+ content: string,+ images: { imageId: string }[]+ };+ expect(content).toContain(images[0]?.imageId);+ expect(await lastToast()).toMatchObject({ noteId: "saved" });+ });++ it("reuses the offscreen document and uses the context menu's page URL", async () => {+ tabMessageHandler = () => ({ rect: { x: 0, y: 0, width: 10, height: 10 } });+ getContexts.mockResolvedValue([ { contextType: "OFFSCREEN_DOCUMENT" } ]);++ await onContextMenuClicked({+ menuItemId: "trilium-save-cropped-screenshot",+ pageUrl: MENU_URL+ });++ expect(createDocument).not.toHaveBeenCalled();+ expect(runtimeSendMessage).toHaveBeenCalledWith(expect.objectContaining({+ cropRect: { x: 0, y: 0, width: 15, height: 15 }+ }));+ expect(lastPayload()).toMatchObject({ pageUrl: MENU_URL });++ facade.callService.mockResolvedValue(null);+ tabsSendMessage.mockClear();+ await sendRuntimeMessage({ name: "save-cropped-screenshot" });+ expect(lastPayload()).toMatchObject({ pageUrl: PAGE_URL });+ expect(await lastToast()).toBeUndefined();+ });++ it("saves the visible part of the page", async () => {+ await onContextMenuClicked({+ menuItemId: "trilium-save-whole-screenshot",+ pageUrl: MENU_URL+ });+ expect(lastPayload()).toMatchObject({+ images: [ { src: "inline.png", dataUrl: PNG } ],+ pageUrl: MENU_URL+ });+ expect(await lastToast()).toMatchObject({ noteId: "saved" });++ facade.callService.mockResolvedValue(null);+ tabsSendMessage.mockClear();+ await sendRuntimeMessage({ name: "save-whole-screenshot" });+ expect(lastPayload()).toMatchObject({ pageUrl: PAGE_URL });+ expect(await lastToast()).toBeUndefined();+ });++ it("crops the screenshot on a canvas under Manifest V2", async () => {+ vi.stubGlobal("__MANIFEST_VERSION__", 2);+ const drawImage = vi.fn();+ const getContext = vi.spyOn(HTMLCanvasElement.prototype, "getContext")+ .mockReturnValue({ drawImage } as unknown as CanvasRenderingContext2D);+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(CROPPED_PNG);+ const image = stubImageLoading();+ tabMessageHandler = () => ({+ rect: { x: 10, y: 20, width: 100, height: 50 },+ devicePixelRatio: 1+ });++ await onCommand("saveCroppedScreenshot");++ expect(runtimeSendMessage).not.toHaveBeenCalled();+ expect(drawImage)+ .toHaveBeenCalledWith(image.instances[0], 15, 30, 150, 75, 0, 0, 150, 75);+ expect(lastPayload()).toMatchObject({+ images: [ { src: "inline.png", dataUrl: CROPPED_PNG } ]+ });++ getContext.mockReturnValue(null);+ await expect(onCommand("saveCroppedScreenshot")).rejects.toBeUndefined();++ image.fail = true;+ await expect(onCommand("saveCroppedScreenshot")).rejects.toBeInstanceOf(Event);+ });+ });++ describe("context menu", () => {+ it("saves an image by fetching it", async () => {+ await onContextMenuClicked({ menuItemId: "trilium-save-image", pageUrl: PAGE_URL });+ expect(facade.callService).not.toHaveBeenCalled();++ await onContextMenuClicked({+ menuItemId: "trilium-save-image",+ srcUrl: "https://example.com/cat.png",+ pageUrl: PAGE_URL+ });+ expect(fetchMock).toHaveBeenCalledWith("https://example.com/cat.png");+ expect(lastPayload()).toMatchObject({+ title: "Active page",+ images: [ {+ src: "https://example.com/cat.png",+ dataUrl: expect.stringMatching(PNG_DATA_URL)+ } ],+ pageUrl: PAGE_URL+ });+ expect(await lastToast()).toMatchObject({ noteId: "saved" });++ facade.callService.mockResolvedValue(null);+ tabsSendMessage.mockClear();+ await onContextMenuClicked({+ menuItemId: "trilium-save-image",+ srcUrl: "https://example.com/cat.png"+ });+ expect(await lastToast()).toBeUndefined();+ });++ it("saves a link, with its URL as the text when the browser gives none", async () => {+ await onContextMenuClicked({ menuItemId: "trilium-save-link", pageUrl: PAGE_URL });+ expect(facade.callService).not.toHaveBeenCalled();++ await onContextMenuClicked({+ menuItemId: "trilium-save-link",+ linkUrl: "https://example.com/target",+ linkText: "Target",+ pageUrl: PAGE_URL+ });+ expect(facade.callService).toHaveBeenLastCalledWith("POST", "clippings", {+ title: "Active page",+ content: "<a href=\"https://example.com/target\">Target</a>",+ pageUrl: PAGE_URL+ });+ expect(await lastToast()).toMatchObject({ noteId: "saved" });++ facade.callService.mockResolvedValue(null);+ tabsSendMessage.mockClear();+ await onContextMenuClicked({+ menuItemId: "trilium-save-link",+ linkUrl: "https://example.com/target"+ });+ expect(lastPayload()).toMatchObject({+ content: "<a href=\"https://example.com/target\">https://example.com/target</a>"+ });+ expect(await lastToast()).toBeUndefined();+ });++ it("ignores unknown items and commands", async () => {+ await onContextMenuClicked({ menuItemId: "unknown" });+ await onCommand("unknown");+ expect(facade.callService).not.toHaveBeenCalled();+ expect(tabsSendMessage).not.toHaveBeenCalled();+ });+ });++ describe("saving tabs", () => {+ it("saves the tabs as a list of links, titled by the most common domains", async () => {+ tabs = [+ { id: 1, title: "A1", url: "https://a.com/1" },+ { id: 2, title: "B1", url: "https://b.com/1" },+ { title: "B2", url: "https://b.com/2" },+ { id: 4, title: "C1", url: "https://c.com/1" },+ { id: 5, title: "D1", url: "https://d.com/1" }+ ];++ await onCommand("saveTabs");++ expect(facade.callService).toHaveBeenCalledWith("POST", "notes", {+ title: "5 browser tabs: b.com, a.com, c.com...",+ content: "<ul>"+ + "<li><a href=\"https://a.com/1\">A1</a></li>"+ + "<li><a href=\"https://b.com/1\">B1</a></li>"+ + "<li><a href=\"https://b.com/2\">B2</a></li>"+ + "<li><a href=\"https://c.com/1\">C1</a></li>"+ + "<li><a href=\"https://d.com/1\">D1</a></li>"+ + "</ul>",+ clipType: "tabs"+ });+ expect(await lastToast()).toMatchObject({ noteId: "saved", tabIds: [ 1, 2, 4, 5 ] });+ });++ it("adds no ellipsis for up to three tabs and shows no toast on failure", async () => {+ tabs = [+ { id: 1, title: "A", url: "https://a.com/" },+ { id: 2, title: "B", url: "https://b.com/" }+ ];+ facade.callService.mockResolvedValue(null);++ await sendRuntimeMessage({ name: "save-tabs" });++ expect(lastPayload()).toMatchObject({ title: "2 browser tabs: a.com, b.com" });+ expect(await lastToast()).toBeUndefined();+ });+ });++ describe("popup and toast messages", () => {+ it("saves a link with a note, titled after the tab when the title is blank", async () => {+ const saveWithTitle = (title: string, content = "") => sendRuntimeMessage({+ name: "save-link-with-note",+ title,+ content+ });++ await expect(saveWithTitle(" ", "Note")).resolves.toBe(true);+ expect(facade.callService).toHaveBeenLastCalledWith("POST", "notes", {+ title: "Active page",+ content: "Note",+ clipType: "note",+ pageUrl: PAGE_URL+ });+ expect(await lastToast()).toMatchObject({ noteId: "saved" });++ facade.callService.mockResolvedValue(null);+ await expect(saveWithTitle("Mine")).resolves.toBe(false);+ expect(lastPayload()).toMatchObject({ title: "Mine" });++ tabs = [ { id: 7, url: "https://example.com/untitled" } ];+ await saveWithTitle("");+ expect(lastPayload()).toMatchObject({ title: "" });+ });++ it("opens a note in the browser when the desktop app cannot", async () => {+ const create = vi.fn(async (_properties: { url: string }) => ({}));+ Object.assign(fakeBrowser.tabs, { create });+ const openNote = () => sendRuntimeMessage({ name: "openNoteInTrilium", noteId: "n1" });++ facade.callService.mockResolvedValue({ result: "ok" });+ await openNote();+ expect(facade.callService).toHaveBeenLastCalledWith("POST", "open/n1");++ facade.callService.mockResolvedValue(null);+ await openNote();++ facade.callService.mockResolvedValue({ result: "open-in-browser" });+ await openNote();+ expect(console.error).toHaveBeenCalledOnce();+ expect(create).not.toHaveBeenCalled();++ await fakeBrowser.storage.sync.set({ triliumServerUrl: "https://trilium.example" });+ await openNote();+ expect(create).toHaveBeenCalledExactlyOnceWith({ url: "https://trilium.example/#n1" });+ });++ it("closes the saved tabs", async () => {+ const remove = vi.spyOn(fakeBrowser.tabs, "remove").mockResolvedValue(undefined);+ await sendRuntimeMessage({ name: "closeTabs", tabIds: [ 1, 2 ] });+ expect(remove).toHaveBeenCalledWith([ 1, 2 ]);+ });++ it("forwards Trilium searches to the server facade", async () => {+ await sendRuntimeMessage({ name: "trigger-trilium-search" });+ expect(facade.triggerSearchForTrilium).toHaveBeenCalledOnce();++ await sendRuntimeMessage({ name: "send-trilium-search-status" });+ expect(facade.sendTriliumSearchStatusToPopup).toHaveBeenCalledOnce();++ await sendRuntimeMessage({ name: "trigger-trilium-search-note-url" });+ expect(facade.triggerSearchNoteByUrl).toHaveBeenCalledWith(PAGE_URL);++ tabs = [ { id: 7 } ];+ await sendRuntimeMessage({ name: "trigger-trilium-search-note-url" });+ expect(facade.triggerSearchNoteByUrl).toHaveBeenCalledOnce();++ await expect(sendRuntimeMessage({ name: "unknown" })).resolves.toBeUndefined();+ });+ });+});++async function sendRuntimeMessage(message: object) {+ const [ result ] = await fakeBrowser.runtime.onMessage.trigger(message, {}, () => {});+ return result;+}++function lastPayload() {+ return facade.callService.mock.lastCall?.[2];+}++async function lastToast() {+ await new Promise((resolve) => setTimeout(resolve));+ return tabsSendMessage.mock.calls+ .map(([ , message ]) => message)+ .filter((message) => message.name === "toast")+ .at(-1);+}++function stubImageLoading() {+ const state = { fail: false, instances: [] as object[] };+ vi.stubGlobal("Image", class {++ onload: (() => void) | null = null;+ onerror: ((event: Event) => void) | null = null;++ constructor() {+ state.instances.push(this);+ }++ set src(_value: string) {+ setTimeout(() => (state.fail ? this.onerror?.(new Event("error")) : this.onload?.()));+ }++ });+ return state;+}diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.tsnew file mode 100644index 0000000000..072f3cbcd5--- /dev/null+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts@@ -0,0 +1,253 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fakeBrowser } from "wxt/testing/fake-browser";++import TriliumServerFacade from "./trilium_server_facade";++const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>();+const SERVER = { triliumServerUrl: "https://trilium.example", authToken: "secret" };+const LOCAL_DATE_TIME = /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3}[+-]\d\d:\d\d$/;++type PopupMessage = { name: string, triliumSearch?: unknown, searchNote?: unknown };+const sendMessage = vi.fn(async (_message: PopupMessage) => {});++describe("TriliumServerFacade", () => {+ beforeEach(() => {+ fakeBrowser.reset();+ vi.useFakeTimers();+ vi.stubGlobal("fetch", fetchMock);+ fetchMock.mockReset();+ sendMessage.mockReset();+ Object.assign(fakeBrowser.runtime, { sendMessage });+ vi.spyOn(console, "log").mockImplementation(() => {});+ vi.spyOn(console, "debug").mockImplementation(() => {});+ });++ afterEach(() => {+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ describe("search for Trilium", () => {+ it("finds the desktop app on the default port and reports it to the popup", async () => {+ fetchMock.mockResolvedValue(handshake("1.0"));++ await createFacade();++ expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:37742/api/clipper/handshake");+ expect(searchStatuses()).toEqual([+ { status: "searching" },+ { status: "found-desktop", port: 37742, url: "http://127.0.0.1:37742" }+ ]);+ });++ it("uses the configured desktop port and searches again every minute", async () => {+ await fakeBrowser.storage.sync.set({ triliumDesktopPort: "12345" });+ fetchMock.mockResolvedValue(handshake("1.2"));++ await createFacade();+ expect(fetchMock)+ .toHaveBeenLastCalledWith("http://127.0.0.1:12345/api/clipper/handshake");++ await vi.advanceTimersByTimeAsync(60 * 1000);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("reports a protocol version mismatch", async () => {+ fetchMock.mockResolvedValue(handshake("2.0"));++ await createFacade();++ expect(lastSearchStatus()).toEqual({+ status: "version-mismatch",+ extensionMajor: 1,+ triliumMajor: 2+ });+ });++ it("falls back to the configured server with its token", async () => {+ await fakeBrowser.storage.sync.set(SERVER);+ fetchMock.mockImplementation(async (url) => {+ if (url.startsWith("http://127.0.0.1")) throw new Error("connection refused");+ return handshake("1.0");+ });++ await createFacade();++ expect(fetchMock).toHaveBeenLastCalledWith(+ "https://trilium.example/api/clipper/handshake",+ { headers: { Authorization: "secret" } });+ expect(lastSearchStatus()).toEqual({+ status: "found-server",+ url: "https://trilium.example",+ token: "secret"+ });+ });++ it("reports not-found when neither the desktop app nor the server is Trilium", async () => {+ await fakeBrowser.storage.sync.set(SERVER);+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ appName: "other" })));+ await createFacade();+ expect(lastSearchStatus()).toEqual({ status: "not-found" });++ fetchMock.mockReset();+ fetchMock.mockImplementation(async (url) => {+ if (url.startsWith("http://127.0.0.1")) return new Response("not json");+ throw new Error("server down");+ });+ await createFacade();+ expect(lastSearchStatus()).toEqual({ status: "not-found" });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("skips the server when no URL or token is configured", async () => {+ await fakeBrowser.storage.sync.set({ triliumServerUrl: "https://trilium.example" });+ fetchMock.mockRejectedValue(new Error("connection refused"));++ await createFacade();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(lastSearchStatus()).toEqual({ status: "not-found" });+ });++ it("ignores the popup being closed", async () => {+ sendMessage.mockRejectedValue(new Error("Could not establish connection"));+ fetchMock.mockResolvedValue(handshake("1.0"));++ const facade = await createFacade();+ await expect(facade.sendTriliumSearchNoteToPopup()).resolves.toBeUndefined();+ });+ });++ describe("callService", () => {+ it("sends JSON with the token and the local time to the found server", async () => {+ await fakeBrowser.storage.sync.set(SERVER);+ fetchMock.mockImplementation(async (url) => {+ if (url.startsWith("http://127.0.0.1")) throw new Error("connection refused");+ if (url.endsWith("/handshake")) return handshake("1.0");+ return Response.json({ noteId: "n1" });+ });+ const facade = await createFacade();++ await expect(facade.callService("POST", "clippings", { title: "T" }))+ .resolves.toEqual({ noteId: "n1" });+ const clippingsUrl = "https://trilium.example/api/clipper/clippings";+ expect(fetchMock).toHaveBeenLastCalledWith(clippingsUrl, {+ method: "POST",+ headers: {+ Authorization: "secret",+ "Content-Type": "application/json",+ "trilium-local-now-datetime": expect.stringMatching(LOCAL_DATE_TIME)+ },+ body: JSON.stringify({ title: "T" })+ });++ await facade.callService("POST", "notes", "raw body");+ expect(fetchMock.mock.lastCall?.[1]?.body).toBe("raw body");++ await facade.callService("GET", "notes-by-url/x");+ expect(fetchMock.mock.lastCall?.[1]).not.toHaveProperty("body");+ });++ it("sends no token to the desktop app and returns null when a request fails", async () => {+ fetchMock.mockResolvedValue(handshake("1.0"));+ const facade = await createFacade();++ fetchMock.mockResolvedValue(new Response("Note not found", { status: 404 }));+ await expect(facade.callService("POST", "open/abc")).resolves.toBeNull();+ expect(fetchMock).toHaveBeenLastCalledWith(+ "http://127.0.0.1:37742/api/clipper/open/abc",+ expect.objectContaining({+ headers: expect.objectContaining({ Authorization: "" })+ }));++ fetchMock.mockRejectedValue(new Error("connection reset"));+ await expect(facade.callService("POST", "open/abc")).resolves.toBeNull();+ });++ it("waits for a running search and rejects once Trilium is not found", async () => {+ let answerHandshake: (response: Response) => void = () => {};+ fetchMock.mockReturnValueOnce(new Promise((resolve) => answerHandshake = resolve));+ const facade = new TriliumServerFacade();++ const call = facade.callService("GET", "notes-by-url/x");+ await vi.advanceTimersByTimeAsync(1500);+ expect(fetchMock).toHaveBeenCalledTimes(1);++ fetchMock.mockResolvedValue(Response.json({ noteId: "n1" }));+ answerHandshake(handshake("1.0"));+ await vi.advanceTimersByTimeAsync(500);+ await expect(call).resolves.toEqual({ noteId: "n1" });++ fetchMock.mockReset();+ fetchMock.mockRejectedValue(new Error("connection refused"));+ await facade.triggerSearchForTrilium();+ await expect(facade.callService("GET", "notes-by-url/x")).rejects.toThrow();+ });++ it("returns undefined while Trilium has a different protocol version", async () => {+ fetchMock.mockResolvedValue(handshake("0.9"));+ const facade = await createFacade();++ await expect(facade.callService("GET", "notes-by-url/x")).resolves.toBeUndefined();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+ });++ it("looks up the note saved for a URL and reports it to the popup", async () => {+ fetchMock.mockResolvedValue(handshake("1.0"));+ const facade = await createFacade();++ fetchMock.mockResolvedValue(Response.json({ noteId: "n1" }));+ await facade.triggerSearchNoteByUrl("https://example.com/a?b=c");+ expect(fetchMock).toHaveBeenLastCalledWith(+ "http://127.0.0.1:37742/api/clipper/notes-by-url/https%3A%2F%2Fexample.com%2Fa%3Fb%3Dc",+ expect.objectContaining({ method: "GET" }));+ expect(sendMessage).toHaveBeenLastCalledWith({+ name: "trilium-previously-visited",+ searchNote: { status: "found", noteId: "n1" }+ });++ fetchMock.mockResolvedValue(Response.json({ noteId: null }));+ await facade.triggerSearchNoteByUrl("https://example.com/b");+ expect(sendMessage).toHaveBeenLastCalledWith({+ name: "trilium-previously-visited",+ searchNote: { status: "not-found", noteId: null }+ });+ });++ it("formats the local time with the time zone offset", async () => {+ fetchMock.mockResolvedValue(handshake("1.0"));+ const facade = await createFacade();+ vi.setSystemTime(new Date("2026-03-04T10:20:30.456Z"));++ vi.spyOn(Date.prototype, "getTimezoneOffset").mockReturnValue(-120);+ expect(facade.localNowDateTime()).toBe("2026-03-04 12:20:30.456+02:00");++ vi.spyOn(Date.prototype, "getTimezoneOffset").mockReturnValue(300);+ expect(facade.localNowDateTime()).toBe("2026-03-04 05:20:30.456-05:00");+ });+});++function handshake(protocolVersion: string) {+ return Response.json({ appName: "trilium", protocolVersion });+}++async function createFacade() {+ sendMessage.mockClear();+ const facade = new TriliumServerFacade();+ await vi.waitFor(() => expect(lastSearchStatus()?.status).not.toBe("searching"));+ return facade;+}++function searchStatuses() {+ return sendMessage.mock.calls+ .map(([ message ]) => message)+ .filter((message) => message.name === "trilium-search-status")+ .map((message) => message.triliumSearch);+}++function lastSearchStatus() {+ return searchStatuses().at(-1) as { status: string } | undefined;+}diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.tsnew file mode 100644index 0000000000..6493cff7a2--- /dev/null+++ b/apps/web-clipper/entrypoints/content/index.spec.ts@@ -0,0 +1,225 @@+import type { Window as HappyDOMWindow } from "happy-dom";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { fakeBrowser } from "wxt/testing/fake-browser";++vi.mock("@/lib/toast", () => ({}));++import contentScript from "./index";++type Rect = { x: number, y: number, width: number, height: number };+type Clipping = {+ title: string,+ content: string,+ images: { imageId: string, src: string }[],+ pageUrl: string+};++const PARAGRAPH = "Trilium is a hierarchical note taking application with focus on "+ + "building large personal knowledge bases. It supports rich text, code, canvas and many "+ + "other note types, scripting and sync. ";++describe("content script", () => {+ beforeAll(() => {+ contentScript.main(undefined as never);+ });++ beforeEach(() => {+ setUrl("https://example.com/blog/post.html?id=1#comments");+ document.head.innerHTML = "<title> Post title </title>";+ document.body.innerHTML = "";+ vi.spyOn(console, "info").mockImplementation(() => {});+ vi.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ describe("saving the selection", () => {+ it("returns the selected HTML with absolute links and deduplicated images", async () => {+ document.body.innerHTML = `+ <p id="start">Before <a href="other.html">relative</a> and <a>no href</a></p>+ <img src="/cat.png">+ <img src="https://cdn.example.com/dog.png">+ <img src="/cat.png">+ <img>+ <p id="end">After</p>`;+ selectRange("start", "end");++ const response = await send<Clipping>({ name: "trilium-save-selection" });++ expect(response.title).toBe("Post title");+ expect(response.pageUrl).toBe("https://example.com/blog/post.html?id=1#comments");+ expect(response.images.map((image) => image.src)).toEqual([+ "https://example.com/cat.png",+ "https://cdn.example.com/dog.png"+ ]);+ const container = document.createElement("div");+ container.innerHTML = response.content;+ expect(attributes(container, "a", "href"))+ .toEqual([ "https://example.com/blog/other.html", null ]);+ expect(attributes(container, "img", "src")).toEqual([+ response.images[0]?.imageId,+ response.images[1]?.imageId,+ response.images[0]?.imageId,+ null+ ]);+ });++ it("falls back to the document title and fails without a selection", async () => {+ document.head.innerHTML = "";+ document.title = " Fallback ";+ document.body.innerHTML = "<p id=\"p\">Text</p>";+ selectRange("p", "p");+ expect(await send({ name: "trilium-save-selection" }))+ .toMatchObject({ title: "Fallback" });++ window.getSelection()?.removeAllRanges();+ expect(await send({ name: "trilium-save-selection" })).toBeUndefined();+ expect(console.error).toHaveBeenCalledOnce();+ });+ });++ describe("saving the page", () => {+ it("returns the readable article with its publication dates as labels", async () => {+ document.head.innerHTML = `+ <title>Article title</title>+ <meta property="article:published_time" content="2026-01-02T10:00:00Z">+ <meta property="article:modified_time" content="2026-02-03T10:00:00Z">`;+ document.body.innerHTML = `+ <nav><a href="/">Home</a></nav>+ <article>+ <h1>Article title</h1>+ <p>${PARAGRAPH.repeat(3)}<a href="/docs">Docs</a></p>+ <p>${PARAGRAPH.repeat(3)}</p>+ <img src="figure.png">+ <p>${PARAGRAPH.repeat(3)}</p>+ </article>`;++ const response = await send<Record<string, unknown>>({ name: "trilium-save-page" });++ expect(response).toMatchObject({+ title: "Article title",+ pageUrl: "https://example.com/blog/post.html?id=1",+ clipType: "page",+ labels: { publishedDate: "2026-01-02", modifiedDate: "2026-02-03" },+ images: [ {+ imageId: expect.any(String),+ src: "https://example.com/blog/figure.png"+ } ]+ });+ expect(response.content).toContain("href=\"https://example.com/docs\"");+ expect(response.content).not.toContain("Home");+ expect(document.querySelector("nav")).not.toBeNull();+ });++ it("adds no labels without dates and fails when Readability finds no article", async () => {+ document.body.innerHTML = `<article><p>${PARAGRAPH.repeat(5)}</p></article>`;+ expect(await send({ name: "trilium-save-page" })).toMatchObject({ labels: {} });++ document.body.innerHTML = "";+ vi.spyOn(Document.prototype, "cloneNode")+ .mockReturnValue(document.implementation.createHTMLDocument(""));+ expect(await send({ name: "trilium-save-page" })).toBeUndefined();+ });+ });++ describe("screenshot area", () => {+ it("returns the dragged rectangle once the overlay is gone", async () => {+ vi.useFakeTimers();+ const response = send<{ rect: Rect | null, devicePixelRatio: number }>({+ name: "trilium-get-rectangle-for-screenshot"+ });+ const [ overlay, messageComp, selection ] =+ [ ...document.body.children ] as HTMLElement[];+ expect(document.activeElement).toBe(messageComp);++ mouse(overlay, "mousemove", 5, 5);+ mouse(overlay, "mousedown", 200, 150);+ mouse(overlay, "mousemove", 100, 100);+ const { left, top, width, height } = selection?.style ?? {};+ expect([ left, top, width, height ]).toEqual([ "100px", "100px", "100px", "50px" ]);+ mouse(overlay, "mouseup", 50, 50);+ expect(document.body.children).toHaveLength(0);++ await vi.advanceTimersByTimeAsync(100);+ await expect(response).resolves.toEqual({+ rect: { x: 50, y: 50, width: 150, height: 100 },+ devicePixelRatio: window.devicePixelRatio+ });+ });++ it("returns no rectangle without a drag on the overlay or after Escape", async () => {+ const release = send({ name: "trilium-get-rectangle-for-screenshot" });+ mouse(document.body.firstElementChild, "mouseup", 10, 10);+ await expect(release).resolves.toMatchObject({ rect: null });++ const cancelled = send({ name: "trilium-get-rectangle-for-screenshot" });+ const messageComp = document.body.children[1];+ messageComp?.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));+ expect(document.body.children).toHaveLength(3);+ messageComp?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ expect(document.body.children).toHaveLength(0);+ await expect(cancelled).resolves.toMatchObject({ rect: null });+ });+ });++ describe("toast", () => {+ it("shows a plain message, or links to the saved note and the saved tabs", async () => {+ const showToast = vi.fn();+ window.showToast = showToast;+ const sendMessage = vi.spyOn(fakeBrowser.runtime, "sendMessage")+ .mockResolvedValue(undefined);++ await send({ name: "toast", message: "Saved." });+ expect(showToast)+ .toHaveBeenLastCalledWith("Saved.", { settings: { duration: 7000 } });++ await send({ name: "toast", message: "Saved.", noteId: "n1" });+ const noteMessage = showToast.mock.lastCall?.[0] as HTMLElement;+ expect(noteMessage.querySelectorAll("a")).toHaveLength(1);++ await send({ name: "toast", message: "Saved.", noteId: "n1", tabIds: [ 1, 2 ] });+ const tabsMessage = showToast.mock.lastCall?.[0] as HTMLElement;+ const [ openLink, closeLink ] = tabsMessage.querySelectorAll("a");+ openLink?.click();+ closeLink?.click();+ expect(sendMessage.mock.calls).toEqual([+ [ null, { name: "openNoteInTrilium", noteId: "n1" } ],+ [ null, { name: "closeTabs", tabIds: [ 1, 2 ] } ]+ ]);+ });+ });++ it("answers unknown messages with nothing", async () => {+ expect(await send({ name: "unknown" })).toBeUndefined();+ expect(console.error).toHaveBeenCalledOnce();+ });+});++function send<T = unknown>(message: object) {+ return new Promise<T>((resolve) => {+ void fakeBrowser.runtime.onMessage.trigger(message, {}, resolve);+ });+}++function mouse(target: Element | null | undefined, type: string, clientX: number, clientY: number) {+ target?.dispatchEvent(new MouseEvent(type, { clientX, clientY }));+}++function attributes(container: HTMLElement, selector: string, attribute: string) {+ return [ ...container.querySelectorAll(selector) ].map((el) => el.getAttribute(attribute));+}++function selectRange(startId: string, endId: string) {+ const range = document.createRange();+ range.setStartBefore(document.getElementById(startId) as Node);+ range.setEndAfter(document.getElementById(endId) as Node);+ window.getSelection()?.removeAllRanges();+ window.getSelection()?.addRange(range);+}++function setUrl(url: string) {+ (window as unknown as HappyDOMWindow).happyDOM.setURL(url);+}diff --git a/apps/web-clipper/entrypoints/offscreen/index.spec.ts b/apps/web-clipper/entrypoints/offscreen/index.spec.tsnew file mode 100644index 0000000000..b60f06b937--- /dev/null+++ b/apps/web-clipper/entrypoints/offscreen/index.spec.ts@@ -0,0 +1,66 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { fakeBrowser } from "wxt/testing/fake-browser";++import "./index";++const CROPPED_PNG = "data:image/png;base64,Q1JPUA==";++describe("offscreen document", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("crops the image on a canvas and answers asynchronously", async () => {+ const images: { src?: string, onload?: () => void }[] = [];+ vi.stubGlobal("Image", class {++ onload?: () => void;++ constructor() {+ images.push(this);+ }++ set src(value: string) {+ Object.defineProperty(this, "src", { value });+ setTimeout(() => this.onload?.());+ }++ });+ const drawImage = vi.fn();+ const getContext = vi.spyOn(HTMLCanvasElement.prototype, "getContext")+ .mockReturnValue({ drawImage } as unknown as CanvasRenderingContext2D);+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(CROPPED_PNG);++ const response = await sendMessage({+ type: "CROP_IMAGE",+ dataUrl: "data:image/png;base64,AAAA",+ cropRect: { x: 1, y: 2, width: 30, height: 40 }+ });++ expect(response).toBe(CROPPED_PNG);+ expect(images[0]?.src).toBe("data:image/png;base64,AAAA");+ expect(drawImage).toHaveBeenCalledWith(images[0], 1, 2, 30, 40, 0, 0, 30, 40);+ const canvas = getContext.mock.contexts[0] as HTMLCanvasElement;+ expect([ canvas.width, canvas.height ]).toEqual([ 30, 40 ]);++ getContext.mockReturnValue(null);+ const emptyCrop = {+ type: "CROP_IMAGE",+ dataUrl: "",+ cropRect: { x: 0, y: 0, width: 1, height: 1 }+ };+ await expect(sendMessage(emptyCrop)).resolves.toBe(CROPPED_PNG);+ });++ it("ignores other messages", async () => {+ const other = await fakeBrowser.runtime.onMessage.trigger({ type: "OTHER" }, {}, () => {});+ expect(other).toEqual([ undefined ]);+ });+});++function sendMessage(message: object) {+ return new Promise((resolve) => {+ void fakeBrowser.runtime.onMessage.trigger(message, {}, resolve);+ });+}diff --git a/apps/web-clipper/package.json b/apps/web-clipper/package.jsonindex 867bfa1608..8cc5cee344 100644--- a/apps/web-clipper/package.json+++ b/apps/web-clipper/package.json@@ -10,6 +10,8 @@"build:firefox": "wxt build -b firefox","zip": "wxt zip","zip:firefox": "wxt zip -b firefox",+ "test": "vitest",+ "coverage": "vitest --coverage","postinstall": "wxt prepare"},"keywords": [],diff --git a/apps/web-clipper/utils.spec.ts b/apps/web-clipper/utils.spec.tsnew file mode 100644index 0000000000..47ed5aa1df--- /dev/null+++ b/apps/web-clipper/utils.spec.ts@@ -0,0 +1,52 @@+import type { Window as HappyDOMWindow } from "happy-dom";+import { afterEach, describe, expect, it, vi } from "vitest";+import { fakeBrowser } from "wxt/testing/fake-browser";++import { createLink, getBaseUrl, getPageLocationOrigin, randomString } from "./utils";++describe("randomString", () => {+ it("returns alphanumeric strings of the requested length", () => {+ expect(randomString(0)).toBe("");+ expect(randomString(20)).toMatch(/^[A-Za-z0-9]{20}$/);+ expect(randomString(20)).not.toBe(randomString(20));+ });+});++describe("page location", () => {+ afterEach(() => setUrl("about:blank"));++ it("strips the file name from the base URL", () => {+ setUrl("https://example.com:8080/dir/page.html?q=1#hash");+ expect(getPageLocationOrigin()).toBe("https://example.com:8080");+ expect(getBaseUrl()).toBe("https://example.com:8080/dir");++ setUrl("https://example.com/dir/");+ expect(getBaseUrl()).toBe("https://example.com/dir/");+ });++ it("uses file:// as the origin of local files", () => {+ setUrl("file:///home/user/page.html");+ expect(getPageLocationOrigin()).toBe("file://");+ expect(getBaseUrl()).toBe("file:///home/user");+ });+});++describe("createLink", () => {+ it("sends the click action to the extension", () => {+ const sendMessage = vi.spyOn(fakeBrowser.runtime, "sendMessage")+ .mockResolvedValue(undefined);+ const action = { name: "openNoteInTrilium", noteId: "abc" };++ const link = createLink(action, "Open");+ expect(link.textContent).toBe("Open");+ expect(link.style.color).toBe("lightskyblue");+ expect(createLink(action, "Close", "tomato").style.color).toBe("tomato");++ link.click();+ expect(sendMessage).toHaveBeenCalledWith(null, action);+ });+});++function setUrl(url: string) {+ (window as unknown as HappyDOMWindow).happyDOM.setURL(url);+}diff --git a/apps/web-clipper/vitest.config.mts b/apps/web-clipper/vitest.config.mtsnew file mode 100644index 0000000000..be833e38ee--- /dev/null+++ b/apps/web-clipper/vitest.config.mts@@ -0,0 +1,44 @@+import { join } from "path";+import type { Plugin } from "vite";+import { defineConfig } from "vitest/config";+import { WxtVitest } from "wxt/testing/vitest-plugin";++export default defineConfig({+ plugins: [ manifestVersionGlobal(), WxtVitest() ],+ test: {+ environment: "happy-dom",+ include: [ "**/*.{test,spec}.ts" ],+ exclude: [ "**/node_modules/**", ".output/**", ".wxt/**" ],+ reporters: [+ "default",+ [ "junit", {+ outputFile: join(import.meta.dirname, "test-output/vitest/junit.xml"),+ addFileAttribute: true+ } ]+ ],+ coverage: {+ reportsDirectory: join(import.meta.dirname, "test-output/vitest/coverage"),+ provider: "v8" as const,+ include: [ "entrypoints/**/*.ts", "utils.ts" ],+ exclude: [ "**/*.{test,spec}.ts", "**/*.d.ts" ],+ reporter: [ "text", "lcov" ]+ }+ }+});++/**+ * Vitest stores `import.meta.env` values as strings, so WXT's numeric `MANIFEST_VERSION` arrives+ * as `"3"` and `=== 3` never matches. Reading it from `globalThis.__MANIFEST_VERSION__` keeps+ * the number and lets a spec switch between Manifest V2 and V3.+ */+function manifestVersionGlobal(): Plugin {+ const MANIFEST_VERSION = "import.meta.env.MANIFEST_VERSION";+ return {+ name: "manifest-version-global",+ enforce: "pre",+ transform(code, id) {+ if (id.includes("node_modules") || !code.includes(MANIFEST_VERSION)) return;+ return code.replaceAll(MANIFEST_VERSION, "(globalThis.__MANIFEST_VERSION__ ?? 3)");+ }+ };+}