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

@red_dot/js-bridge

v1.0.0

Published

Web 与 Native 双向通信的 JavaScript Bridge SDK,适用于 Mini Program 场景。

Readme

@red_dot/js-bridge

Web 与 Native 双向通信的 JavaScript Bridge SDK,适用于 Mini Program 场景。

安装

pnpm add @red_dot/js-bridge

快速开始

import { JsBridge } from '@red_dot/js-bridge';

// 1. 创建实例
const sdk = new JsBridge({});

// 2. 初始化(内部会自动完成登录)
const result = await sdk.init({
  appId: 'your-app-id',
  onReady: (response) => {
    console.log('SDK ready', response);
  },
  onError: (error) => {
    console.error('SDK error', error);
  }
});

// 3. 获取用户信息
const userInfo = await sdk.getUserInfo();

// 4. 发起支付
const paymentResult = await sdk.requestPayment({
  appId: 'your-app-id',
  openId: 'user-open-id',
  prepayId: 'prepay-id',
  amount: 100,
  sign: 'signature',
  timestamp: '1700000000',
  nonceStr: 'random-string'
});

API

new JsBridge(props)

创建 JsBridge 实例。

| 参数 | 类型 | 必填 | 说明 | | ----- | --------------- | ---- | ---------- | | props | JsBridgeProps | ✅ | 构造器配置 |


sdk.init(options): Promise<RequestNativeResult>

初始化 SDK。内部会自动调用 login 完成鉴权,初始化成功后 SDK 状态变为 initialized

| 参数 | 类型 | 必填 | 说明 | | ------- | ------------------------------------------ | ---- | -------------------------- | | appId | string | ✅ | 应用 ID | | onReady | (response: RequestNativeResponse) => void | ❌ | 初始化成功回调 | | onError | (error: ErrorDetails) => void | ❌ | 错误回调(全局错误监听器) |

注意: init 只能调用一次。重复调用会根据当前状态返回对应错误码。


sdk.getUserInfo(): Promise<RequestNativeResult>

获取用户信息。需要在 init 完成后调用。

const userInfo = await sdk.getUserInfo();

sdk.requestPayment(options): Promise<RequestNativeResult>

发起支付请求。需要在 init 完成后调用。

| 参数 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ---------- | | appId | string | ✅ | 应用 ID | | openId | string | ✅ | 用户 OpenID | | prepayId | string | ✅ | 预支付 ID | | amount | number | ✅ | 支付金额 | | sign | string | ✅ | 签名 | | timestamp | string | ✅ | 时间戳 | | nonceStr | string | ✅ | 随机字符串 |


sdk.isReady(): boolean

检查 SDK 是否已初始化就绪。


sdk.destroy(): void

销毁 SDK 实例,状态变为 destroyed,此后任何 API 调用都会返回错误。

SDK 生命周期

uninitialized ──init()──▶ initializing ──login 成功──▶ initialized
       │                       │                           │
       │                  login 失败                   destroy()
       │                       ▼                           ▼
       │                     error                     destroyed
       │                                                   │
       └──── 重复调用 init ──▶ 返回对应状态错误码 ◀─────────┘

| 状态 | 说明 | 允许的操作 | | -------------- | ------------------ | ----------------------------- | | uninitialized | 初始状态 | init() | | initializing | 正在初始化 | 等待完成 | | initialized | 初始化完成 | getUserInfo() / requestPayment() / destroy() | | error | 初始化失败 | — | | destroyed | 已销毁 | — |

错误码

SDK 状态 (1xxx)

| 错误码 | 常量 | 说明 | | ------ | --------------------- | --------------- | | 1001 | NOT_INITIALIZED | SDK 未初始化 | | 1002 | ALREADY_INITIALIZED | SDK 已初始化 | | 1003 | INITIALIZING | SDK 正在初始化 | | 1004 | DESTROYED | SDK 已销毁 | | 1005 | INIT_FAILED | SDK 初始化失败 |

Bridge 通信 (2xxx)

| 错误码 | 常量 | 说明 | | ------ | ---------------------- | ---------------------- | | 2001 | BRIDGE_NOT_AVAILABLE | Native Bridge 不可用 | | 2002 | BRIDGE_TIMEOUT | 请求超时(默认 30s) |

业务错误 (3xxx)

| 错误码 | 常量 | 说明 | | ------ | --------------------- | ------------ | | 3001 | LOGIN_FAILED | 登录失败 | | 3002 | GET_USER_INFO_FAILED | 获取用户信息失败 | | 3003 | PAYMENT_FAILED | 支付失败 | | 3004 | PAYMENT_CANCELLED | 支付取消 |

未知错误

| 错误码 | 常量 | 说明 | | ------ | --------- | -------- | | 9999 | UNKNOWN | 未知错误 |

错误处理

所有 API 调用在失败时返回 ErrorDetails 对象:

interface ErrorDetails {
  code: ErrorCode | number;  // 错误码
  message: string;           // 错误信息
  details?: Record<string, unknown>; // 附加详情
}

同时,如果在 init 时注册了 onError 回调,错误也会通过该回调通知:

sdk.init({
  appId: 'your-app-id',
  onError: (error) => {
    // error: ErrorDetails
    console.error(`[${error.code}] ${error.message}`);
  }
});

架构

┌───────────────────────────────────────────────────────┐
│                      JsBridge                         │
│  (状态管理 / 生命周期 / 对外 API)                      │
├──────────────────────┬────────────────────────────────┤
│     WebToNative      │         NativeToWeb            │
│  (Web → Native 通信)  │    (Native → Web 事件推送)     │
├──────────────────────┤────────────────────────────────┤
│   CallbackManager    │        EventEmitter            │
│  (回调注册/超时管理)   │    (事件发布/订阅)             │
└──────────────────────┴────────────────────────────────┘
  • WebToNative — 封装 Web 向 Native 发送消息的通道,通过 flutter_inappwebview.callHandler 调用 Native 方法,并通过 CallbackManager 管理异步回调与超时。
  • NativeToWeb — 监听 Native 主动推送的事件,通过 EventEmitter 分发给对应的监听器。
  • CallbackManager — 统一管理所有 Web → Native 的回调,支持注册、注销、超时自动 reject。
  • EventEmitter — 事件发布订阅系统,支持 on / once / off / emit,限制单事件最大监听器数量防止内存泄漏。

通信协议

Web → Native(请求)

{
  "callId": "unique-call-id",
  "action": "auth.login",
  "params": { "appId": "xxx" }
}

Native → Web(响应)

{
  "callId": "unique-call-id",
  "code": 200,
  "message": "success",
  "data": {}
}

Native → Web(事件推送)

{
  "callId": "unique-call-id",
  "event": "event.auth.verify",
  "data": {}
}

导出

// 主类
export { JsBridge } from '@red_dot/js-bridge';

// 类型导出
export type {
  JsBridgeProps,
  InitOptions,
  PaymentOptions,
  LoginOptions,
  ErrorDetails,
  RequestNativeParams,
  RequestNativeResponse,
  RequestNativeResult,
  JsBridgeEvent,
  EventListener
} from '@red_dot/js-bridge';

// 枚举导出
export type {
  NativeAction,
  JsBridgeEventType,
  ErrorCode
} from '@red_dot/js-bridge';

开发

# 安装依赖
pnpm install

# 构建(按环境)
pnpm build:dev        # 开发环境
pnpm build:staging    # 预发布环境
pnpm build:prod       # 生产环境

# 类型检查
pnpm typecheck

# 测试
pnpm test

License

SEE LICENSE IN LICENSE.md