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

wsse-sdk

v2.0.0

Published

专门用于 AI 流式输出和站内消息广播的 SSE(Server-Sent Events)长连接管理 SDK。提供了完整的事件监听、自动重连和消息处理机制,特别适合 AI 对话、实时通知等场景。

Downloads

66

Readme

WSSE-SDK

专门用于 AI 流式输出和站内消息广播的 SSE(Server-Sent Events)长连接管理 SDK。提供了完整的事件监听、自动重连和消息处理机制,特别适合 AI 对话、实时通知等场景。

✨ 特性

  • 专门优化了 AI 流式输出场景
  • 支持站内消息实时广播
  • 自动解析和处理流式消息
  • 完整的错误处理和重试机制
  • 支持自定义事件监听器
  • 跨浏览器兼容,特别优化了 Firefox

📦 安装

npm install wsse-sdk

🚀 快速开始

基础配置项

| 参数 | 说明 | 类型 | 默认值 | |------|------|------|--------| | url | 连接地址(必填) | string | - | | eventListeners | 后端自定义消息类型的监听器配置 | object | {} | | parseMessage | 是否自动解析消息 | boolean | false | | reconnectTime | 重连间隔(毫秒) | number | 60000 | | retryCount | 重试次数,设置为 0 可禁用自动重连 | number | 5 | | streamTimeout | 流式响应超时(毫秒),设置为 0 可禁用超时检测 | number | 300000 | | withCredentials | 是否发送凭证 | boolean | false | | debugger | 是否开启调试日志 | boolean | true | | autoReconnect | 是否启用自动重连 | boolean | true | | timeout | 连接建立超时时间(毫秒) | number | 5000 |

配置禁用说明:

  1. 禁用流式响应超时

    const aiChat = new WSSE({
      url: "https://api.ai-service.com/stream",
      streamTimeout: 0  // 设置为0即可禁用流式响应超时
    });
  2. 禁用自动重连

    const aiChat = new WSSE({
      url: "https://api.ai-service.com/stream",
      autoReconnect: false,  // 方式1:直接禁用自动重连
      retryCount: 0          // 方式2:设置重试次数为0
    });

基础用法

import WSSE from 'wsse-sdk';

const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  // 配置后端自定义消息类型的监听器
  eventListeners: {
    chat_response: (data) => {
      console.log('收到聊天响应:', data);
    },
    error_message: (data) => {
      console.log('收到错误消息:', data);
    }
  },
  parseMessage: true,                // 启用消息自动解析(默认关闭)
  streamTimeout: 300000,             // 流式响应5分钟超时
});

// 添加系统事件监听
aiChat.on({
  // 连接建立时触发
  open: () => console.log('连接已建立'),
  
  // 连接错误时触发
  error: (error) => console.error('连接错误:', error),

  // 默认消息处理器,处理所有未指定类型的消息
  message: (event) => {
    const data = JSON.parse(event.data);
    console.log('收到未指定类型的消息:', data);
    
    // 根据消息类型做不同处理
    switch(data.type) {
      case 'stream':
        console.log('流式响应片段:', data.content);
        break;
      case 'done':
        console.log('响应结束');
        break;
      default:
        console.log('其他类型消息:', data);
    }
  }
});

// 添加额外的自定义消息类型监听
aiChat.addMessageListener({
  status_update: (data) => {
    console.log('状态更新:', data);
  }
});

// 手动重连
await aiChat.reconnect();

// 关闭连接
aiChat.close();

消息处理

传递参数示例

import WSSE from 'wsse-sdk';

// 1. URL 参数方式
const aiChat1 = new WSSE({
  url: "https://api.ai-service.com/stream?userId=123&token=abc",
  eventListeners: {
    chat_response: (data) => console.log('收到响应:', data)
  }
});

// 2. URL 路径参数方式
const aiChat2 = new WSSE({
  url: "https://api.ai-service.com/stream/user/123",
  eventListeners: {
    chat_response: (data) => console.log('收到响应:', data)
  }
});

// 3. 跨域携带凭证方式
const aiChat3 = new WSSE({
  url: "https://api.ai-service.com/stream",
  withCredentials: true,  // 允许跨域请求携带 cookie
  eventListeners: {
    chat_response: (data) => console.log('收到响应:', data)
  }
});

