| 7 | if (typeof window === 'undefined') return () => {}; |
| 8 | |
| 9 | const handler = (event) => { |
| 10 | const msg = event?.data; |
| 11 | if (!msg || msg.source !== 'dogalog-ai-bridge') return; |
| 12 | const { action, payload, id } = msg; |
| 13 | |
| 14 | if (action === 'setCode') { |
| 15 | setCode?.(typeof payload === 'string' ? payload : ''); |
| 16 | return; |
| 17 | } |
| 18 | |
| 19 | if (action === 'runQuery') { |
| 20 | runQuery?.(typeof payload === 'string' ? payload : ''); |
| 21 | return; |
| 22 | } |
| 23 | |
| 24 | if (action === 'getCode') { |
| 25 | const code = typeof getCode === 'function' ? getCode() : ''; |
| 26 | try { |
| 27 | event.source?.postMessage?.({ |
| 28 | source: 'dogalog-ai-bridge', |
| 29 | id, |
| 30 | action: 'code', |
| 31 | payload: code |
| 32 | }, event.origin || '*'); |
| 33 | } catch (err) { |
| 34 | // Swallow errors to keep bridge optional and non-breaking. |
| 35 | } |
| 36 | } |
| 37 | }; |
| 38 | |
| 39 | window.addEventListener('message', handler); |
| 40 | return () => window.removeEventListener('message', handler); |