UNPKG

histoire

Version:

A fast story book powered by Vite

66 lines (65 loc) • 2.2 kB
const observers = new WeakMap(); const listeners = new WeakMap(); /** Runtime bridge notifications cannot interrupt generation ownership changes. */ function announce(context, observer) { for (const listener of listeners.get(context) ?? []) { try { listener(observer); } catch { /* Channel failures cannot alter runtime lifecycle. */ } } } /** Bind observation to one context without keeping retired runtime contexts alive. */ export function attachMcpObserver(context, observer) { observers.set(context, observer); announce(context, observer); return () => { if (observers.get(context) === observer) { observers.delete(context); announce(context); } }; } /** Read only the observer owned by this exact dev runtime context. */ export function getMcpObserver(context) { return observers.get(context); } /** Observe late MCP startup on a channel whose Vite server already exists. */ export function onMcpObserverChange(context, listener) { let subscribers = listeners.get(context); if (!subscribers) listeners.set(context, subscribers = new Set()); subscribers.add(listener); return () => { subscribers.delete(listener); if (!subscribers.size && listeners.get(context) === subscribers) listeners.delete(context); }; } /** Share exact current-context attachment across dev HTTP and stdio runtimes. */ export function bindMcpObserver(controller, observer, reset) { let context; let detach; let closed = false; /** Retire old attachment before publishing a fresh generation snapshot. */ function synchronize() { const handle = controller.current; const next = handle?.isActive() ? handle.context : undefined; if (next === context) return; detach?.(); context = next; reset(); detach = next ? attachMcpObserver(next, observer) : undefined; } const off = controller.subscribe(synchronize); synchronize(); return () => { if (closed) return; closed = true; off(); detach?.(); reset(); }; }