// 4. 动态更新连接
let connectionUrl = "https://api.ai-service.com/stream";
const token = "user-token";

// 添加认证信息
const addAuthToUrl = (baseUrl, token) => {
  const url = new URL(baseUrl);
  url.searchParams.append('token', token);
  return url.toString();
}

const aiChat4 = new WSSE({
  url: addAuthToUrl(connectionUrl, token),
  eventListeners: {
    chat_response: (data) => console.log('收到响应:', data)
  }
});

📖 高级功能

自动解析消息

SDK 默认不会自动解析消息,需要通过 parseMessage 配置项来开启。这样可以让用户更灵活地控制消息解析方式。

配置说明

// 手动解析消息(默认行为)
const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  eventListeners: {
    chat_response: (event) => {
      // 需要手动解析消息
      const data = JSON.parse(event.data);
      console.log('收到聊天响应:', data);
    }
  }
});

// 开启自动解析
const aiChatWithParse = new WSSE({
  url: "https://api.ai-service.com/stream",
  parseMessage: true,  // 开启自动解析
  eventListeners: {
    chat_response: (data) => {
      // data 已经是解析后的对象
      console.log('收到聊天响应:', data);
    }
  }
});

解析规则

  1. 自动解析开启 (parseMessage: true)
// 后端发送的原始消息
event.data = '{"type":"chat_response","content":"Hello","timestamp":1678234567890}'

// 监听器收到的数据(自动解析为对象)
{
  type: "chat_response",
  content: "Hello",
  timestamp: 1678234567890
}
  1. 自动解析关闭 (parseMessage: false)
// 监听器收到的是原始字符串
aiChat.on({
  message: (event) => {
    // 需要手动解析
    const data = JSON.parse(event.data);
    console.log(data);
  }
});

错误处理

  1. 解析失败处理
aiChat.on({
  message: (event) => {
    try {
      // 手动解析示例
      const data = parseMessage ? JSON.parse(event.data) : event.data;
      console.log('解析成功:', data);
    } catch (error) {
      console.error('消息解析失败:', error);
      // 保留原始数据
      console.log('原始数据:', event.data);
    }
  }
});
  1. 特殊格式处理
const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  parseMessage: true,
  eventListeners: {
    chat_response: (event) => {
      // 某些情况下可能需要特殊处理
      const rawData = event.data;
      let data;
      
      // 处理特殊格式
      if (rawData.startsWith('data: ')) {
        data = JSON.parse(rawData.slice(6));
      } else {
        data = JSON.parse(rawData);
      }
      
      console.log('处理后的数据:', data);
    }
  }
});

最佳实践

  1. 标准 JSON 格式
// 推荐的消息格式
{
  "type": "chat_response",      // 消息类型(必需)
  "content": "消息内容",        // 消息内容
  "timestamp": 1678234567890,   // 时间戳
  "metadata": {                 // 额外信息(可选)
    "messageId": "abc123",
    "status": "success"
  }
}
  1. 非标准格式处理
const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  parseMessage: false,  // 关闭自动解析
  eventListeners: {
    chat_response: (event) => {
      // 自定义解析逻辑
      const data = customParser(event.data);
      console.log('自定义解析结果:', data);
    }
  }
});

function customParser(rawData) {
  // 实现自定义解析逻辑
  // 返回解析后的数据
}

流式内容管理

获取当前流式内容

const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  eventListeners: {
    // 监听流式内容完成事件
    streamComplete: (content) => {
      console.log('完整的流式内容:', content);
    },
    // 监听消息入队事件
    messageQueued: (message) => {
      console.log('新消息已入队:', message);
    }
  }
});

错误处理最佳实践

const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  retryCount: 3,
  reconnectTime: 5000,
  eventListeners: {
    error_message: (error) => {
      switch(error.code) {
        case 'TOKEN_EXPIRED':
          // 处理 token 过期
          refreshToken().then(() => aiChat.reconnect());
          break;
        case 'RATE_LIMIT':
          // 处理限流
          console.warn('请求过于频繁,请稍后重试');
          break;
        default:
          // 其他错误处理
          console.error('发生错误:', error);
      }
    }
  }
});

// 手动重连时的错误处理
try {
  await aiChat.reconnect();
  console.log('重连成功');
} catch (error) {
  console.error('重连失败:', error);
}

状态管理

1. 消息过滤和转换

