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

@lhy-meta-web/websocket

v0.0.1

Published

Browser WebSocket client for @lhy-meta-server/meta-websocket: event protocol, request/ack, reconnection, offline queue and heartbeat

Readme

@lhy-meta-web/websocket

@lhy-meta-server/meta-websocket 的浏览器端客户端。使用与服务端一致的 JSON 信封协议,提供双向请求-确认、自动重连、离线发送队列与应用层心跳。零运行时依赖。

安装

pnpm add @lhy-meta-web/websocket

快速开始

import { WsClient, WsRemoteAckError } from '@lhy-meta-web/websocket'

// 可选:声明事件类型,获得事件名、载荷与确认数据的类型推断
interface ClientEvents {
  'room:join': { data: { room: string }; ack: { joined: string } }
  'chat:send': { data: { room: string; text: string }; ack: { delivered: boolean } }
}
interface ServerEvents {
  'chat:message': { data: { from: string; text: string } }
  confirm: { data: { question: string }; ack: boolean }
}

const client = new WsClient<ServerEvents, ClientEvents>({
  // 每次连接(含重连)前调用,适合携带短期票据
  url: async () => `wss://api.example.com/ws?token=${await fetchTicket()}`,
})

client.connect()

// 单向事件;未连接时进入离线队列,连接后按顺序发送
client.emit('chat:send', { room: 'r1', text: 'hi' })

// 请求-确认:兑现为服务端处理器的返回值
try {
  const { joined } = await client.request('room:join', { room: 'r1' }, { timeout: 5000 })
} catch (error) {
  if (error instanceof WsRemoteAckError) console.warn(error.code, error.details) // 如 VALIDATION_FAILED
}

// 监听服务端事件
client.on('chat:message', ({ data }) => render(data))

// 应答服务端 connection.request():返回值(可为 Promise)作为确认数据,抛出 WsError 作为确认失败
client.on('confirm', ({ data }) => window.confirm(data.question))

// 生命周期
client.lifecycle.on('open', ({ reconnected }) => reconnected && resync())
client.lifecycle.on('close', ({ code, reason, willReconnect }) => {})
client.lifecycle.on('server-error', ({ code, message, event }) => {}) // 服务端保留事件 "error"
client.lifecycle.on('error', error => {}) // 客户端内部错误

client.close() // 主动关闭,不再重连

服务端对应写法:

manager.on('ping', () => 'pong') // 应用层心跳
manager.on('room:join', wsTypeBox(t.Object({ room: t.String() })), ({ connection, data }) => {
  connection.join(data.room)
  return { joined: data.room }
})
const ok = await connection.request('confirm', { question: 'Continue?' })

协议

与服务端 WsJsonCodec 完全一致:

| 方向 | 格式 | | --- | --- | | 事件 | { "event": "chat", "data": {...} } | | 请求 | { "event": "chat", "data": {...}, "id": "1" } | | 成功确认 | { "ack": "1", "data": {...} } | | 失败确认 | { "ack": "1", "error": { "code": "...", "message": "...", "details": ... } } | | 错误通知 | { "event": "error", "data": { "code": "...", "message": "...", "event": "chat" } } |

服务端换用 MessagePack 等编解码器时,实现 WsCodec 接口并通过 codec 传入。服务端使用 mode: 'raw' 时,客户端也设置 mode: 'raw',只用 send() 和 lifecycle.on('message')。

行为说明

状态

idle → connecting → open → reconnecting → … → closed,通过 client.state 和 lifecycle.on('state') 获取。

自动重连

默认开启,指数退避加抖动(首次 1 秒,每次翻倍,上限 30 秒,无次数上限),成功连接后重新计数。

默认不重连的关闭码:1000、1002、1003、1008(如限流)、1009(消息过大)以及 4000–4999(业务自定义,如服务端 disconnect(4001) 踢下线)。其他情况(1001 服务端重启、1006 异常断开或握手被拒、1011、1013 等)都会重连。可通过 shouldReconnect 覆盖。

等待重连时浏览器触发 online 事件会立即重连。在 reconnecting 状态调用 connect() 也会立即重连。

浏览器拿不到握手被拒绝时的 HTTP 状态码(401、403、429 等),只会收到 1006,客户端会按退避策略重试。票据失效时在 url 工厂函数中刷新;需要停止重试时,在 close 事件中调用 client.close()。

离线队列与请求

  • 非 open 状态(idle、connecting、reconnecting)下的 emit、request、send 进入队列,连接建立后在 open 事件之前按顺序发送。队列满时抛出 QUEUE_FULL;queue: false 时直接抛出 CONNECTION_CLOSED。
  • request() 的超时从调用时开始计算,包含在队列中等待的时间;超时或取消的请求会从队列中移除。
  • 连接断开时,已发送但未确认的请求以 CONNECTION_CLOSED 拒绝,不会在重连后重发(服务端已是新连接,重发可能导致重复执行)。仍在队列中的请求会在重连后发送。
  • 进入 closed 后,队列中的消息被丢弃,所有等待中的请求以 CONNECTION_CLOSED 拒绝。
  • 发送前按 maxMessageSize 检查体积,超限抛出 MESSAGE_TOO_LARGE,避免被服务端以 1009 断开。

