sindresorhus / electron-better-ipc

Simplified IPC communication for Electron apps
MIT License
715 stars 60 forks source link

Better Typescript Support #45

Open stefnotch opened 2 years ago

stefnotch commented 2 years ago

It'd be lovely if this library came with excellent Typescript support, where one can define which "ipc methods" actually exist. Like being able to say

type MainIpc = {
  "get-emoji"(name: string): string;
};

Then doing a bit to annotate the IPC with said types, like const ipc: SafeMainProcessIpc<MainIpc, RendererIpc> = ipcMain;

After that, one could have excellent autocomplete and Typescript errors if something doesn't add up. image

stefnotch commented 2 years ago

Here's an example implementation, feel free to use it.

import type { BrowserWindow } from "electron";

/**
 * IPC methods that the main process supports
 */
export type MainIpc = {
  noPayload(a: number): void;
  simplePlayload(cat: number): string;
  complexRet(b: number): {
    foo: string;
    bar: {
      baz: number;
    };
  };
  "get-emoji"(name: string): string;
};

/**
 * IPC methods that our single render process supports.
 * Technically we could have multiple render processes, but in this simplistic version we don't.
 */
export type RendererIpc = {
  "complex-payload"(a: string): {
    foo: string;
    bar: {
      baz: number;
    };
  };
};

// We have functions with at most one argument
type IpcTypeSchema = { [key: string]: (...args: [any]) => any };

/**
 * MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
export interface SafeMainProcessIpc<
  MainType extends IpcTypeSchema,
  RendererType extends IpcTypeSchema
> {
  /**
    Send a message to the given window.

    In the renderer process, use `ipcRenderer.answerMain` to reply to this message.

    @param browserWindow - The window to send the message to.
    @param channel - The channel to send the message on.
    @param data - The data to send to the receiver.
    @returns - The reply from the renderer process.

    @example
import {BrowserWindow} from 'electron';
import {ipcMain as ipc} from 'electron-better-ipc';

const browserWindow = BrowserWindow.getFocusedWindow();

const emoji = await ipc.callRenderer(browserWindow!, 'get-emoji', 'unicorn');
console.log(emoji);
//=> '🦄'
```
*/

callRenderer( browserWindow: BrowserWindow, channel: Channel, ...data: Parameters<RendererType[Channel]> ): Promise<ReturnType<RendererType[Channel]>>;

/** Send a message to the focused window, as determined by electron.BrowserWindow.getFocusedWindow.

In the renderer process, use `ipcRenderer.answerMain` to reply to this message.

@param channel - The channel to send the message on.
@param data - The data to send to the receiver.
@returns - The reply from the renderer process.

@example
```
import {ipcMain as ipc} from 'electron-better-ipc';

const emoji = await ipc.callFocusedRenderer('get-emoji', 'unicorn');
console.log(emoji);
//=> '🦄'
```
*/

callFocusedRenderer( channel: Channel, ...data: Parameters<RendererType[Channel]> ): Promise<ReturnType<RendererType[Channel]>>;

/** This method listens for a message from ipcRenderer.callMain defined in a renderer process and replies back.

@param channel - The channel to send the message on.
@param callback - The return value is sent back to the `ipcRenderer.callMain` in the renderer process.
@returns A function, that when called, removes the listener.

@example
```
import {ipcMain as ipc} from 'electron-better-ipc';

ipc.answerRenderer('get-emoji', async emojiName => {
    const emoji = await getEmoji(emojiName);
    return emoji;
});
```
*/

answerRenderer( channel: Channel, callback: ( data: Parameters<MainType[Channel]>[0], browserWindow: BrowserWindow ) => | ReturnType<MainType[Channel]> | PromiseLike<ReturnType<MainType[Channel]>> ): () => void;

/** This method listens for a message from ipcRenderer.callMain defined in the given BrowserWindow's renderer process and replies back.

@param browserWindow - The window for which to expect the message.
@param channel - The channel to send the message on.
@param callback - The return value is sent back to the `ipcRenderer.callMain` in the renderer process.
@returns A function, that when called, removes the listener.

@example
```
import {ipcMain as ipc} from 'electron-better-ipc';

ipc.answerRenderer('get-emoji', async emojiName => {
    const emoji = await getEmoji(emojiName);
    return emoji;
});
```
*/

answerRenderer( browserWindow: BrowserWindow, channel: Channel, callback: ( data: Parameters<MainType[Channel]>[0], browserWindow: BrowserWindow ) => | ReturnType<MainType[Channel]> | PromiseLike<ReturnType<MainType[Channel]>> ): () => void;

/** Send a message to all renderer processes (windows).

@param channel - The channel to send the message on.
@param data - The data to send to the receiver.
*/

sendToRenderers( channel: Channel, data?: Parameters<RendererType[Channel]>[0] ): void; }

export interface SafeRendererProcessIpc< MainType extends IpcTypeSchema, RendererType extends IpcTypeSchema

{ /** Send a message to the main process.

In the main process, use `ipcMain.answerRenderer` to reply to this message.

@param channel - The channel to send the message on.
@param data - The data to send to the receiver.
@returns The reply from the main process.

@example
```
import {ipcRenderer as ipc} from 'electron-better-ipc';

const emoji = await ipc.callMain('get-emoji', 'unicorn');
console.log(emoji);
//=> '🦄'
```
*/

callMain( channel: Channel, ...data: Parameters<MainType[Channel]> ): Promise<ReturnType<MainType[Channel]>>;

/** This method listens for a message from ipcMain.callRenderer defined in the main process and replies back.

@param channel - The channel to send the message on.
@param callback - The return value is sent back to the `ipcMain.callRenderer` in the main process.
@returns A function, that when called, removes the listener.

@example
```
import {ipcRenderer as ipc} from 'electron-better-ipc';

ipc.answerMain('get-emoji', async emojiName => {
    const emoji = await getEmoji(emojiName);
    return emoji;
});
```
*/

answerMain( channel: Channel, callback: ( data: Parameters<RendererType[Channel]>[0] ) => | ReturnType<RendererType[Channel]> | PromiseLike<ReturnType<RendererType[Channel]>> ): () => void; }

sindresorhus commented 2 years ago

I'm happy to have this added if someone does a high-quality pull request with docs and tests.

linonetwo commented 1 year ago

https://github.com/sindresorhus/electron-better-ipc/issues/48 TS version

so1ve commented 1 year ago

https://github.com/sindresorhus/electron-better-ipc/issues/48 TS version

Deleted :( why?

linonetwo commented 1 year ago

Maybe owner don't like my redirect...Anyway sorry for that.

And the link in that issue was https://github.com/linonetwo/electron-ipc-cat