import type { ExecutionOptions, ExecutionResult, MathJSLabRuntime, RuntimeSession } from 'mathjslab/runtime'; /** Serialize commands into one workspace; the remote runtime recovers its Worker after timeout. */ export class CalculatorSession { private session: Promise | undefined; private queue: Promise = Promise.resolve(); private disposed = false; public constructor(private readonly runtime: MathJSLabRuntime) {} public execute(source: string, options: ExecutionOptions = {}): Promise { const operation = this.queue.then(async () => { if (this.disposed) throw new Error('Calculator session is disposed.'); this.session ??= this.runtime.createSession({ parfor: 'fallback' }).catch((error: unknown) => { this.session = undefined; throw error; }); const session = await this.session; return session.execute(source, { timeoutMs: 15000, ...options }); }); this.queue = operation.catch(() => undefined); return operation; } public async dispose(): Promise { if (this.disposed) return; this.disposed = true; await this.runtime.dispose(); } }