npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@quiteer/electron-ipc

v3.2.0

Published

基于electron , 提供了一些 独立无副作用的 ipc 事件相关操作

Readme

@quiteer/electron-ipc

Electron 主进程 IPC 预设通道:一次 init(),渲染进程即可安全地操作所属窗口、调用 node:path 能力。

包内不持有任何全局状态,所有窗口操作都来自 event.sender 定位的窗口,渲染进程无法越权操作别的窗口。

从 3.0 升级请看 升级指南:3.2 起内置通道默认只接受主 frame 的调用;也介绍了如何把现有通道迁到 IPC 契约。

安装

pnpm add @quiteer/electron-ipc

快速开始

主进程里初始化:

import { Ipc } from '@quiteer/electron-ipc';
import { app } from 'electron';

app.whenReady().then(() => {
  Ipc.init();
});

渲染进程里按枚举发消息(需配合预加载脚本暴露的 window.$ipc):

import { EventKeys, IpcWindowOptions } from '@quiteer/electron-ipc/web';

// 最大化当前窗口
window.$ipc.send(EventKeys.WindowOptionsKey, IpcWindowOptions.MAXIMIZE);

// 拼路径, 返回 Promise
const full = await window.$ipc.invoke(EventKeys.FileOptionsKey, 'join', '/user', 'local');

内置通道

__window_options__ — 窗口控制

send 单向发送,操作对象是发起调用的窗口自身。

| 枚举 | 值 | 说明 | | ---------------------- | ---------------------- | -------------------------------------- | | DESTROY | destroy | 销毁窗口,触发 closed | | CLOSE | close | 尝试关闭,等同点关闭按钮(页面可拦截) | | SHOW | show | 显示 | | HIDE | hide | 隐藏 | | FOCUS | focus | 获取焦点 | | BLUR | blur | 失去焦点 | | MAXIMIZE | maximize | 最大化 | | UNMAXIMIZE | unmaximize | 取消最大化 | | MINIMIZE | minimize | 最小化 | | RESTORE | restore | 从最小化还原 | | RELOAD | reload | 刷新 | | SET_FULL_SCREEN | setFullScreen | 全屏,附 flag: boolean | | SET_TITLE | setTitle | 改标题,附 title: string | | FLASH_FRAME | flashFrame | 任务栏闪烁,附 flag: boolean | | SWITCH_FOCUS | switch-focus | 聚焦 / 失焦互切 | | SWITCH_MAX | switch-max | 最大化 / 还原互切 | | SWITCH_MIN | switch-min | 最小化 / 还原互切 | | SWITCH_FULL | switch-full | 全屏 / 退出全屏互切 | | SWITCH_RESIZABLE | switch-resizable | 可否调整尺寸互切 | | SWITCH_MOVABLE | switch-movable | 可否移动互切(Linux 无效) | | SWITCH_MINIMIZABLE | switch-minimizable | 可否最小化互切(Linux 无效) | | SWITCH_MAXIMIZABLE | switch-maximizable | 可否最大化互切(Linux 无效) | | SWITCH_ALWAYS_ON_TOP | switch-always-on-top | 是否置顶互切 |

带参数的调用:

window.$ipc.send(EventKeys.WindowOptionsKey, IpcWindowOptions.SET_TITLE, '新标题');
window.$ipc.send(EventKeys.WindowOptionsKey, IpcWindowOptions.SET_FULL_SCREEN, true);

__file_options__ — 路径处理

invoke 双向调用,返回 Promise,等价于在主进程里调用 node:path 的同名方法。

| 枚举 | 值 | 等价方法 | | ---------- | ---------- | ------------------------------ | | BASENAME | basename | path.basename(path, suffix?) | | DIRNAME | dirname | path.dirname(path) | | EXTNAME | extname | path.extname(path) | | JOIN | join | path.join(...paths) | | PARSE | parse | path.parse(path) | | RELATIVE | relative | path.relative(from, to) | | RESOLVE | resolve | path.resolve(...paths) |

const dir = await window.$ipc.invoke(EventKeys.FileOptionsKey, 'dirname', '/a/b/c.txt');
const info = await window.$ipc.invoke(EventKeys.FileOptionsKey, 'parse', '/a/b/c.txt');

