()
| 21 | let cachedBridge: VscodeBridge | null = null; |
| 22 | |
| 23 | export function getVscodeBridge(): VscodeBridge { |
| 24 | if (cachedBridge) { |
| 25 | return cachedBridge; |
| 26 | } |
| 27 | |
| 28 | const traceId = |
| 29 | (document.body && document.body.dataset && document.body.dataset.muxTraceId) || "unknown"; |
| 30 | |
| 31 | let vscode: { postMessage: (data: unknown) => void }; |
| 32 | try { |
| 33 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 34 | // @ts-ignore VS Code injects this in the webview |
| 35 | vscode = acquireVsCodeApi(); |
| 36 | } catch (error) { |
| 37 | throw new Error(`mux webview: acquireVsCodeApi failed: ${String(error)}`); |
| 38 | } |
| 39 | |
| 40 | const startedAtMs = Date.now(); |
| 41 | let nextSeq = 1; |
| 42 | |
| 43 | const listeners = new Set<(data: unknown) => void>(); |
| 44 | |
| 45 | const onMessage = (handler: (data: unknown) => void): (() => void) => { |
| 46 | listeners.add(handler); |
| 47 | return () => { |
| 48 | listeners.delete(handler); |
| 49 | }; |
| 50 | }; |
| 51 | |
| 52 | window.addEventListener("message", (event: MessageEvent) => { |
| 53 | for (const handler of listeners) { |
| 54 | try { |
| 55 | handler(event.data); |
| 56 | } catch (error) { |
| 57 | // eslint-disable-next-line no-console |
| 58 | console.error("mux webview: message handler crashed", error); |
| 59 | } |
| 60 | } |
| 61 | }); |
| 62 | |
| 63 | const postMessage = (payload: WebviewToExtensionMessage): void => { |
| 64 | assert(payload && typeof payload === "object" && "type" in payload, "postMessage requires a payload with type"); |
| 65 | |
| 66 | const meta = { |
| 67 | traceId, |
| 68 | seq: nextSeq++, |
| 69 | sentAtMs: Date.now(), |
| 70 | sinceStartMs: Date.now() - startedAtMs, |
| 71 | }; |
| 72 | |
| 73 | const envelope: Record<string, unknown> = { __muxMeta: meta, ...payload }; |
| 74 | vscode.postMessage(envelope); |
| 75 | }; |
| 76 | |
| 77 | const debugLog = (message: string, data?: unknown): void => { |
| 78 | // Mirror to DevTools console. |
| 79 | // eslint-disable-next-line no-console |
| 80 | console.log(`[mux-webview ${traceId}] ${message}`, data); |
no test coverage detected