// The bridge, as the page sees it. Sandboxed and context-isolated: the page // gets `window.mollusc` with exactly the calls listed in mollusc.json's `api`, // grouped by namespace (`mollusc.fs.read`), plus `on` for events, `openWindow`, // `pathForFile` for dropped files, and `env` (name, version, platform, port, // token, origins). Every call is one IPC round trip that the main process // validates. const { contextBridge, ipcRenderer, webUtils } = require('electron'); const arg = (name) => { const prefix = `--mollusc-${name}=`; const hit = process.argv.find((a) => a.startsWith(prefix)); return hit ? hit.slice(prefix.length) : ''; }; const names = arg('api').split(',').filter(Boolean); const env = arg('env') ? JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(arg('env')), (c) => c.charCodeAt(0)))) : {}; const listeners = new Map(); // What a listener returns is of no interest, but crossing back from the page's // world it gets cloned, and a page object cannot be: those errors are dropped. const uncloneable = (err) => /could not be cloned/i.test(String(err?.message || err)); ipcRenderer.on('mollusc:event', (e, name, payload) => { for (const fn of listeners.get(name) || []) { try { const out = fn(payload); if (out && typeof out.then === 'function') out.then(null, (err) => { if (!uncloneable(err)) console.error(`mollusc.on(${name}):`, err); }); } catch (err) { if (!uncloneable(err)) console.error(`mollusc.on(${name}):`, err); } } }); // Listening for close-requested is what tells the shell to ask before closing. const guardChanged = (name) => { if (name === 'close-requested') ipcRenderer.invoke('mollusc:guardClose', (listeners.get(name)?.size || 0) > 0); }; const mollusc = { env: Object.freeze(env), on (name, fn) { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(fn); guardChanged(name); return () => { listeners.get(name)?.delete(fn); guardChanged(name); }; }, openWindow: (url, opts) => ipcRenderer.invoke('mollusc:openWindow', url, opts), }; for (const name of names) { const [ns, fn] = name.split('.'); if (!ns || !fn || ns in mollusc && typeof mollusc[ns] !== 'object') continue; mollusc[ns] ||= {}; mollusc[ns][fn] = (...args) => ipcRenderer.invoke(`mollusc:${name}`, ...args); } // The path of a File the user dropped or picked with , and // leave to read it with mollusc.fs. '' for a File made in script. if (names.some((n) => n.startsWith('fs.'))) { mollusc.pathForFile = async (file) => { const p = webUtils.getPathForFile(file); if (p) await ipcRenderer.invoke('mollusc:grantDropped', p); return p; }; } contextBridge.exposeInMainWorld('mollusc', mollusc);