类型安全的 IPC 契约

业务通道不再是「字符串 + unknown」:在一个共享文件里定义契约,主进程 handler、渲染层 client、preload 通道白名单都从它推导,任何一端写错通道名、参数或返回值都会直接类型报错。

1. 定义契约(主进程与渲染层共享)

// shared/ipc.ts —— 只依赖 /web 入口, 主进程、preload、渲染层都能引用
import { channel, defineContract } from '@quiteer/electron-ipc/web';

export const api = defineContract({
  // 渲染层 → 主进程, 有返回值
  invoke: {
    'user:get': channel<(id: string) => User>(),
  },
  // 渲染层 → 主进程, 单向
  send: {
    'app:log': channel<(msg: string) => void>(),
  },
  // 主进程 → 渲染层推送
  on: {
    'download:progress': channel<(percent: number) => void>(),
  },
});

channel<F>() 用函数签名描述参数与返回值,运行时只是一个空占位。

2. 主进程实现

import { createEmitter, handleContract } from '@quiteer/electron-ipc';
import { api } from '../shared/ipc';

const dispose = handleContract(api, {
  invoke: {
    'user:get': (ctx, id) => db.users.find(id), // 可返回 Promise
  },
  send: {
    'app:log': (ctx, msg) => logger.info(ctx.window?.id, msg),
  },
});

const emitter = createEmitter(api);
emitter.emit(win, 'download:progress', 0.5); // 推给某个窗口 / webContents
emitter.broadcast('download:progress', 1); // 推给全部窗口
  • 契约里每个 invoke / send 通道都必须实现,漏写、多写或返回值不符都会类型报错;运行时漏实现也会在注册前抛错,不会留下注册了一半的通道。
  • handler 的第一个参数 ctx 与 Electron 的 (event, ...args) 约定一致:{ event, sender, window },window 是发起调用的 BrowserWindow。
  • 返回的 dispose() 注销本次注册的全部通道,可用于热重载。

3. 渲染层调用

import { createClient } from '@quiteer/electron-ipc/web';
import { api } from '../shared/ipc';

const client = createClient(api); // 默认使用 window.$ipc, 也可显式传入

const user = await client.invoke('user:get', '1'); // Promise<User>
client.send('app:log', 'hello');
const off = client.on('download:progress', (percent) => {}); // 回调不带 event

契约之外的通道名在运行时同样会被拒绝,as any 也绕不过去。

4. 生成 preload 通道白名单

// main
import { createPreload } from '@quiteer/electron-preload/main';
import { channelsOf } from '@quiteer/electron-ipc';
import { api, settingsApi } from '../shared/ipc';

api.channels; // { send: ['app:log'], invoke: ['user:get'], on: ['download:progress'] }

new BrowserWindow({
  webPreferences: {
    // 多个契约合并去重; 本包内置通道由 createPreload 默认放行
    ...createPreload({ channels: channelsOf(api, settingsApi) }),
  },
});

白名单形状 { send, invoke, on } 与 createPreload({ channels }) 一一对应,不需要再手写一遍。关闭了 createPreload 的 builtinChannels 又想单独放行时,可以合并本包导出的 builtinChannels。

参数校验(可选)

渲染层的参数在主进程边界不可信。channel 接受任意 Standard Schema(zod / valibot / arktype 等),schema 的输出类型必须与签名参数一致:

import { z } from 'zod';

channel<(id: string) => User>({ args: z.tuple([z.string().uuid()]) });

校验在主进程执行:失败时 invoke 以错误拒绝,send 丢弃并 console.error;handler 拿到的是校验后的值。

来源校验

handleContract 的第三个参数与 Ipc.init(options) 完全一致:默认只接受主 frame 的调用,页面里嵌入的第三方 iframe 无法调用契约通道;可用 allowedOrigins 进一步限定页面来源,或用 validateSender 完全自定义。

handleContract(api, handlers, { allowedOrigins: ['file://', 'http://localhost:5173'] });

渲染层类型增强

包内提供 WithIpcChannels,把内置通道的精确签名叠加到预加载的 $ipc 类型上:

