chore(ipc): extract as electron-ipc-decorator
- Added electron-ipc-decorator as a dependency to streamline IPC method registration and context management. - Refactored IPC service classes to utilize the new decorator, enhancing code organization and readability. - Removed the base IPC context file, consolidating IPC logic within the decorator framework. - Updated package.json files to include electron-ipc-decorator in both main and renderer processes. These changes collectively enhance the IPC architecture, improving maintainability and reducing boilerplate code. Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
@@ -30,6 +30,7 @@
|
||||
"@sentry/electron": "6.8.0",
|
||||
"builder-util-runtime": "9.3.1",
|
||||
"electron-context-menu": "4.0.5",
|
||||
"electron-ipc-decorator": "0.1.1",
|
||||
"electron-log": "5.4.1",
|
||||
"electron-squirrel-startup": "1.0.1",
|
||||
"electron-store": "10.1.0",
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import type { IpcMainInvokeEvent, WebContents } from "electron"
|
||||
import { ipcMain } from "electron"
|
||||
|
||||
// Base context for IPC methods
|
||||
export interface IpcContext {
|
||||
sender: WebContents
|
||||
event: IpcMainInvokeEvent
|
||||
}
|
||||
|
||||
// Metadata storage for decorated methods
|
||||
const methodMetadata = new WeakMap<any, Map<string, string>>()
|
||||
|
||||
// Decorator for IPC methods
|
||||
export function IpcMethod(methodName?: string) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const { constructor } = target
|
||||
|
||||
if (!methodMetadata.has(constructor)) {
|
||||
methodMetadata.set(constructor, new Map())
|
||||
}
|
||||
|
||||
const methods = methodMetadata.get(constructor)!
|
||||
const finalMethodName = methodName || propertyKey
|
||||
methods.set(propertyKey, finalMethodName)
|
||||
|
||||
return descriptor
|
||||
}
|
||||
}
|
||||
|
||||
// Handler registry for IPC methods
|
||||
export class IpcHandler {
|
||||
private static instance: IpcHandler
|
||||
private registeredChannels = new Set<string>()
|
||||
|
||||
static getInstance(): IpcHandler {
|
||||
if (!IpcHandler.instance) {
|
||||
IpcHandler.instance = new IpcHandler()
|
||||
}
|
||||
return IpcHandler.instance
|
||||
}
|
||||
|
||||
registerMethod<TOutput>(
|
||||
channel: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
if (this.registeredChannels.has(channel)) {
|
||||
return // Already registered
|
||||
}
|
||||
|
||||
this.registeredChannels.add(channel)
|
||||
|
||||
ipcMain.handle(channel, async (event: IpcMainInvokeEvent, ...args: any[]) => {
|
||||
const context: IpcContext = {
|
||||
sender: event.sender,
|
||||
event,
|
||||
}
|
||||
|
||||
try {
|
||||
return await handler(context, ...args)
|
||||
} catch (error) {
|
||||
console.error(`Error in IPC method ${channel}:`, error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Send events to renderer
|
||||
sendToRenderer<T = any>(webContents: WebContents, channel: string, data: T) {
|
||||
webContents.send(channel, data)
|
||||
}
|
||||
}
|
||||
|
||||
// Base class for IPC service groups
|
||||
export abstract class IpcService {
|
||||
protected handler = IpcHandler.getInstance()
|
||||
|
||||
constructor(protected groupName: string) {
|
||||
this.registerMethods()
|
||||
}
|
||||
|
||||
protected registerMethods(): void {
|
||||
const { constructor } = this
|
||||
const methods = methodMetadata.get(constructor)
|
||||
|
||||
if (methods) {
|
||||
for (const [propertyKey, methodName] of methods) {
|
||||
const method = (this as any)[propertyKey]
|
||||
if (typeof method === "function") {
|
||||
this.registerMethod(methodName, method.bind(this))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected registerMethod<TOutput>(
|
||||
methodName: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
const channel = `${this.groupName}.${methodName}`
|
||||
this.handler.registerMethod(channel, handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract method signatures from service class, removing context parameter
|
||||
export type ExtractServiceMethods<T> = {
|
||||
[K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] extends (
|
||||
context: IpcContext,
|
||||
...args: infer Args
|
||||
) => infer Output
|
||||
? Args extends []
|
||||
? () => AlwaysPromise<Output>
|
||||
: Args extends [infer Input]
|
||||
? (input: Input) => AlwaysPromise<Output>
|
||||
: (...args: Args) => AlwaysPromise<Output>
|
||||
: never
|
||||
}
|
||||
|
||||
type AlwaysPromise<T> = Promise<Awaited<T>>
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExtractServiceMethods } from "./base"
|
||||
import type { MergeIpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { AppService } from "./services/app"
|
||||
import { AuthService } from "./services/auth"
|
||||
import { DebugService } from "./services/debug"
|
||||
@@ -21,16 +22,7 @@ export const services = {
|
||||
} as const
|
||||
|
||||
// Extract method types automatically from services
|
||||
export type IpcServices = {
|
||||
app: ExtractServiceMethods<AppService>
|
||||
auth: ExtractServiceMethods<AuthService>
|
||||
debug: ExtractServiceMethods<DebugService>
|
||||
dock: ExtractServiceMethods<DockService>
|
||||
menu: ExtractServiceMethods<MenuService>
|
||||
reader: ExtractServiceMethods<ReaderService>
|
||||
setting: ExtractServiceMethods<SettingService>
|
||||
integration: ExtractServiceMethods<IntegrationService>
|
||||
}
|
||||
export type IpcServices = MergeIpcService<typeof services>
|
||||
|
||||
// Initialize all services (this will register all IPC handlers)
|
||||
export function initializeIpcServices() {
|
||||
|
||||
@@ -4,6 +4,8 @@ import { fileURLToPath } from "node:url"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import { app, BrowserWindow, clipboard, dialog, shell } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import path from "pathe"
|
||||
|
||||
import { getCacheSize } from "~/lib/cleaner"
|
||||
@@ -17,8 +19,6 @@ import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
|
||||
|
||||
import { downloadFile } from "../../lib/download"
|
||||
import { checkForAppUpdates, quitAndInstall } from "../../updater"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
interface WindowActionInput {
|
||||
action: "close" | "minimize" | "maximum"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { deleteNotificationsToken, updateNotificationsToken } from "../../lib/user"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
export class AuthService extends IpcService {
|
||||
constructor() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
interface InspectElementInput {
|
||||
x: number
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../../constants/app"
|
||||
import { apiClient } from "../../lib/api-client"
|
||||
import { setDockCount } from "../../lib/dock"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
class PollingManager {
|
||||
private abortController: AbortController | null = null
|
||||
|
||||
@@ -2,14 +2,13 @@ import { existsSync } from "node:fs"
|
||||
import fsp from "node:fs/promises"
|
||||
|
||||
import { shell } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import path from "pathe"
|
||||
|
||||
import { store } from "~/lib/store"
|
||||
import { logger } from "~/logger"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
// Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts
|
||||
// https://datatracker.ietf.org/doc/html/rfc2396
|
||||
// eslint-disable-next-line no-control-regex
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron"
|
||||
import { dialog, Menu, ShareMenu } from "electron"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
type SerializableMenuItem = Omit<MenuItemConstructorOptions, "click" | "submenu"> & {
|
||||
submenu?: SerializableMenuItem[]
|
||||
|
||||
@@ -3,13 +3,13 @@ import fs from "node:fs"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { readability } from "@follow-app/readability"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts"
|
||||
import path from "pathe"
|
||||
import type { ModelResult } from "vscode-languagedetection"
|
||||
|
||||
import { detectCodeStringLanguage } from "../../modules/language-detection"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const tts = new MsEdgeTTS()
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { createRequire } from "node:module"
|
||||
|
||||
import { app, nativeTheme } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { WindowManager } from "~/manager/window"
|
||||
|
||||
import { setProxyConfig, updateProxy } from "../../lib/proxy"
|
||||
import { store } from "../../lib/store"
|
||||
import { getTrayConfig, setTrayConfig } from "../../lib/tray"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"cookie-es": "2.0.0",
|
||||
"dayjs": "1.11.13",
|
||||
"dnum": "2.15.0",
|
||||
"electron-ipc-decorator": "0.1.1",
|
||||
"embla-carousel-react": "8.6.0",
|
||||
"embla-carousel-wheel-gestures": "8.0.2",
|
||||
"es-toolkit": "1.39.6",
|
||||
|
||||
@@ -1,25 +1,7 @@
|
||||
import type { IpcServices } from "@follow/electron-main"
|
||||
import type { IpcRenderer } from "electron"
|
||||
import { createIpcProxy } from "electron-ipc-decorator/client"
|
||||
|
||||
function createIpcProxy(): IpcServices | null {
|
||||
if (!window.electron) {
|
||||
return null
|
||||
}
|
||||
|
||||
return new Proxy({} as IpcServices, {
|
||||
get(target, groupName: string) {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_, methodName: string) {
|
||||
return (...args: any[]) => {
|
||||
const channel = `${groupName}.${methodName}`
|
||||
return window.electron!.ipcRenderer.invoke(channel, args[0])
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const ipcServices = createIpcProxy()
|
||||
export const ipcServices = createIpcProxy<IpcServices>(
|
||||
window.electron?.ipcRenderer as unknown as IpcRenderer,
|
||||
)
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
"14002": "Upload failed",
|
||||
"15000": "AI token limit exceeded. Please try again later.",
|
||||
"15001": "You are not allowed to access AI chat",
|
||||
"15002": "AI attachment file limit exceeded. Please try again later.",
|
||||
"16000": "MCP OAuth error",
|
||||
"16001": "MCP discovery error",
|
||||
"16002": "MCP service not found",
|
||||
|
||||
Generated
+16
@@ -372,6 +372,9 @@ importers:
|
||||
electron-context-menu:
|
||||
specifier: 4.0.5
|
||||
version: 4.0.5(patch_hash=15ed04a0d246eb9e701f47314b91328c64a8a7374914ad58b4053a3f84075fab)
|
||||
electron-ipc-decorator:
|
||||
specifier: 0.1.1
|
||||
version: 0.1.1(electron@37.2.0)
|
||||
electron-log:
|
||||
specifier: 5.4.1
|
||||
version: 5.4.1
|
||||
@@ -592,6 +595,9 @@ importers:
|
||||
dnum:
|
||||
specifier: 2.15.0
|
||||
version: 2.15.0
|
||||
electron-ipc-decorator:
|
||||
specifier: 0.1.1
|
||||
version: 0.1.1(electron@37.2.0)
|
||||
embla-carousel-react:
|
||||
specifier: 8.6.0
|
||||
version: 8.6.0(react@19.0.0)
|
||||
@@ -8751,6 +8757,12 @@ packages:
|
||||
engines: {node: '>= 16'}
|
||||
hasBin: true
|
||||
|
||||
electron-ipc-decorator@0.1.1:
|
||||
resolution: {integrity: sha512-qzEdgNjSWbG3iqjeAJ0WcusyiLvoKhsyb4XBn/mPqu2fkYAXVsUvvVI56Un3CKC77GGaMEhYvXcf8ddlZJO0wg==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
peerDependencies:
|
||||
electron: '>=32.0.0'
|
||||
|
||||
electron-is-dev@3.0.1:
|
||||
resolution: {integrity: sha512-8TjjAh8Ec51hUi3o4TaU0mD3GMTOESi866oRNavj9A3IQJ7pmv+MJVmdZBFGw4GFT36X7bkqnuDNYvkQgvyI8Q==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -24716,6 +24728,10 @@ snapshots:
|
||||
- supports-color
|
||||
optional: true
|
||||
|
||||
electron-ipc-decorator@0.1.1(electron@37.2.0):
|
||||
dependencies:
|
||||
electron: 37.2.0
|
||||
|
||||
electron-is-dev@3.0.1: {}
|
||||
|
||||
electron-log@5.4.1: {}
|
||||
|
||||
Reference in New Issue
Block a user