Gathering detailed insights and metrics for wsse-sdk
Gathering detailed insights and metrics for wsse-sdk
Gathering detailed insights and metrics for wsse-sdk
Gathering detailed insights and metrics for wsse-sdk
npm install wsse-sdk
Typescript
Module System
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
专门用于 AI 流式输出和站内消息广播的 SSE(Server-Sent Events)长连接管理 SDK。提供了完整的事件监听、自动重连和消息处理机制,特别适合 AI 对话、实时通知等场景。
1npm 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 |
配置禁用说明:
禁用流式响应超时
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 streamTimeout: 0 // 设置为0即可禁用流式响应超时 4});
禁用自动重连
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 autoReconnect: false, // 方式1:直接禁用自动重连 4 retryCount: 0 // 方式2:设置重试次数为0 5});
1import WSSE from 'wsse-sdk'; 2 3const aiChat = new WSSE({ 4 url: "https://api.ai-service.com/stream", 5 // 配置后端自定义消息类型的监听器 6 eventListeners: { 7 chat_response: (data) => { 8 console.log('收到聊天响应:', data); 9 }, 10 error_message: (data) => { 11 console.log('收到错误消息:', data); 12 } 13 }, 14 parseMessage: true, // 启用消息自动解析(默认关闭) 15 streamTimeout: 300000, // 流式响应5分钟超时 16}); 17 18// 添加系统事件监听 19aiChat.on({ 20 // 连接建立时触发 21 open: () => console.log('连接已建立'), 22 23 // 连接错误时触发 24 error: (error) => console.error('连接错误:', error), 25 26 // 默认消息处理器,处理所有未指定类型的消息 27 message: (event) => { 28 const data = JSON.parse(event.data); 29 console.log('收到未指定类型的消息:', data); 30 31 // 根据消息类型做不同处理 32 switch(data.type) { 33 case 'stream': 34 console.log('流式响应片段:', data.content); 35 break; 36 case 'done': 37 console.log('响应结束'); 38 break; 39 default: 40 console.log('其他类型消息:', data); 41 } 42 } 43}); 44 45// 添加额外的自定义消息类型监听 46aiChat.addMessageListener({ 47 status_update: (data) => { 48 console.log('状态更新:', data); 49 } 50}); 51 52// 手动重连 53await aiChat.reconnect(); 54 55// 关闭连接 56aiChat.close();
1import WSSE from 'wsse-sdk'; 2 3// 1. URL 参数方式 4const aiChat1 = new WSSE({ 5 url: "https://api.ai-service.com/stream?userId=123&token=abc", 6 eventListeners: { 7 chat_response: (data) => console.log('收到响应:', data) 8 } 9}); 10 11// 2. URL 路径参数方式 12const aiChat2 = new WSSE({ 13 url: "https://api.ai-service.com/stream/user/123", 14 eventListeners: { 15 chat_response: (data) => console.log('收到响应:', data) 16 } 17}); 18 19// 3. 跨域携带凭证方式 20const aiChat3 = new WSSE({ 21 url: "https://api.ai-service.com/stream", 22 withCredentials: true, // 允许跨域请求携带 cookie 23 eventListeners: { 24 chat_response: (data) => console.log('收到响应:', data) 25 } 26}); 27 28// 4. 动态更新连接 29let connectionUrl = "https://api.ai-service.com/stream"; 30const token = "user-token"; 31 32// 添加认证信息 33const addAuthToUrl = (baseUrl, token) => { 34 const url = new URL(baseUrl); 35 url.searchParams.append('token', token); 36 return url.toString(); 37} 38 39const aiChat4 = new WSSE({ 40 url: addAuthToUrl(connectionUrl, token), 41 eventListeners: { 42 chat_response: (data) => console.log('收到响应:', data) 43 } 44});
SDK 默认不会自动解析消息,需要通过 parseMessage
配置项来开启。这样可以让用户更灵活地控制消息解析方式。
1// 手动解析消息(默认行为) 2const aiChat = new WSSE({ 3 url: "https://api.ai-service.com/stream", 4 eventListeners: { 5 chat_response: (event) => { 6 // 需要手动解析消息 7 const data = JSON.parse(event.data); 8 console.log('收到聊天响应:', data); 9 } 10 } 11}); 12 13// 开启自动解析 14const aiChatWithParse = new WSSE({ 15 url: "https://api.ai-service.com/stream", 16 parseMessage: true, // 开启自动解析 17 eventListeners: { 18 chat_response: (data) => { 19 // data 已经是解析后的对象 20 console.log('收到聊天响应:', data); 21 } 22 } 23});
1// 后端发送的原始消息 2event.data = '{"type":"chat_response","content":"Hello","timestamp":1678234567890}' 3 4// 监听器收到的数据(自动解析为对象) 5{ 6 type: "chat_response", 7 content: "Hello", 8 timestamp: 1678234567890 9}
1// 监听器收到的是原始字符串 2aiChat.on({ 3 message: (event) => { 4 // 需要手动解析 5 const data = JSON.parse(event.data); 6 console.log(data); 7 } 8});
1aiChat.on({ 2 message: (event) => { 3 try { 4 // 手动解析示例 5 const data = parseMessage ? JSON.parse(event.data) : event.data; 6 console.log('解析成功:', data); 7 } catch (error) { 8 console.error('消息解析失败:', error); 9 // 保留原始数据 10 console.log('原始数据:', event.data); 11 } 12 } 13});
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 parseMessage: true, 4 eventListeners: { 5 chat_response: (event) => { 6 // 某些情况下可能需要特殊处理 7 const rawData = event.data; 8 let data; 9 10 // 处理特殊格式 11 if (rawData.startsWith('data: ')) { 12 data = JSON.parse(rawData.slice(6)); 13 } else { 14 data = JSON.parse(rawData); 15 } 16 17 console.log('处理后的数据:', data); 18 } 19 } 20});
1// 推荐的消息格式 2{ 3 "type": "chat_response", // 消息类型(必需) 4 "content": "消息内容", // 消息内容 5 "timestamp": 1678234567890, // 时间戳 6 "metadata": { // 额外信息(可选) 7 "messageId": "abc123", 8 "status": "success" 9 } 10}
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 parseMessage: false, // 关闭自动解析 4 eventListeners: { 5 chat_response: (event) => { 6 // 自定义解析逻辑 7 const data = customParser(event.data); 8 console.log('自定义解析结果:', data); 9 } 10 } 11}); 12 13function customParser(rawData) { 14 // 实现自定义解析逻辑 15 // 返回解析后的数据 16}
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 eventListeners: { 4 // 监听流式内容完成事件 5 streamComplete: (content) => { 6 console.log('完整的流式内容:', content); 7 }, 8 // 监听消息入队事件 9 messageQueued: (message) => { 10 console.log('新消息已入队:', message); 11 } 12 } 13});
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 retryCount: 3, 4 reconnectTime: 5000, 5 eventListeners: { 6 error_message: (error) => { 7 switch(error.code) { 8 case 'TOKEN_EXPIRED': 9 // 处理 token 过期 10 refreshToken().then(() => aiChat.reconnect()); 11 break; 12 case 'RATE_LIMIT': 13 // 处理限流 14 console.warn('请求过于频繁,请稍后重试'); 15 break; 16 default: 17 // 其他错误处理 18 console.error('发生错误:', error); 19 } 20 } 21 } 22}); 23 24// 手动重连时的错误处理 25try { 26 await aiChat.reconnect(); 27 console.log('重连成功'); 28} catch (error) { 29 console.error('重连失败:', error); 30}
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream", 3 eventListeners: { 4 chat_response: (message) => { 5 // 过滤特定类型的消息 6 if (message.type === 'thought') { 7 return; // 忽略思考过程 8 } 9 10 // 转换消息格式 11 const transformedMessage = { 12 content: message.content, 13 timestamp: Date.now(), 14 formatted: true 15 }; 16 17 console.log('处理后的消息:', transformedMessage); 18 } 19 } 20});
1const aiChat = new WSSE({ 2 url: "https://api.ai-service.com/stream" 3}); 4 5// 监听连接状态变化 6aiChat.on({ 7 open: () => { 8 console.log('连接状态:', aiChat.state); // WSSE.STATE_OPEN 9 console.log('是否正在重连:', aiChat.isReconnecting); 10 console.log('是否正在连接:', aiChat.isConnecting); 11 } 12}); 13 14// 状态常量 15console.log('连接中:', WSSE.STATE_CONNECTING); // 0 16console.log('已连接:', WSSE.STATE_OPEN); // 1 17console.log('已关闭:', WSSE.STATE_CLOSED); // 2
流式响应
自动重连
消息类型监听
重连策略优化
内存管理
URL 参数传递
1// 推荐:构建 URL 时使用 URLSearchParams 2const params = new URLSearchParams({ 3 userId: '123', 4 token: 'abc', 5 timestamp: Date.now() 6}); 7 8const aiChat = new WSSE({ 9 url: `https://api.ai-service.com/stream?${params.toString()}` 10});
认证信息传递
1// 方式1:通过 URL 参数 2const aiChat1 = new WSSE({ 3 url: "https://api.ai-service.com/stream?token=abc" 4}); 5 6// 方式2:通过 cookie(需要后端支持) 7const aiChat2 = new WSSE({ 8 url: "https://api.ai-service.com/stream", 9 withCredentials: true // 允许跨域请求携带 cookie 10});
动态参数处理
1class ChatService { 2 constructor(baseUrl) { 3 this.baseUrl = baseUrl; 4 this.sseInstance = null; 5 } 6 7 connect(params = {}) { 8 // 构建URL 9 const url = new URL(this.baseUrl); 10 Object.entries(params).forEach(([key, value]) => { 11 url.searchParams.append(key, value); 12 }); 13 14 // 创建SSE实例 15 this.sseInstance = new WSSE({ 16 url: url.toString(), 17 eventListeners: { 18 chat_response: this.handleResponse.bind(this) 19 } 20 }); 21 } 22 23 handleResponse(data) { 24 console.log('收到响应:', data); 25 } 26 27 disconnect() { 28 this.sseInstance?.close(); 29 } 30} 31 32// 使用示例 33const chatService = new ChatService('https://api.ai-service.com/stream'); 34chatService.connect({ 35 userId: '123', 36 token: 'abc', 37 timestamp: Date.now() 38});
流式响应
自动重连
消息类型监听
消息处理
重连策略优化
内存管理
MIT
No vulnerabilities found.
No security vulnerabilities found.