import { contextBridge, ipcRenderer } from "electron"; import { electronAPI } from "@electron-toolkit/preload"; import type { SelfAPI } from "./index.d"; // Static properties that are not IPC methods const staticProps = { platform: process.platform, } as const; // Proxy-based API that automatically routes method calls to IPC invoke // Method name = IPC channel name, no manual mapping needed const api: SelfAPI = new Proxy(staticProps as SelfAPI, { get(_target, prop: string) { // Return static property if exists if (prop in staticProps) { return (staticProps as Record)[prop]; } // Otherwise, auto-create IPC invoke function // prop (method name) = IPC channel name return (...args: unknown[]) => ipcRenderer.invoke(prop, ...args); }, }); // Use `contextBridge` APIs to expose Electron APIs to // renderer only if context isolation is enabled, otherwise // just add to the DOM global. if (process.contextIsolated) { try { contextBridge.exposeInMainWorld("electron", electronAPI); contextBridge.exposeInMainWorld("api", api); } catch (error) { console.error(error); } } else { // @ts-ignore (define in dts) window.electron = electronAPI; // @ts-ignore (define in dts) window.api = api; }