XuqmGroup-Web/docs-site/docs/public/h5-sdk/index.umd.js

8 行
18 KiB
JavaScript

(function(i,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(i=typeof globalThis<"u"?globalThis:i||self,m(i.XuqmH5SDK={}))})(this,(function(i){"use strict";let m="",I=()=>null;function le(n,e){m=n.replace(/\/$/,""),I=e}function pe(n,e){if(!e)return`${m}${n}`;const t=new URLSearchParams;for(const[o,u]of Object.entries(e))u==null||u===""||t.set(o,u instanceof Date?u.toISOString():String(u));const s=t.toString();return s?`${m}${n}?${s}`:`${m}${n}`}async function v(n,e,t,s){const o=I(),u={"Content-Type":"application/json"};o&&(u.Authorization=`Bearer ${o}`);const d=await(await fetch(pe(e,s),{method:n,headers:u,body:t!==void 0?JSON.stringify(t):void 0})).json();if(d.code!==200)throw new Error(d.message);return d.data}async function h(n){const e=I(),t=new FormData;t.append("file",n);const o=await(await fetch(`${m}/api/file/upload`,{method:"POST",headers:e?{Authorization:`Bearer ${e}`}:{},body:t})).json();if(o.code!==200)throw new Error(o.message);return o.data}const r={get:(n,e)=>v("GET",n,void 0,e),post:(n,e,t)=>v("POST",n,e,t),put:(n,e,t)=>v("PUT",n,e,t),delete:(n,e)=>v("DELETE",n,void 0,e)},w="https://dev.xuqinmin.com",he="wss://dev.xuqinmin.com/ws/im";let b=null,R=null,T=null;function fe(n){b=n,le(n.baseUrl||w,()=>R),n.debug&&console.log("[XuqmSDK] initialized",n.appKey,"baseUrl=",n.baseUrl||w)}function y(n){R=n}function C(n){T=n}function E(){return R}function k(){return T}function ge(n,e){y(e),C(n)}function ve(){y(null),C(null)}function l(){if(!b)throw new Error("XuqmSDK not initialized. Call init() first.");return b}const Ie=3e4;function p(n,e,t){let s=n+`
`;for(const[o,u]of Object.entries(e))s+=`${o}:${u}
`;return s+=`
`,t&&(s+=t),s+="\0",s}function be(n){var me;const e=n.indexOf("\0");if(e<0)return null;const t=n.substring(0,e),s=t.indexOf(`
`);if(s<0)return null;const o=t.substring(0,s),u=t.substring(s+2),a=o.split(`
`).filter(g=>g.trim()!==""),d=((me=a[0])==null?void 0:me.trim())||"",de={};for(let g=1;g<a.length;g++){const G=a[g],M=G.indexOf(":");M>0&&(de[G.substring(0,M).trim()]=G.substring(M+1).trim())}return{command:d,headers:de,body:u}}class ${constructor(){this.ws=null,this.reconnectDelay=3e3,this.reconnectTimer=null,this.destroyed=!1,this.listeners={},this.subscriptionSeed=0,this.subscriptions=new Map}on(e,t){const s=this.listeners,o=s[e]??new Set;return o.add(t),s[e]=o,this}off(e,t){var s;return(s=this.listeners[e])==null||s.delete(t),this}emit(e,...t){var s;(s=this.listeners[e])==null||s.forEach(o=>o(...t))}connect(){if(this.destroyed)return;const e=l(),t=E(),s=`${e.wsUrl||he}?token=${t??""}`;this.ws=new WebSocket(s);let o="";this.ws.onopen=()=>{var d;this.reconnectDelay=3e3,e.debug&&console.log("[ImClient] ws opened, sending STOMP CONNECT");const u=new URL(s),a={"accept-version":"1.2","heart-beat":"0,0",host:u.hostname+(u.port?":"+u.port:"")};t&&(a.Authorization=`Bearer ${t}`),(d=this.ws)==null||d.send(p("CONNECT",a))},this.ws.onmessage=u=>{o+=u.data;let a;for(;(a=be(o))!==null;)o=o.substring(o.indexOf("\0")+1),this.handleStompFrame(a,e)},this.ws.onclose=u=>{this.emit("disconnected",u.code,u.reason),this.destroyed||this.scheduleReconnect()},this.ws.onerror=u=>{this.emit("error",u)}}handleStompFrame(e,t){const s=e.command.toUpperCase();switch(t.debug&&console.log(`[ImClient] STOMP ${s}`,e.headers),s){case"CONNECTED":{t.debug&&console.log("[ImClient] STOMP connected"),this.sendSubscribe("/user/queue/messages"),this.subscriptions.forEach((o,u)=>{var a;u!=="/user/queue/messages"&&((a=this.ws)==null||a.send(p("SUBSCRIBE",{id:o,destination:u})))}),this.sendSync(),this.emit("connected");break}case"MESSAGE":{try{const o=this.normalizeMessage(JSON.parse(e.body));t.debug&&console.log("[ImClient] MESSAGE",o.id,o.msgType,o.status),o.status==="READ"&&this.emit("read",o),(o.revoked||o.status==="REVOKED"||o.msgType==="REVOKED")&&this.emit("revoke",{msgId:o.id,operatorId:o.fromId??o.fromUserId}),this.emit("message",o),this.emit("conversations")}catch{}break}case"ERROR":{const o=e.body||e.headers.message||"STOMP error";t.debug&&console.error("[ImClient] STOMP ERROR",o),this.emit("error",new Event(o));break}}}send(e){var d;const t=l(),s=k()??"",o=e.messageId??this.generateMessageId(),u={id:o,appId:t.appKey,fromUserId:s,fromId:s,toId:e.toId,chatType:e.chatType,msgType:e.msgType,content:e.content,status:"SENDING",mentionedUserIds:e.mentionedUserIds,revoked:!1,createdAt:new Date().toISOString()};if(((d=this.ws)==null?void 0:d.readyState)!==WebSocket.OPEN)return{...u,status:"FAILED"};const a={appId:t.appKey,messageId:o,toId:e.toId,chatType:e.chatType,msgType:e.msgType,content:e.content};return e.mentionedUserIds&&(a.mentionedUserIds=e.mentionedUserIds),this.ws.send(p("SEND",{destination:"/app/chat.send","content-type":"application/json"},JSON.stringify(a))),u}revoke(e){var s;if(((s=this.ws)==null?void 0:s.readyState)!==WebSocket.OPEN)throw new Error("WebSocket not connected");const t=l();this.ws.send(p("SEND",{destination:"/app/chat.revoke","content-type":"application/json"},JSON.stringify({appId:t.appKey,messageId:e})))}sync(){this.sendSync()}sendSync(){var t;if(((t=this.ws)==null?void 0:t.readyState)!==WebSocket.OPEN)return;const e=l();this.ws.send(p("SEND",{destination:"/app/chat.sync","content-type":"application/json"},JSON.stringify({appId:e.appKey})))}subscribe(e){this.subscriptions.has(e)||this.sendSubscribe(e)}sendSubscribe(e,t){var o;const s=t??this.nextSubscriptionId();this.subscriptions.set(e,s),(o=this.ws)==null||o.send(p("SUBSCRIBE",{id:s,destination:e}))}disconnect(){var e,t;this.destroyed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(p("DISCONNECT",{})),(t=this.ws)==null||t.close(),this.ws=null,this.subscriptions.clear()}scheduleReconnect(){this.destroyed||(l().debug&&console.log(`[ImClient] reconnect in ${this.reconnectDelay}ms`),this.reconnectTimer=setTimeout(()=>{this.connect(),this.reconnectDelay=Math.min(this.reconnectDelay*2,Ie)},this.reconne