chore(standalone): use a simpler CLS mechanism considering lack of multi-threading

This commit is contained in:
Elian Doran 2026-02-09 18:16:15 +02:00
parent 223d69206c
commit 49ce312ab2
No known key found for this signature in database

View File

@ -1,46 +1,32 @@
import { ExecutionContext } from "@triliumnext/core";
/**
* Browser execution context implementation.
*
* Unlike the server (which uses cls-hooked for per-request isolation),
* the browser is single-threaded with a single user and doesn't need
* request-level isolation. We maintain a single persistent context
* throughout the page lifetime.
*/
export default class BrowserExecutionContext implements ExecutionContext {
private store: Map<string, any> | null = null;
private store: Map<string, any> = new Map();
get<T = any>(key: string): T | undefined {
return this.store?.get(key);
get<T = any>(key: string): T {
return this.store.get(key);
}
set(key: string, value: any): void {
if (!this.store) {
throw new Error("ExecutionContext not initialized");
}
this.store.set(key, value);
}
reset(): void {
this.store = null;
this.store.clear();
}
init<T>(callback: () => T): T {
// Create a fresh context for this request
const prev = this.store;
this.store = new Map();
try {
const result = callback();
// If the result is a Promise, we need to handle cleanup after it resolves
if (result && typeof result === 'object' && 'then' in result && 'catch' in result) {
const promise = result as unknown as Promise<any>;
return promise.finally(() => {
this.store = prev;
}) as T;
} else {
// Synchronous result, clean up immediately
this.store = prev;
return result;
}
} catch (error) {
// Always clean up on error (for synchronous errors)
this.store = prev;
throw error;
}
// In browser, we don't need per-request isolation.
// Just execute the callback with the persistent context.
// This allows fire-and-forget operations to access context.
return callback();
}
}