Skip to content

Build your personal knowledge base with Trilium Notes

perf(server): bundle to ESM with code splitting

Elian Doran489242857452
diff --git a/CLAUDE.md b/CLAUDE.md
index 65af2331aa..e6dbb09c81 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -236,7 +236,7 @@ The `_hidden` subtree holds system notes with deterministic `_`-prefixed IDs so
Tools are `defineTools({...})` registries in `packages/trilium-core/src/services/llm/tools/` (`note_tools`, `attribute_tools`, `attachment_tools`, `hierarchy_tools`, …), served to both the LLM chat and the MCP server. Each tool: `description`, Zod `inputSchema`, `execute`, `mutates: true` for writes. A new module goes into `allToolRegistries` in `tools/index.ts`; Node-only tools (in-app docs) live in `apps/server/src/services/llm/tools/` and register via `registerToolRegistryLoader()` (a lazy dynamic-import loader — see `registerServerLlmExtensions` in `apps/server/src/services/llm/index.ts`) so the tool stack stays out of the startup path. Add the client label under `llm.tools.<tool_name>` in imperative tense ("Search notes"). Mirror ETAPI's field choices but **don't import ETAPI mappers** — inline them so the LLM layer stays decoupled.
### Server-Side Static Assets
-Node-side assets (templates, translations, prompts) live in `apps/server/src/assets/` and are read via `RESOURCE_DIR` from `apps/server/src/services/resource_dir.ts` (`path.join(RESOURCE_DIR, "llm", "prompts", …)`); assets core itself reads (`schema.sql`, LLM skills) live in `packages/trilium-core/src/assets/`. **Never resolve paths with `import.meta.url`/`fileURLToPath` or `__dirname` + relative path** — the server is bundled to CJS and both point at the bundle, not the source tree.
+Node-side assets (templates, translations, prompts) live in `apps/server/src/assets/` and are read via `RESOURCE_DIR` from `apps/server/src/services/resource_dir.ts` (`path.join(RESOURCE_DIR, "llm", "prompts", …)`); assets core itself reads (`schema.sql`, LLM skills) live in `packages/trilium-core/src/assets/`. **Never resolve paths with `import.meta.url`/`fileURLToPath` or `__dirname` + relative path** — the server bundles to `dist/main.mjs` plus lazy `chunks/`, so both point at the bundle (or at whichever chunk the module landed in), not the source tree.
## MCP Server
diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.ts
index bee11fb536..9cfd182dd6 100644
--- a/apps/desktop/src/services/printing.ts
+++ b/apps/desktop/src/services/printing.ts
@@ -6,7 +6,7 @@ import path from "path";
import { TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";
-// Preload bundle path — built next to main.cjs in production by
+// Preload bundle path — built next to main.mjs in production by
// apps/desktop/scripts/build.ts, or compiled in-place by the dev runner
// (scripts/electron-start.mts) into apps/desktop/src/preload.compiled.cjs.
// Print windows share the same preload as the main window so the renderer
@@ -19,7 +19,7 @@ let preloadScriptCache: string | undefined;
function getPreloadScript(): string {
if (preloadScriptCache === undefined) {
// Dev: this file lives one directory below the preload bundle.
- // Prod: this file is bundled into dist/main.cjs alongside preload.cjs
+ // Prod: this file is bundled into dist/main.mjs alongside preload.cjs
// (no `..` — keep this synced with apps/desktop/src/services/window.ts).
/* v8 ignore next 5 -- prod preload arm is cache-once (only the first ternary evaluation counts); covered by the production build, not unit tests */
preloadScriptCache = path.resolve(
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 9e52a6a393..6756e7c198 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -13,7 +13,7 @@ import { setupWebContentsSecurity } from "./web_contents_security.js";
// - Dev: this file lives at apps/desktop/src/services/window.ts, and the
// preload bundle is one level up at apps/desktop/src/preload.compiled.cjs
// (built in place by scripts/electron-start.mts).
-// - Prod: this file is bundled into apps/desktop/dist/main.cjs, with
+// - Prod: this file is bundled into apps/desktop/dist/main.mjs, with
// preload.cjs sitting next to it in dist/ (NOT one level up — getting
// this wrong leaves the renderer without `window.electronApi`).
//
diff --git a/apps/server/e2e/sync/sync-instance.ts b/apps/server/e2e/sync/sync-instance.ts
index bf0cf73ea1..bac428f791 100644
--- a/apps/server/e2e/sync/sync-instance.ts
+++ b/apps/server/e2e/sync/sync-instance.ts
@@ -2,7 +2,7 @@ import { type ChildProcess, spawn } from "child_process";
import { join } from "path";
/**
- * A real Trilium server instance (the production `dist/main.cjs` bundle, same as the e2e
+ * A real Trilium server instance (the production `dist/main.mjs` bundle, same as the e2e
* webServer) spawned against its own data directory, plus the HTTP plumbing needed to drive
* the sync protocol end-to-end: document setup, password, ETAPI seeding, sync-from-server and
* completion polling.
@@ -27,7 +27,7 @@ export default class SyncInstance {
async start() {
const serverDir = join(__dirname, "..", "..");
- this.child = spawn(process.execPath, ["dist/main.cjs"], {
+ this.child = spawn(process.execPath, ["dist/main.mjs"], {
cwd: serverDir,
env: {
...process.env,
diff --git a/apps/server/e2e/sync/sync.spec.ts b/apps/server/e2e/sync/sync.spec.ts
index 2add974ea5..098623fac5 100644
--- a/apps/server/e2e/sync/sync.spec.ts
+++ b/apps/server/e2e/sync/sync.spec.ts
@@ -21,11 +21,11 @@ const PASSWORD = "sync-e2e-password";
test.describe("sync protocol", () => {
// This spec spawns its own local server instances from the production bundle, so it only
- // needs `dist/main.cjs` to exist — which every CI e2e job guarantees (they all build the
+ // needs `dist/main.mjs` to exist — which every CI e2e job guarantees (they all build the
// server first), regardless of whether the *main* e2e target is local or Docker-hosted.
test.skip(
- !existsSync(join(__dirname, "..", "..", "dist", "main.cjs")),
- "requires the built server bundle (dist/main.cjs)"
+ !existsSync(join(__dirname, "..", "..", "dist", "main.mjs")),
+ "requires the built server bundle (dist/main.mjs)"
);
test("initial sync reproduces the source; incremental sync works both ways", async ({}, testInfo) => {
diff --git a/apps/server/package.json b/apps/server/package.json
index 3e110ed118..7950ff3120 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -16,7 +16,7 @@
"coverage": "vitest --coverage",
"test-build": "vitest --config vitest.build.config.mts",
"start-prod": "cross-env TRILIUM_DATA_DIR=data pnpm start-prod-no-dir",
- "start-prod-no-dir": "pnpm build && cross-env TRILIUM_ENV=production TRILIUM_PORT=8082 node dist/main.cjs",
+ "start-prod-no-dir": "pnpm build && cross-env TRILIUM_ENV=production TRILIUM_PORT=8082 node dist/main.mjs",
"e2e": "playwright test",
"circular-deps": "dpdm -T src/**/*.ts --tree=false --warning=false --skip-dynamic-imports=circular",
"docker-build-debian": "pnpm build && docker build . -t triliumnext-debian -f Dockerfile",
diff --git a/apps/server/rootless-entrypoint.sh b/apps/server/rootless-entrypoint.sh
index 4056df2a29..6e2c071a8a 100755
--- a/apps/server/rootless-entrypoint.sh
+++ b/apps/server/rootless-entrypoint.sh
@@ -25,4 +25,4 @@ fi
mkdir -p "${TRILIUM_DATA_DIR}"
# Start the app
-exec node ./main.cjs
+exec node ./main.mjs
diff --git a/apps/server/scripts/build-server.sh b/apps/server/scripts/build-server.sh
index c140e18d1a..39267e5372 100644
--- a/apps/server/scripts/build-server.sh
+++ b/apps/server/scripts/build-server.sh
@@ -43,7 +43,7 @@ rm -rf $BUILD_DIR/node/lib/node_modules/{npm,corepack} \
$BUILD_DIR/node_modules/electron* \
$BUILD_DIR/electron*.{js,map}
-printf "#!/bin/sh\nexec ./node/bin/node main.cjs\n" > $BUILD_DIR/trilium.sh
+printf "#!/bin/sh\nexec ./node/bin/node main.mjs\n" > $BUILD_DIR/trilium.sh
chmod 755 $BUILD_DIR/trilium.sh
VERSION=`jq -r ".version" package.json`
diff --git a/apps/server/scripts/build.ts b/apps/server/scripts/build.ts
index bc97f2428e..17d2bae316 100644
--- a/apps/server/scripts/build.ts
+++ b/apps/server/scripts/build.ts
@@ -3,7 +3,9 @@ import BuildHelper from "../../../scripts/build-utils";
const build = new BuildHelper("apps/server");
async function main() {
- await build.buildBackend([ "src/main.ts" ]);
+ // ESM so dynamic-import boundaries split into chunks/ that only load on first use; the
+ // image worker below is spawned by its .cjs path and stays CJS.
+ await build.buildBackend([ "src/main.ts" ], { format: "esm" });
// Its own call so it lands beside the bundle rather than under a `services/` path: the pool
// looks for it next to whatever is running, and desktop builds it the same way.
await build.buildBackend([ "src/services/image_worker.ts" ]);
@@ -13,7 +15,7 @@ async function main() {
// The healthcheck docker runs; the Dockerfiles point at it inside the image.
build.copy("docker_healthcheck.sh", "docker_healthcheck.sh");
// schema.sql lives in trilium-core but is loaded at server startup. The
- // bundled main.cjs can't `require.resolve("@triliumnext/core/...")` in
+ // bundled main.mjs can't `require.resolve("@triliumnext/core/...")` in
// Docker (no workspace symlinks in the image), so we copy the file
// alongside the server's own assets and read it via RESOURCE_DIR at
// runtime. See main.ts.
diff --git a/apps/server/src/services/process_errors.ts b/apps/server/src/services/process_errors.ts
index e05c80c479..aa9884fe70 100644
--- a/apps/server/src/services/process_errors.ts
+++ b/apps/server/src/services/process_errors.ts
@@ -41,7 +41,7 @@ let appReady = false;
* Deferred work — a `setTimeout` callback, a floating promise — has no request to fail and no caller to
* catch it, so without this a single throw from a background task takes the whole application down: the
* server process dies, and Electron replaces the desktop app with a modal stack trace against minified
- * `main.cjs` offsets (see #10823). That is a wildly disproportionate outcome for work whose failure is
+ * `main.mjs` offsets (see #10823). That is a wildly disproportionate outcome for work whose failure is
* usually inconsequential, and it costs the user whatever unsaved state they had.
*
* Crashing therefore has to be a decision rather than the default, which is what {@link markAppReady}
diff --git a/apps/server/start-docker.sh b/apps/server/start-docker.sh
index 0de1628859..8d38923c1c 100644
--- a/apps/server/start-docker.sh
+++ b/apps/server/start-docker.sh
@@ -4,4 +4,4 @@
[ ! -z "${USER_GID}" ] && groupmod -og ${USER_GID} node || echo "No USER_GID specified, leaving 1000"
chown -R node:node /home/node
-exec su -c "node ./main.cjs" node
\ No newline at end of file
+exec su -c "node ./main.mjs" node
\ No newline at end of file
diff --git a/flake.nix b/flake.nix
index f553176ee4..83a9269945 100644
--- a/flake.nix
+++ b/flake.nix
@@ -293,7 +293,7 @@ nodejs.python
--add-flags "\''${NIXOS_OZONE_WL:+\''${WAYLAND_DISPLAY:+--ozone-platform-hint=auto --enable-features=WaylandWindowDecorations --enable-wayland-ime=true}}" \
--set-default ELECTRON_IS_DEV 0 \
--set TRILIUM_RESOURCE_DIR $out/opt/trilium \
- --add-flags $out/opt/trilium/main.cjs
+ --add-flags $out/opt/trilium/main.mjs
'';
};
@@ -319,7 +319,7 @@ nodejs.python
mkdir -p $out/{bin,opt/trilium-server}
cp --archive apps/server/dist/* $out/opt/trilium-server
makeWrapper ${lib.getExe nodejs} $out/bin/trilium-server \
- --add-flags $out/opt/trilium-server/main.cjs
+ --add-flags $out/opt/trilium-server/main.mjs
'';
};