UNPKG

kichat.js

Version:

A JavaScript library to connect to Kick.com chat.

3 lines (2 loc) 9.96 kB
var p=Object.create;var u=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var C=(r,n)=>()=>(n||r((n={exports:{}}).exports,n),n.exports);var K=(r,n,i,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of f(n))!k.call(r,t)&&t!==i&&u(r,t,{get:()=>n[t],enumerable:!(s=E(n,t))||s.enumerable});return r};var S=(r,n,i)=>(i=r!=null?p(g(r)):{},K(n||!r||!r.__esModule?u(i,"default",{value:r,enumerable:!0}):i,r));var v=C((y,b)=>{"use strict";b.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var o=class{info;chatroom;connectionNotified=!1;constructor(n,i){this.info=n,this.chatroom=i}get id(){return this.info.id}get name(){return this.info.user.username}get slug(){return this.info.slug}get chatroomId(){return this.info.chatroom.id}get notified(){return this.connectionNotified}set notified(n){this.connectionNotified=n}static toLogin(n){let i=n.trim().toLowerCase();return i.startsWith("#")?i.slice(1):i}toString(){return this.name}};var d=class{listeners=new Map;on(n,i){return this.listeners.has(n)||this.listeners.set(n,new Set),this.listeners.get(n).add(i),this}off(n,i){return this.listeners.get(n)?.delete(i),this}emit(n,...i){if(!this.listeners.has(n)){if(n==="error")throw i[0]instanceof Error?i[0]:new Error("Uncaught error emitted",{cause:i[0]});return!1}for(let s of this.listeners.get(n))s(...i);return!0}};var a=r=>{try{return JSON.parse(r)}catch{return null}},w="wss://ws-us2.pusher.com/app/32cbd69e4b950bf97679",l=class extends d{socket;wasCloseCalled=!1;reconnectAttempts=0;pingInterval;socketSession={activity_timeout:120,socket_id:""};reconnectEnabled;reconnectMaxAttempts;reconnectInitialTimeout;reconnectMaxTimeout;channels=new Map;channelsByChatroomId=new Map;subscribePusher;constructor(n={}){super(),this.reconnectEnabled=n.reconnect??!0,this.reconnectMaxAttempts=n?.reconnectMaxAttempts??1/0,this.reconnectInitialTimeout=n?.reconnectInitialTimeout??1e3,this.reconnectMaxTimeout=n?.reconnectMaxTimeout??6e4,this.subscribePusher=n?.subscribePusher??{channel:!0,chatRoom:!0,predictions:!0},n.channels&&n.channels.forEach(i=>this.join(i))}isConnected(){return this.socket?.readyState===1}connect(){if(this.isConnected())throw new Error("Client is already connected.");this.wasCloseCalled=!1,this.createWebSocket().catch(n=>this.emit("socketError",n))}async createWebSocket(){let n=new URLSearchParams({protocol:"7",client:"js",version:"7.4.0",flash:"false"}),i=`${w}?${n.toString()}`;if(typeof window<"u"&&typeof window.WebSocket<"u")this.socket=new window.WebSocket(i),this.socket.onerror=s=>{},this.socket.onopen=()=>this.onSocketOpen(),this.socket.onmessage=s=>this.onSocketMessage(s.data),this.socket.onclose=s=>this.onSocketClose(s.code,s.reason),this.socket.onerror=()=>this.onSocketError(new Error("WebSocket error"));else{let{default:s}=await Promise.resolve().then(()=>S(v(),1));this.socket=new s(i),this.socket.onerror=t=>{},this.socket.on("open",()=>this.onSocketOpen()),this.socket.on("message",t=>this.onSocketMessage(t)),this.socket.on("close",(t,e)=>this.onSocketClose(t,e.toString())),this.socket.on("socketError",t=>this.onSocketError(t))}}close(){this.socket&&(this.wasCloseCalled=!0,this.socket.close())}async reconnect(){if(this.isConnected()&&this.socket.close(),this.reconnectAttempts>=this.reconnectMaxAttempts){this.emit("socketError",new Error("Maximum reconnect attempts reached."));return}this.reconnectAttempts++;let n=Math.min(this.reconnectInitialTimeout*1.23**this.reconnectAttempts,this.reconnectMaxTimeout);this.emit("reconnecting"),await new Promise(i=>setTimeout(i,n)),this.connect()}onSocketOpen(){this.reconnectAttempts=0,this.channels.forEach(n=>this.subscribeToChannel(n))}onSocketClose(n,i){clearInterval(this.pingInterval),!this.wasCloseCalled&&this.reconnectEnabled?this.reconnect():this.emit("disconnected",i||`Socket closed with code ${n}`)}onSocketError(n){this.emit("socketError",n)}onSocketMessage(n){let i=n.toString();this.emit("raw",i);let s=a(i);if(!s)return;let t;if(s.channel){let e=s.channel.match(/(\d{5,})/);if(e){let c=parseInt(e[1],10);Array.from(this.channelsByChatroomId.entries()).forEach(([m,h])=>{(h.chatroomId==c||h.id==c)&&(t=this.channelsByChatroomId.get(h.chatroomId))})}}switch(s.event){case"pusher:connection_established":{let e=a(s.data);e&&(this.socketSession=e,this.startPing(),this.emit("connected"));break}case"pusher_internal:subscription_succeeded":{t?.notified==!1&&(this.channels.get(t.slug).notified=!0,this.emit("join",t));break}case"pusher:pong":break;case"pusher:error":{a(s.data)?.code===4200&&this.reconnect();break}case"App\\Events\\ChatMessageEvent":{let e=a(s.data);e&&t&&this.emit("message",e,t);break}case"App\\Events\\SubscriptionEvent":{let e=a(s.data);e&&t&&this.emit("subscription",e,t);break}case"GiftedSubscriptionsEvent":{let e=a(s.data);e&&t&&this.emit("giftedSubscriptions",e,t);break}case"App\\Events\\StreamHostEvent":{let e=a(s.data);e&&t&&this.emit("streamHost",e,t);break}case"App\\Events\\UserBannedEvent":{let e=a(s.data);e&&t&&this.emit("userBanned",e,t);break}case"App\\Events\\UserUnbannedEvent":{let e=a(s.data);e&&t&&this.emit("userUnbanned",e,t);break}case"App\\Events\\MessageDeletedEvent":{let e=a(s.data);e&&t&&this.emit("messageDeleted",e,t);break}case"App\\Events\\PinnedMessageCreatedEvent":{let e=a(s.data);e&&t&&this.emit("pinnedMessageCreated",e,t);break}case"App\\Events\\PinnedMessageDeletedEvent":{let e=a(s.data);e&&t&&this.emit("pinnedMessageDeleted",e,t);break}case"App\\Events\\ChatroomUpdatedEvent":{let e=a(s.data);e&&t&&this.emit("chatroomUpdated",e,t);break}case"App\\Events\\PollUpdateEvent":{let e=a(s.data);e&&t&&this.emit("pollUpdate",e,t);break}case"App\\Events\\PollDeleteEvent":{t&&this.emit("pollDelete",t);break}case"App\\Events\\StreamerIsLive":{let e=a(s.data);e&&t&&this.emit("streamerIsLive",e,t);break}case"App\\Events\\StopStreamBroadcast":{let e=a(s.data);e&&t&&this.emit("stopStreamBroadcast",e,t);break}case"GoalCreatedEvent":{let e=a(s.data);e&&t&&this.emit("goalCreated",e,t);break}case"GoalCanceledEvent":{let e=a(s.data);e&&t&&this.emit("goalCanceled",e,t);break}case"GoalProgressUpdateEvent":{let e=a(s.data);e&&t&&this.emit("goalProgressUpdate",e,t);break}case"App\\Events\\LivestreamUpdated":{let e=a(s.data);e&&t&&this.emit("livestreamUpdated",e,t);break}case"PredictionCreated":{let e=a(s.data);e&&t&&this.emit("predictionCreated",e,t);break}case"PredictionUpdated":{let e=a(s.data);e&&t&&this.emit("predictionUpdated",e,t);break}case"RewardRedeemedEvent":{let e=a(s.data);e&&t&&this.emit("rewardRedeemed",e,t);break}case"App\\Events\\ChannelSubscriptionEvent":{let e=a(s.data);e&&t&&this.emit("channelSubscription",e,t);break}case"App\\Events\\LuckyUsersWhoGotGiftSubscriptionsEvent":{let e=a(s.data);e&&t&&this.emit("luckyUsersWhoGotGiftSubscriptions",e,t);break}case"App\\Events\\VideoPrivatedEvent":{let e=a(s.data);e&&t&&this.emit("videoPrivated",e,t);break}case"GiftsLeaderboardUpdated":{let e=a(s.data);e&&t&&this.emit("giftsLeaderboardUpdated",e,t);break}case"App\\Events\\ChatMoveToSupportedChannelEvent":{let e=a(s.data);e&&t&&this.emit("chatMoveToSupportedChannel",e,t);break}}}sendPusher(n,i="subscribe"){this.isConnected()&&this.socket.send(JSON.stringify({event:`pusher:${i}`,data:{auth:"",channel:n}}))}startPing(){clearInterval(this.pingInterval),this.pingInterval=setInterval(()=>{this.isConnected()&&this.socket.send(JSON.stringify({event:"pusher:ping",data:{}}))},this.socketSession.activity_timeout*1e3)}subscribeToChannel(n){this.subscribePusher?.chatRoom==!0&&this.sendPusher(`chatrooms.${n.chatroomId}.v2`),this.subscribePusher?.chatRoom==!0&&this.sendPusher(`chatroom_${n.chatroomId}`),this.subscribePusher?.channel==!0&&this.sendPusher(`channel_${n.id}`),this.subscribePusher?.channel==!0&&this.sendPusher(`channel.${n.id}`),this.subscribePusher?.predictions==!0&&this.sendPusher(`predictions-channel-${n.id}`)}async fetchUserInfo(n){let i=o.toLogin(n),s=await fetch(`https://kick.com/api/v2/channels/${i}/info`,{cache:"no-cache"});if(s.ok)return await s.json()}async fetchChatRoom(n){let i=o.toLogin(n),s=await fetch(`https://kick.com/api/v2/channels/${i}/info`,{cache:"no-cache"});if(s.ok)return await s.json()}async join(n){let i=o.toLogin(n);if(this.channels.has(i))return this.channels.get(i);try{let s=await this.fetchUserInfo(i);if(!s)throw new Error(`Failed to fetch channel info for ${i}`);let t=await this.fetchChatRoom(i);if(!t)throw new Error(`Failed to fetch chatroom info for ${i}`);let e=new o(s,t);return this.channels.set(i,e),this.channelsByChatroomId.set(e.chatroomId,e),this.isConnected()&&this.subscribeToChannel(e),await this.waitForEvent("join",m=>m.slug===i)}catch(s){this.channels.delete(i);let t=Array.from(this.channelsByChatroomId.values()).find(e=>e.slug===i);throw t&&this.channelsByChatroomId.delete(t.chatroomId),this.emit("socketError",s),s}}leave(n){let i=o.toLogin(n),s=this.channels.get(i);s&&(this.isConnected()&&(this.subscribePusher?.chatRoom==!0&&this.sendPusher(`chatrooms.${s.chatroomId}.v2`,"unsubscribe"),this.subscribePusher?.chatRoom==!0&&this.sendPusher(`chatroom_${s.chatroomId}`,"unsubscribe"),this.subscribePusher?.channel==!0&&this.sendPusher(`channel_${s.id}`,"unsubscribe"),this.subscribePusher?.channel==!0&&this.sendPusher(`channel.${s.id}`,"unsubscribe"),this.subscribePusher?.predictions==!0&&this.sendPusher(`predictions-channel-${s.id}`,"unsubscribe")),this.channels.delete(i),this.channelsByChatroomId.delete(s.chatroomId),this.emit("leave",s,"Disconnected by user"))}waitForEvent(n,i,s=1e4){return new Promise((t,e)=>{let c=(...h)=>{i(...h)&&(this.off(n,c),clearTimeout(m),t(h[0]))},m=setTimeout(()=>{this.off(n,c),e(new Error(`Timed out waiting for event: ${n}`))},s);this.on(n,c)})}};var B={KiChatjs:l};export{o as KiChannel,l as KiChatjs,B as default}; //# sourceMappingURL=kichat.js.browser.min.mjs.map