Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): lightweight router implementation

Elian Doran8274f9a220fb
diff --git a/apps/client/src/lightweight/browser_router.ts b/apps/client/src/lightweight/browser_router.ts
new file mode 100644
index 0000000000..68f3c48606
--- /dev/null
+++ b/apps/client/src/lightweight/browser_router.ts
@@ -0,0 +1,230 @@
+/**
+ * Browser-compatible router that mimics Express routing patterns.
+ * Supports path parameters (e.g., /api/notes/:noteId) and query strings.
+ */
+
+export interface BrowserRequest {
+ method: string;
+ url: string;
+ path: string;
+ params: Record<string, string>;
+ query: Record<string, string | undefined>;
+ body?: unknown;
+}
+
+export interface BrowserResponse {
+ status: number;
+ headers: Record<string, string>;
+ body: ArrayBuffer;
+}
+
+export type RouteHandler = (req: BrowserRequest) => unknown | Promise<unknown>;
+
+interface Route {
+ method: string;
+ pattern: RegExp;
+ paramNames: string[];
+ handler: RouteHandler;
+}
+
+const encoder = new TextEncoder();
+
+/**
+ * Convert an Express-style path pattern to a RegExp.
+ * Supports :param syntax for path parameters.
+ *
+ * Examples:
+ * /api/notes/:noteId -> /^\/api\/notes\/([^\/]+)$/
+ * /api/notes/:noteId/revisions -> /^\/api\/notes\/([^\/]+)\/revisions$/
+ */
+function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {
+ const paramNames: string[] = [];
+
+ // Escape special regex characters except for :param patterns
+ const regexPattern = path
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape special chars
+ .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName) => {
+ paramNames.push(paramName);
+ return '([^/]+)';
+ });
+
+ return {
+ pattern: new RegExp(`^${regexPattern}$`),
+ paramNames
+ };
+}
+
+/**
+ * Parse query string into an object.
+ */
+function parseQuery(search: string): Record<string, string | undefined> {
+ const query: Record<string, string | undefined> = {};
+ if (!search || search === '?') return query;
+
+ const params = new URLSearchParams(search);
+ for (const [key, value] of params) {
+ query[key] = value;
+ }
+ return query;
+}
+
+/**
+ * Convert a result to a JSON response.
+ */
+function jsonResponse(obj: unknown, status = 200, extraHeaders: Record<string, string> = {}): BrowserResponse {
+ const body = encoder.encode(JSON.stringify(obj)).buffer as ArrayBuffer;
+ return {
+ status,
+ headers: { "content-type": "application/json; charset=utf-8", ...extraHeaders },
+ body
+ };
+}
+
+/**
+ * Convert a string to a text response.
+ */
+function textResponse(text: string, status = 200, extraHeaders: Record<string, string> = {}): BrowserResponse {
+ const body = encoder.encode(text).buffer as ArrayBuffer;
+ return {
+ status,
+ headers: { "content-type": "text/plain; charset=utf-8", ...extraHeaders },
+ body
+ };
+}
+
+/**
+ * Browser router class that handles route registration and dispatching.
+ */
+export class BrowserRouter {
+ private routes: Route[] = [];
+
+ /**
+ * Register a route handler.
+ */
+ register(method: string, path: string, handler: RouteHandler): void {
+ const { pattern, paramNames } = pathToRegex(path);
+ this.routes.push({
+ method: method.toUpperCase(),
+ pattern,
+ paramNames,
+ handler
+ });
+ }
+
+ /**
+ * Convenience methods for common HTTP methods.
+ */
+ get(path: string, handler: RouteHandler): void {
+ this.register('GET', path, handler);
+ }
+
+ post(path: string, handler: RouteHandler): void {
+ this.register('POST', path, handler);
+ }
+
+ put(path: string, handler: RouteHandler): void {
+ this.register('PUT', path, handler);
+ }
+
+ patch(path: string, handler: RouteHandler): void {
+ this.register('PATCH', path, handler);
+ }
+
+ delete(path: string, handler: RouteHandler): void {
+ this.register('DELETE', path, handler);
+ }
+
+ /**
+ * Dispatch a request to the appropriate handler.
+ */
+ async dispatch(method: string, urlString: string, body?: unknown): Promise<BrowserResponse> {
+ const url = new URL(urlString);
+ const path = url.pathname;
+ const query = parseQuery(url.search);
+ const upperMethod = method.toUpperCase();
+
+ // Find matching route
+ for (const route of this.routes) {
+ if (route.method !== upperMethod) continue;
+
+ const match = path.match(route.pattern);
+ if (!match) continue;
+
+ // Extract path parameters
+ const params: Record<string, string> = {};
+ for (let i = 0; i < route.paramNames.length; i++) {
+ params[route.paramNames[i]] = decodeURIComponent(match[i + 1]);
+ }
+
+ const request: BrowserRequest = {
+ method: upperMethod,
+ url: urlString,
+ path,
+ params,
+ query,
+ body
+ };
+
+ try {
+ const result = await route.handler(request);
+ return this.formatResult(result);
+ } catch (error) {
+ return this.formatError(error);
+ }
+ }
+
+ // No route matched
+ return textResponse(`Not found: ${method} ${path}`, 404);
+ }
+
+ /**
+ * Format a handler result into a response.
+ * Follows the same patterns as the server's apiResultHandler.
+ */
+ private formatResult(result: unknown): BrowserResponse {
+ // Handle [statusCode, response] format
+ if (Array.isArray(result) && result.length > 0 && Number.isInteger(result[0])) {
+ const [statusCode, response] = result;
+ return jsonResponse(response, statusCode);
+ }
+
+ // Handle undefined (no content)
+ if (result === undefined) {
+ return jsonResponse('', 204);
+ }
+
+ // Default: JSON response with 200
+ return jsonResponse(result, 200);
+ }
+
+ /**
+ * Format an error into a response.
+ */
+ private formatError(error: unknown): BrowserResponse {
+ console.error('[Router] Handler error:', error);
+
+ // Check for known error types
+ if (error && typeof error === 'object') {
+ const err = error as { constructor?: { name?: string }; message?: string };
+
+ if (err.constructor?.name === 'NotFoundError') {
+ return jsonResponse({ message: err.message || 'Not found' }, 404);
+ }
+
+ if (err.constructor?.name === 'ValidationError') {
+ return jsonResponse({ message: err.message || 'Validation error' }, 400);
+ }
+ }
+
+ // Generic error
+ const message = error instanceof Error ? error.message : String(error);
+ return jsonResponse({ message }, 500);
+ }
+}
+
+/**
+ * Create a new router instance.
+ */
+export function createRouter(): BrowserRouter {
+ return new BrowserRouter();
+}
diff --git a/apps/client/src/lightweight/browser_routes.ts b/apps/client/src/lightweight/browser_routes.ts
new file mode 100644
index 0000000000..29c326c0eb
--- /dev/null
+++ b/apps/client/src/lightweight/browser_routes.ts
@@ -0,0 +1,80 @@
+/**
+ * Browser route definitions.
+ * This mirrors the server's routes.ts but for the browser worker.
+ */
+
+import type { routes as coreRoutes } from '@triliumnext/core';
+import { BrowserRouter, type BrowserRequest } from './browser_router';
+
+type CoreRoutes = typeof coreRoutes;
+
+/**
+ * Register all API routes on the browser router.
+ *
+ * @param router - The browser router instance
+ * @param routes - The core routes module from @triliumnext/core
+ */
+export function registerRoutes(router: BrowserRouter, routes: CoreRoutes): void {
+ const { optionsApiRoute, treeApiRoute, keysApiRoute } = routes;
+
+ // Tree routes
+ router.get('/api/tree', (req) =>
+ treeApiRoute.getTree({
+ query: {
+ subTreeNoteId: req.query.subTreeNoteId
+ }
+ } as any)
+ );
+
+ router.post('/api/tree/load', (req) =>
+ treeApiRoute.load({
+ body: req.body
+ } as any)
+ );
+
+ // Options routes
+ router.get('/api/options', () =>
+ optionsApiRoute.getOptions()
+ );
+
+ router.put('/api/options/:name/:value', (req) =>
+ optionsApiRoute.updateOption({
+ params: req.params
+ } as any)
+ );
+
+ router.put('/api/options', (req) =>
+ optionsApiRoute.updateOptions({
+ body: req.body
+ } as any)
+ );
+
+ router.get('/api/options/user-themes', () =>
+ optionsApiRoute.getUserThemes()
+ );
+
+ router.get('/api/options/locales', () =>
+ optionsApiRoute.getSupportedLocales()
+ );
+
+ // Keyboard actions routes
+ router.get('/api/keyboard-actions', () =>
+ keysApiRoute.getKeyboardActions()
+ );
+
+ router.get('/api/keyboard-shortcuts-for-notes', () =>
+ keysApiRoute.getShortcutsForNotes()
+ );
+
+ // Add more routes here as they are implemented in @triliumnext/core
+ // Follow the pattern from apps/server/src/routes/routes.ts
+}
+
+/**
+ * Create and configure a router with all routes registered.
+ */
+export function createConfiguredRouter(routes: CoreRoutes): BrowserRouter {
+ const router = new BrowserRouter();
+ registerRoutes(router, routes);
+ return router;
+}
diff --git a/apps/client/src/local-server-worker.ts b/apps/client/src/local-server-worker.ts
index 4072305ee2..f808524e8a 100644
--- a/apps/client/src/local-server-worker.ts
+++ b/apps/client/src/local-server-worker.ts
@@ -5,6 +5,8 @@
import BrowserExecutionContext from './lightweight/cls_provider';
import BrowserCryptoProvider from './lightweight/crypto_provider';
import BrowserSqlProvider from './lightweight/sql_provider';
+import { BrowserRouter } from './lightweight/browser_router';
+import { createConfiguredRouter } from './lightweight/browser_routes';
// Global error handlers - MUST be set up before any async imports
self.onerror = (message, source, lineno, colno, error) => {
@@ -48,8 +50,9 @@ console.log("[Worker] Error handlers installed");
// Shared SQL provider instance
const sqlProvider = new BrowserSqlProvider();
-// Core module and initialization state
+// Core module, router, and initialization state
let coreModule: typeof import("@triliumnext/core") | null = null;
+let router: BrowserRouter | null = null;
let initPromise: Promise<void> | null = null;
let initError: Error | null = null;
@@ -91,6 +94,10 @@ async function initialize(): Promise<void> {
console.log("[Worker] Supported routes", Object.keys(coreModule.routes));
+ // Create and configure the router
+ router = createConfiguredRouter(coreModule.routes);
+ console.log("[Worker] Router configured");
+
console.log("[Worker] Initializing becca...");
await coreModule.becca_loader.beccaLoaded;
@@ -107,14 +114,14 @@ async function initialize(): Promise<void> {
/**
* Ensure the worker is initialized before processing requests.
- * Returns the core module if initialization was successful.
+ * Returns the router if initialization was successful.
*/
async function ensureInitialized() {
await initialize();
- if (!coreModule) {
- throw new Error("Core module not loaded");
+ if (!router) {
+ throw new Error("Router not initialized");
}
- return coreModule;
+ return router;
}
const encoder = new TextEncoder();
@@ -128,15 +135,6 @@ function jsonResponse(obj: unknown, status = 200, extraHeaders = {}) {
};
}
-function textResponse(text: string, status = 200, extraHeaders = {}) {
- const body = encoder.encode(text).buffer;
- return {
- status,
- headers: { "content-type": "text/plain; charset=utf-8", ...extraHeaders },
- body
- };
-}
-
// Example: your /bootstrap handler placeholder
async function handleBootstrap() {
console.log("[Worker] Bootstrap request received");
@@ -194,6 +192,7 @@ async function handleBootstrap() {
interface LocalRequest {
method: string;
url: string;
+ body?: unknown;
}
// Main dispatch
@@ -201,39 +200,17 @@ async function dispatch(request: LocalRequest) {
const url = new URL(request.url);
console.log("[Worker] Dispatch:", url.pathname);
- // NOTE: your core router will do this later.
+
+ // Bootstrap is handled specially before the router is ready
if (request.method === "GET" && url.pathname === "/bootstrap") {
return handleBootstrap();
}
- // Ensure initialization is complete before accessing routes
- const core = await ensureInitialized();
-
- if (request.method === "GET" && url.pathname === "/api/options") {
- return jsonResponse(core.routes.optionsApiRoute.getOptions());
- }
-
- if (request.method === "GET" && url.pathname === "/api/tree") {
- return jsonResponse(core.routes.treeApiRoute.getTree({
- query: {
- subTreeNoteId: url.searchParams.get("subTreeNoteId") || undefined
- }
- }));
- }
-
- if (request.method === "GET" && url.pathname === "/api/keyboard-actions") {
- return jsonResponse(core.routes.keysApiRoute.getKeyboardActions());
- }
-
- if (request.method === "GET" && url.pathname === "/api/keyboard-shortcuts-for-notes") {
- return jsonResponse(core.routes.keysApiRoute.getShortcutsForNotes());
- }
-
- if (url.pathname.startsWith("/api/echo")) {
- return jsonResponse({ ok: true, method: request.method, url: request.url });
- }
+ // Ensure initialization is complete and get the router
+ const appRouter = await ensureInitialized();
- return textResponse("Not found", 404);
+ // Dispatch to the router
+ return appRouter.dispatch(request.method, request.url, request.body);
}
// Start initialization immediately when the worker loads