服务端事件

  • 同一事件可以注册多个处理器,按注册顺序调用。服务端请求确认时,以第一个处理器的返回值作为确认数据。
  • 处理器抛出 WsError 时,错误码、消息与详情原样作为确认失败返回;其他错误返回 INTERNAL_ERROR。
  • 服务端请求的事件没有处理器时,返回 UNKNOWN_EVENT 确认失败。
  • 处理器完成前连接已更换时,确认会被丢弃(它属于旧连接)。
  • error 是保留事件名,分发到 lifecycle.on('server-error'),不能用 client.on('error') 监听。

心跳

浏览器会自动回应服务端的协议层 ping,但无法发送 ping,也感知不到半开连接(如切换网络)。客户端默认开启应用层心跳:

  1. interval(默认 25 秒)内没有收到任何消息时,以 { "event": "ping", "id": "hb:N" } 发送请求。
  2. timeout(默认 10 秒)内收到任意消息即视为存活,否则判定连接失效,以 1006 / Heartbeat timeout 断开并重连。

服务端应注册心跳事件:manager.on('ping', () => 'pong')。未注册时服务端返回的 UNKNOWN_EVENT 确认同样视为存活,但服务端设置了 sendErrors: false 时不会有任何响应,连接会被反复判定失效。心跳请求同样计入服务端 rateLimit。服务端配置了 idleTimeout 时,心跳也能保活。

错误

lifecycle.on('error') 接收套接字错误、解码失败、处理器异常、地址工厂失败等客户端内部错误。没有注册监听器时输出到 console.error。

配置项

| 选项 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | url | string \| URL \| () => string \| URL \| Promise<…> | - | 连接地址(必填),工厂函数在每次连接前调用 | | protocols | string \| string[] | - | 子协议 | | mode | 'event' \| 'raw' | 'event' | raw 时只收发原始帧,心跳关闭 | | codec | WsCodec | WsJsonCodec | 需与服务端一致 | | reconnect | { maxAttempts, delay, maxDelay, factor, jitter } \| boolean | { Infinity, 1000, 30000, 2, 0.5 } | 自动重连 | | shouldReconnect | (info) => boolean | wsDefaultShouldReconnect | 根据关闭码判断是否重连 | | reconnectOnOnline | boolean | true | 恢复联网时立即重连 | | heartbeat | { interval, timeout, event, data? } \| boolean | { 25000, 10000, 'ping' } | 应用层心跳 | | queue | { maxSize } \| boolean | { maxSize: 100 } | 离线发送队列 | | ackTimeout | number | 10000 | request() 默认超时 | | maxPendingAcks | number | 100 | 同时等待确认的请求数 | | maxMessageSize | number \| false | 1048576 | 单条发送消息字节上限 | | WebSocket | WebSocket 构造函数 | globalThis.WebSocket | 测试或非浏览器环境注入 |

API

WsClient<ServerEvents, ClientEvents>

| 成员 | 说明 | | --- | --- | | connect() | 建立连接;已连接或连接中时不做任何操作 | | close(code = 1000, reason = '') | 主动关闭;关闭码只允许 1000 或 3000–4999,原因超过 123 字节会被截断 | | destroy() | 关闭并移除全部监听器,之后不可再使用 | | emit(event, data?) | 单向事件 | | request(event, data?, { timeout, signal }) | 请求-确认 | | send(frame) | 发送原始文本或二进制帧 | | on / once / off | 服务端事件,on / once 返回取消函数 | | lifecycle.on / once / off | 生命周期事件:state、connecting、open、close、reconnecting、reconnect-failed、message、server-error、error | | state / isOpen / protocol / bufferedAmount | 连接信息 | | pendingAcks / queuedMessages / reconnectAttempts | 计数 |

错误码

| 错误码 | 场景 | | --- | --- | | ACK_TIMEOUT / ACK_ABORTED | request() 超时或被取消 | | CONNECTION_CLOSED | 已关闭、队列关闭时未连接,或已发送的请求遇到断线 | | TOO_MANY_PENDING_ACKS | 超过 maxPendingAcks | | QUEUE_FULL | 离线队列已满 | | MESSAGE_TOO_LARGE | 超过 maxMessageSize | | SEND_FAILED | 底层 send() 抛出异常 | | CONNECTION_ERROR | 底层 WebSocket 触发 error 事件 | | INVALID_MESSAGE | 收到无法解码的消息 | | INVALID_OPTION | 配置或参数无效 | | 服务端错误码 | 通过 WsRemoteAckError(确认失败)或 server-error 事件返回,如 VALIDATION_FAILED、UNKNOWN_EVENT、RATE_LIMITED、INTERNAL_ERROR |

测试

pnpm vitest run apps/meta-websocket   # 在仓库根目录执行