Skip to content

Build your personal knowledge base with Trilium Notes

refactor(desktop): use core imports where applicable

Elian Doranec4ed4ee0651
diff --git a/apps/desktop/src/ipc_messaging_provider.spec.ts b/apps/desktop/src/ipc_messaging_provider.spec.ts
index d9b1dfe283..1ef69f0649 100644
--- a/apps/desktop/src/ipc_messaging_provider.spec.ts
+++ b/apps/desktop/src/ipc_messaging_provider.spec.ts
@@ -48,15 +48,17 @@ vi.mock("electron", () => ({
}
}));
-// `log` reads RESOURCE_DIR / data-dir state at module-load time, which is not
-// available in the test process — stub it out so importing the provider
-// doesn't transitively initialise the server log subsystem.
-vi.mock("@triliumnext/server/src/services/log.js", () => ({
- default: {
- info: vi.fn(),
- error: vi.fn()
- }
-}));
+// `getLog()` throws when the log service hasn't been initialised via
+// `initializeCore` — and we don't want to spin up core in unit tests just to
+// satisfy a logger. Partial-mock core so `getLog` returns no-op stubs while
+// every other core export keeps its real implementation.
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn() })
+ };
+});
const { default: IpcMessagingProvider } = await import("./ipc_messaging_provider.js");
diff --git a/apps/desktop/src/ipc_messaging_provider.ts b/apps/desktop/src/ipc_messaging_provider.ts
index 8304262ca1..0325e23b1f 100644
--- a/apps/desktop/src/ipc_messaging_provider.ts
+++ b/apps/desktop/src/ipc_messaging_provider.ts
@@ -1,6 +1,5 @@
import type { WebSocketMessage } from "@triliumnext/commons";
-import type { ClientMessageHandler, MessagingProvider } from "@triliumnext/core";
-import log from "@triliumnext/server/src/services/log.js";
+import { getLog, type ClientMessageHandler, type MessagingProvider } from "@triliumnext/core";
import electron from "electron";
/**
@@ -38,7 +37,7 @@ export default class IpcMessagingProvider implements MessagingProvider {
try {
await this.clientMessageHandler(String(event.sender.id), parsed);
} catch (err) {
- log.error(`IPC messaging: handler threw: ${err}`);
+ getLog().error(`IPC messaging: handler threw: ${err}`);
}
}
});
@@ -52,7 +51,7 @@ export default class IpcMessagingProvider implements MessagingProvider {
// Match the WS provider's log-filtering so noisy sync-failed /
// api-log-messages traffic doesn't flood the log.
if (message.type !== "sync-failed" && message.type !== "api-log-messages") {
- log.info(`Sending message to all windows: ${JSON.stringify(message)}`);
+ getLog().info(`Sending message to all windows: ${JSON.stringify(message)}`);
}
for (const win of electron.BrowserWindow.getAllWindows()) {
@@ -91,7 +90,7 @@ function safeParse(message: string): unknown {
try {
return JSON.parse(message);
} catch (err) {
- log.error(`IPC messaging: discarding non-JSON renderer message: ${err}`);
+ getLog().error(`IPC messaging: discarding non-JSON renderer message: ${err}`);
return undefined;
}
}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 770ec7e53d..6ed338404d 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -1,4 +1,4 @@
-import { getLog, initializeCore, options, sql_init } from "@triliumnext/core";
+import { becca_loader, cls, entity_changes, getLog, initializeCore, options, sql_init, ws } from "@triliumnext/core";
import ServerBackupService from "@triliumnext/server/src/backup_provider.js";
import ClsHookedExecutionContext from "@triliumnext/server/src/cls_provider.js";
import { loadCoreSchema } from "@triliumnext/server/src/core_assets.js";
@@ -152,19 +152,13 @@ async function main() {
provider: dbProvider,
isReadOnly: config.General.readOnly,
async onTransactionCommit() {
- const ws = (await import("@triliumnext/server/src/services/ws.js")).default;
ws.sendTransactionEntityChangesToAllClients();
},
async onTransactionRollback() {
- const cls = (await import("@triliumnext/server/src/services/cls.js")).default;
- const becca_loader = (await import("@triliumnext/core")).becca_loader;
- const entity_changes = (await import("@triliumnext/server/src/services/entity_changes.js")).default;
- const log = (await import("@triliumnext/server/src/services/log")).default;
-
const entityChangeIds = cls.getAndClearEntityChangeIds();
if (entityChangeIds.length > 0) {
- log.info("Transaction rollback dirtied the becca, forcing reload.");
+ getLog().info("Transaction rollback dirtied the becca, forcing reload.");
becca_loader.load();
}
diff --git a/apps/desktop/src/services/custom_dictionary.spec.ts b/apps/desktop/src/services/custom_dictionary.spec.ts
index e048c9dcfb..8f318cd4c3 100644
--- a/apps/desktop/src/services/custom_dictionary.spec.ts
+++ b/apps/desktop/src/services/custom_dictionary.spec.ts
@@ -1,16 +1,21 @@
import { becca, becca_easy_mocking } from "@triliumnext/core";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import * as customDictionary from "./custom_dictionary.js";
-
const { buildNote } = becca_easy_mocking;
-vi.mock("@triliumnext/server/src/services/log.js", () => ({
- default: {
- info: vi.fn(),
- error: vi.fn()
- }
-}));
+// `getLog()` throws when the log service hasn't been initialised via
+// `initializeCore` — and we don't want to spin up core in unit tests just to
+// satisfy a logger. Partial-mock core so `getLog` returns no-op stubs while
+// every other core export keeps its real implementation.
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn() })
+ };
+});
+
+const customDictionary = await import("./custom_dictionary.js");
function mockSession(localWords: string[] = []) {
return {
diff --git a/apps/desktop/src/services/custom_dictionary.ts b/apps/desktop/src/services/custom_dictionary.ts
index 03d8401a6b..5f809f1c7a 100644
--- a/apps/desktop/src/services/custom_dictionary.ts
+++ b/apps/desktop/src/services/custom_dictionary.ts
@@ -1,5 +1,4 @@
-import { becca, cls, options as optionService, sql_init } from "@triliumnext/core";
-import log from "@triliumnext/server/src/services/log.js";
+import { becca, cls, getLog, options as optionService, sql_init } from "@triliumnext/core";
import electron, { type Session } from "electron";
const DICTIONARY_NOTE_ID = "_customDictionary";
@@ -33,7 +32,7 @@ function saveWords(words: Set<string>) {
cls.getContext().init(() => {
const note = becca.getNote(DICTIONARY_NOTE_ID);
if (!note) {
- log.error("Custom dictionary note not found.");
+ getLog().error("Custom dictionary note not found.");
return;
}
@@ -59,7 +58,7 @@ function clearFromLocalDictionary(session: Session, localWords: string[]) {
for (const word of localWords) {
session.removeWordFromSpellCheckerDictionary(word);
}
- log.info(`Cleared ${localWords.length} words from local spellchecker dictionary.`);
+ getLog().info(`Cleared ${localWords.length} words from local spellchecker dictionary.`);
}
/**
@@ -69,7 +68,7 @@ function clearFromLocalDictionary(session: Session, localWords: string[]) {
export async function loadForSession(session: Session) {
const note = becca.getNote(DICTIONARY_NOTE_ID);
if (!note) {
- log.error("Custom dictionary note not found.");
+ getLog().error("Custom dictionary note not found.");
return;
}
@@ -80,7 +79,7 @@ export async function loadForSession(session: Session) {
// One-time import: if the note is empty but there are local words, import them.
if (noteWords.size === 0 && localWords.length > 0) {
- log.info(`Importing ${localWords.length} words from local spellchecker dictionary.`);
+ getLog().info(`Importing ${localWords.length} words from local spellchecker dictionary.`);
merged = new Set(localWords);
saveWords(merged);
}
@@ -100,7 +99,7 @@ export async function loadForSession(session: Session) {
}
if (merged.size > 0) {
- log.info(`Loaded ${merged.size} custom dictionary words into spellchecker.`);
+ getLog().info(`Loaded ${merged.size} custom dictionary words into spellchecker.`);
}
}
@@ -122,7 +121,7 @@ export function setupCustomDictionary() {
if (loadedSessions.has(session)) return;
loadedSessions.add(session);
loadForSession(session).catch(err =>
- log.error(`Failed to load custom dictionary for spellcheck: ${err}`)
+ getLog().error(`Failed to load custom dictionary for spellcheck: ${err}`)
);
});
diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.ts
index 30d23ee5ba..0904637ea9 100644
--- a/apps/desktop/src/services/printing.ts
+++ b/apps/desktop/src/services/printing.ts
@@ -1,5 +1,4 @@
-import { utils as coreUtils } from "@triliumnext/core";
-import log from "@triliumnext/server/src/services/log.js";
+import { getLog, utils as coreUtils } from "@triliumnext/core";
import { default as electron, ipcMain, type IpcMainEvent } from "electron";
import fs from "fs/promises";
import { t } from "i18next";
@@ -125,10 +124,10 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac
browserWindow.webContents.on("console-message", (event, message, line, sourceId) => {
if (event.level === "debug") return;
if (event.level === "error") {
- log.error(`[Print Window ${sourceId}:${line}] ${message}`);
+ getLog().error(`[Print Window ${sourceId}:${line}] ${message}`);
return;
}
- log.info(`[Print Window ${sourceId}:${line}] ${message}`);
+ getLog().info(`[Print Window ${sourceId}:${line}] ${message}`);
});
try {
@@ -139,7 +138,7 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac
// print page would never render.
await browserWindow.loadURL(`trilium-app://app/?print#${notePath}`);
} catch (err) {
- log.error(`Failed to load print window: ${err}`);
+ getLog().error(`Failed to load print window: ${err}`);
ipcMain.off("print-progress", progressCallback);
throw err;
}
@@ -169,7 +168,7 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac
});
});
})();
- `).catch(err => log.error(`Failed to set up error handlers in print window: ${err}`));
+ `).catch(err => getLog().error(`Failed to set up error handlers in print window: ${err}`));
let printReport;
try {
@@ -193,7 +192,7 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac
});
`);
} catch (err) {
- log.error(`Print window promise failed for ${notePath}: ${err}`);
+ getLog().error(`Print window promise failed for ${notePath}: ${err}`);
ipcMain.off("print-progress", progressCallback);
throw err;
}
diff --git a/apps/desktop/src/services/shell.ts b/apps/desktop/src/services/shell.ts
index db7b7363bf..df1c694ce7 100644
--- a/apps/desktop/src/services/shell.ts
+++ b/apps/desktop/src/services/shell.ts
@@ -1,7 +1,6 @@
import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";
-import { utils as coreUtils } from "@triliumnext/core";
+import { getLog, utils as coreUtils } from "@triliumnext/core";
import dataDirs from "@triliumnext/server/src/services/data_dir.js";
-import log from "@triliumnext/server/src/services/log.js";
import { execFile } from "child_process";
import electron from "electron";
import fs from "fs";
@@ -237,7 +236,7 @@ export function setupShellHandlers() {
const validated = validateOpenExternalUrl(externalUrl);
electron.shell.openExternal(validated.toString());
} catch (e) {
- log.error(`open-external failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ getLog().error(`open-external failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
}
});
@@ -246,7 +245,7 @@ export function setupShellHandlers() {
const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR);
return electron.shell.openPath(resolved);
} catch (e) {
- log.error(`open-path failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ getLog().error(`open-path failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
return coreUtils.safeExtractMessageAndStackFromError(e);
}
});
@@ -256,7 +255,7 @@ export function setupShellHandlers() {
const filePath = validateOpenFileUrl(fileUrl);
return electron.shell.openPath(filePath);
} catch (e) {
- log.error(`open-file-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ getLog().error(`open-file-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
return coreUtils.safeExtractMessageAndStackFromError(e);
}
});
@@ -266,7 +265,7 @@ export function setupShellHandlers() {
const validated = validateDownloadUrl(downloadUrl, event.sender.getURL());
event.sender.downloadURL(validated.toString());
} catch (e) {
- log.error(`download-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ getLog().error(`download-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
}
});
@@ -289,14 +288,14 @@ export function setupShellHandlers() {
const tryTerminal = (index: number) => {
if (index >= terminals.length) {
- log.error("open-custom: no terminal emulator found");
+ getLog().error("open-custom: no terminal emulator found");
electron.shell.openPath(resolved);
return;
}
const terminal = terminals[index];
execFile(terminal, ["-e", innerCommand], (err) => {
if (err) {
- log.info(`open-custom: ${terminal} failed: ${err.message}`);
+ getLog().info(`open-custom: ${terminal} failed: ${err.message}`);
tryTerminal(index + 1);
}
});
@@ -312,7 +311,7 @@ export function setupShellHandlers() {
// (so it cannot contain quotes or other rundll32-confusing characters).
execFile("rundll32.exe", ["shell32.dll,OpenAs_RunDLL", winPath], { windowsVerbatimArguments: true }, (err) => {
if (err) {
- log.error(`open-custom: rundll32 failed: ${err.message}`);
+ getLog().error(`open-custom: rundll32 failed: ${err.message}`);
electron.shell.openPath(resolved);
}
});
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 771651f735..df5c3a39c1 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -1,5 +1,4 @@
-import { app_info, cls, events, keyboard_actions as keyboardActionsService, options as optionService, sql_init, utils as coreUtils } from "@triliumnext/core";
-import log from "@triliumnext/server/src/services/log.js";
+import { app_info, cls, events, getLog, keyboard_actions as keyboardActionsService, options as optionService, sql_init, utils as coreUtils } from "@triliumnext/core";
import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";
import path from "path";
@@ -312,9 +311,9 @@ async function registerGlobalShortcuts() {
);
if (result) {
- log.info(`Registered global shortcut ${translatedShortcut} for action ${action.actionName}`);
+ getLog().info(`Registered global shortcut ${translatedShortcut} for action ${action.actionName}`);
} else {
- log.info(`Could not register global shortcut ${translatedShortcut}`);
+ getLog().info(`Could not register global shortcut ${translatedShortcut}`);
}
}
}
@@ -505,7 +504,7 @@ export function setupWindowing() {
await createMainWindow();
closeSetupWindow();
} catch (err) {
- log.error(`Failed to swap setup window for main window: ${err}`);
+ getLog().error(`Failed to swap setup window for main window: ${err}`);
}
});
}