// global.d.ts
interface Window {
  $ipc: import('@quiteer/electron-ipc/web').WithIpcChannels<
    import('@quiteer/electron-preload').PreloadIpc
  >;
}

之后写错操作名或漏传参数都会直接报错,业务自定义通道照常使用:

window.$ipc.send('__window_options__', 'destroy'); // ✅
window.$ipc.invoke('__file_options__', 'join', '/', '/experiment'); // ✅ Promise<string>
window.$ipc.send('my-channel', { id: 1 }); // ✅ 业务通道不受影响
window.$ipc.send('__window_options__', 'not-exist'); // ❌ 类型报错
window.$ipc.send('__window_options__', 'setTitle'); // ❌ 漏传 title

旧写法 PreloadIpc & ExpandPreloadIpc 不会报错:PreloadIpc 的宽松签名 (channel: string, ...args) 会兜住所有调用。ExpandPreloadIpc 仍然导出,但请改用 WithIpcChannels。

与 @quiteer/electron-browser 配合

本包按 event.sender 定位窗口,若你还需要按名管理窗口,可在自己的业务通道里用 browser 的仓库反查来源:

import { ipcMain } from 'electron';
import { windows } from '@quiteer/electron-browser';

ipcMain.on('custom', (event) => {
  const controller = windows.store.fromWebContents(event.sender);
  controller?.target.webContents.send('custom:reply', controller.name);
});

API

Ipc 是模块级单例,直接取用即可。

| 成员 | 说明 | | -------------------- | ------------------------------------------------------------------ | | Ipc.init(options?) | 注册两个内置通道的监听与处理器,重复调用无副作用(以首次选项为准) | | Ipc.destroy() | 注销本包注册的监听与处理器,之后可再次 init() | | Ipc.initialized | 当前是否已注册 |

来源校验

内置通道默认只接受主 frame 的调用,子 frame(含第三方 iframe)发来的窗口操作会被忽略、路径调用会被拒绝。还可以进一步限定页面来源:

Ipc.init({ allowedOrigins: ['file://', 'http://localhost:5173'] });

| 选项 | 说明 | | ---------------- | ------------------------------------------------------------------ | | allowedOrigins | 允许的页面来源,file:// 按协议匹配,其余按 URL.origin 精确匹配 | | validateSender | (event) => boolean,传入后替代默认校验(包括主 frame 检查) |

配合 @quiteer/electron-preload 使用时,内置通道默认已在其通道白名单内。

契约相关:

| 导出 | 入口 | 说明 | | ------------------------------------- | -------- | ------------------------------------------------------ | | defineContract(spec) | 两者皆有 | 定义契约,返回值带 channels 白名单 | | channel<F>(options?) | 两者皆有 | 声明单个通道,可选 args 参数校验 | | channelsOf(...sources) | 两者皆有 | 合并多个契约 / 白名单并去重 | | builtinChannels | 两者皆有 | Ipc.init() 注册的内置通道白名单 | | handleContract(api, handlers, opts) | 主入口 | 注册主进程 handler,返回 dispose() | | createEmitter(api) | 主入口 | 按契约推送:emit(target, channel, ...) / broadcast | | createClient(api, bridge?) | /web | 渲染层 client:invoke / send / on / once |

主入口同时导出 EventKeys、IpcWindowOptions、IpcFileOptions,主进程里需要引用通道名时不必再走 /web。

注意事项

  • 只需在主进程 app.whenReady() 之后 init();init() 是幂等的,热重载时可先 destroy() 再 init()。
  • destroy() 只移除本包自己的监听,业务方挂在同名通道上的回调不受影响。
  • 渲染层传入未知操作时:窗口通道静默忽略,路径通道 invoke 会以错误拒绝。
  • 窗口类操作只作用于发起调用的窗口,渲染进程无法指定其他窗口——这是刻意的约束。
  • 通道常量统一走 EventKeys,不要手写字符串,避免拼写漂移。
  • 包为 ESM-only:主进程需使用 ESM,或交由打包器(electron-builder / vite / esbuild)一起编译。CJS 主进程直接 require() 会抛 ERR_PACKAGE_PATH_NOT_EXPORTED。