const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream",
  eventListeners: {
    chat_response: (message) => {
      // 过滤特定类型的消息
      if (message.type === 'thought') {
        return; // 忽略思考过程
      }
      
      // 转换消息格式
      const transformedMessage = {
        content: message.content,
        timestamp: Date.now(),
        formatted: true
      };
      
      console.log('处理后的消息:', transformedMessage);
    }
  }
});

2. 连接状态管理

const aiChat = new WSSE({
  url: "https://api.ai-service.com/stream"
});

// 监听连接状态变化
aiChat.on({
  open: () => {
    console.log('连接状态:', aiChat.state); // WSSE.STATE_OPEN
    console.log('是否正在重连:', aiChat.isReconnecting);
    console.log('是否正在连接:', aiChat.isConnecting);
  }
});

// 状态常量
console.log('连接中:', WSSE.STATE_CONNECTING);    // 0
console.log('已连接:', WSSE.STATE_OPEN);          // 1
console.log('已关闭:', WSSE.STATE_CLOSED);        // 2

连接管理注意事项

  1. 流式响应

    • 设置了5分钟的默认超时时间
    • 超时后会触发 streamTimeout 事件
  2. 自动重连

    • 连接断开后自动重试
    • 可配置重试次数和间隔时间
  3. 消息类型监听

    • eventListeners 用于配置后端自定义的消息类型监听器
    • on 方法用于监听系统事件(如 open、error)
    • addMessageListener 用于动态添加自定义消息类型监听器

性能优化建议

  1. 重连策略优化

    • 根据实际需求设置 retryCount
    • 避免过于频繁的重连尝试
  2. 内存管理

    • 及时调用 close() 释放资源
    • 清理不需要的消息监听器

⚠️ 使用注意事项

参数传递注意事项

  1. URL 参数传递

    // 推荐:构建 URL 时使用 URLSearchParams
    const params = new URLSearchParams({
      userId: '123',
      token: 'abc',
      timestamp: Date.now()
    });
       
    const aiChat = new WSSE({
      url: `https://api.ai-service.com/stream?${params.toString()}`
    });
  2. 认证信息传递

    // 方式1:通过 URL 参数
    const aiChat1 = new WSSE({
      url: "https://api.ai-service.com/stream?token=abc"
    });
    
    // 方式2:通过 cookie(需要后端支持)
    const aiChat2 = new WSSE({
      url: "https://api.ai-service.com/stream",
      withCredentials: true  // 允许跨域请求携带 cookie
    });
  3. 动态参数处理

    class ChatService {
      constructor(baseUrl) {
        this.baseUrl = baseUrl;
        this.sseInstance = null;
      }
    
      connect(params = {}) {
        // 构建URL
        const url = new URL(this.baseUrl);
        Object.entries(params).forEach(([key, value]) => {
          url.searchParams.append(key, value);
        });
    
        // 创建SSE实例
        this.sseInstance = new WSSE({
          url: url.toString(),
          eventListeners: {
            chat_response: this.handleResponse.bind(this)
          }
        });
      }
    
      handleResponse(data) {
        console.log('收到响应:', data);
      }
    
      disconnect() {
        this.sseInstance?.close();
      }
    }
    
    // 使用示例
    const chatService = new ChatService('https://api.ai-service.com/stream');
    chatService.connect({
      userId: '123',
      token: 'abc',
      timestamp: Date.now()
    });

连接管理注意事项

  1. 流式响应

    • 设置了5分钟的默认超时时间
    • 超时后会触发 streamTimeout 事件
  2. 自动重连

    • 连接断开后自动重试
    • 可配置重试次数和间隔时间
  3. 消息类型监听

    • eventListeners 用于配置后端自定义的消息类型监听器
    • on 方法用于监听系统事件(如 open、error)
    • addMessageListener 用于动态添加自定义消息类型监听器
  4. 消息处理

    • 后端发送的消息需要指定 type 字段
    • type 字段值需要与监听器配置的键名一致

性能优化建议

  1. 重连策略优化

    • 根据实际需求设置 retryCount
    • 避免过于频繁的重连尝试
  2. 内存管理

    • 及时调用 close() 释放资源
    • 清理不需要的消息监听器

📱 系统要求

浏览器兼容性

  • Chrome 92+
  • Firefox 90+
  • Safari 14.1+
  • Edge 92+

📄 许可证

MIT