UNPKG

twitch-js

Version:

Javascript library for the Twitch Messaging Interface.

3 lines (2 loc) 46.9 kB
import t from"eventemitter3";import e from"delay";import n from"p-cancelable";import r from"p-event";import o from"p-timeout";import i from"lodash/uniq";import s from"pino";import a from"ws";import u from"p-queue";import{parse as c}from"tekko/dist/parse";import E from"camelcase-keys";import _ from"lodash/isEmpty";import h from"lodash/toLower";import O from"invariant";import l from"lodash/conformsTo";import S from"lodash/defaults";import p from"lodash/isString";import d from"lodash/isFinite";import f from"lodash/isBoolean";import T from"lodash/isNil";import N from"lodash/random";import{CustomError as m}from"ts-custom-error";import A from"lodash/gt";import I from"lodash/toNumber";import v from"lodash/toUpper";import C from"lodash/camelCase";import R from"lodash/replace";import y from"lodash/isFunction";import D from"lodash/includes";import g from"cross-fetch";import U from"form-data";import{stringify as L}from"qs";import M from"lodash/isUndefined";var b=function(t,e){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function w(t,e){function n(){this.constructor=t}b(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var P,F,G,H,B,W,k,Y,j,V,x=function(){return(x=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function K(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]])}return n}function J(t,e,n,r){return new(n||(n=Promise))((function(o,i){function s(t){try{u(r.next(t))}catch(t){i(t)}}function a(t){try{u(r.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}u((r=r.apply(t,e||[])).next())}))}function q(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function z(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function Z(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(z(arguments[e]));return t}!function(t){t.Helix="helix",t.Kraken="kraken"}(P||(P={})),function(t){t.tags="twitch.tv/tags",t.commands="twitch.tv/commands",t.membership="twitch.tv/membership"}(F||(F={})),function(t){t.JOIN="JOIN",t.MODE="MODE",t.PART="PART",t.NAMES="353",t.NAMES_END="366"}(G||(G={})),function(t){t.CLEAR_CHAT="CLEARCHAT",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.PRIVATE_MESSAGE="PRIVMSG",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(H||(H={})),function(t){t.WELCOME="001",t.PING="PING",t.PONG="PONG",t.WHISPER="WHISPER"}(B||(B={})),function(t){t.CLEAR_CHAT="CLEARCHAT",t.CLEAR_MESSAGE="CLEARMSG",t.HOST_TARGET="HOSTTARGET",t.NOTICE="NOTICE",t.RECONNECT="RECONNECT",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(W||(W={})),function(t){t.WELCOME="001",t.PING="PING",t.PONG="PONG",t.RECONNECT="RECONNECT",t.WHISPER="PRIVMSG #jtv",t.JOIN="JOIN",t.MODE="MODE",t.PART="PART",t.NAMES="353",t.NAMES_END="366",t.CLEAR_CHAT="CLEARCHAT",t.CLEAR_MESSAGE="CLEARMSG",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.HOST_TARGET="HOSTTARGET",t.NOTICE="NOTICE",t.PRIVATE_MESSAGE="PRIVMSG",t.ROOM_STATE="ROOMSTATE",t.USER_NOTICE="USERNOTICE",t.USER_STATE="USERSTATE"}(k||(k={})),function(t){t.RAW="RAW",t.ALL="*",t.CONNECTED="CONNECTED",t.DISCONNECTED="DISCONNECTED",t.RECONNECT="RECONNECT",t.AUTHENTICATED="AUTHENTICATED",t.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED",t.GLOBALUSERSTATE="GLOBALUSERSTATE",t.ERROR_ENCOUNTERED="ERROR_ENCOUNTERED",t.PARSE_ERROR_ENCOUNTERED="PARSE_ERROR_ENCOUNTERED",t.ANON_GIFT_PAID_UPGRADE="ANON_GIFT_PAID_UPGRADE",t.GIFT_PAID_UPGRADE="GIFT_PAID_UPGRADE",t.RAID="RAID",t.RESUBSCRIPTION="RESUBSCRIPTION",t.RITUAL="RITUAL",t.SUBSCRIPTION="SUBSCRIPTION",t.SUBSCRIPTION_GIFT="SUBSCRIPTION_GIFT",t.SUBSCRIPTION_GIFT_COMMUNITY="SUBSCRIPTION_GIFT_COMMUNITY",t.ROOM_MODS="ROOM_MODS",t.MOD_GAINED="MOD_GAINED",t.MOD_LOST="MOD_LOST",t.USER_BANNED="USER_BANNED",t.CHEER="CHEER",t.HOST_ON="HOST_ON",t.HOST_OFF="HOST_OFF",t.HOSTED="HOSTED",t.HOSTED_WITHOUT_VIEWERS="HOSTED/WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="HOSTED/WITH_VIEWERS",t.HOSTED_AUTO="HOSTED/AUTO"}(Y||(Y={})),function(t){t.BAN="ban",t.BLOCK="block",t.CLEAR="clear",t.COLOR="color",t.COMMERCIAL="commercial",t.DELETE="delete",t.EMOTE_ONLY="emoteonly",t.EMOTE_ONLY_OFF="emoteonlyoff",t.FOLLOWERS_ONLY="followers",t.FOLLOWERS_ONLY_OFF="followersoff",t.HELP="help",t.HOST="host",t.MARKER="marker",t.ME="me",t.MOD="mod",t.MODS="mods",t.R9K="r9kbeta",t.R9K_OFF="r9kbetaoff",t.RAID="raid",t.SLOW="slow",t.SLOW_OFF="slowoff",t.SUBSCRIBERS="subscribers",t.SUBSCRIBERS_OFF="subscribersoff",t.TIMEOUT="timeout",t.UNBAN="unban",t.UNBLOCK="unblock",t.UNHOST="unhost",t.UNMOD="unmod",t.UNRAID="unraid",t.UNVIP="unvip",t.VIP="vip",t.VIPS="vips",t.WHISPER="w"}(j||(j={})),function(t){t.ALREADY_BANNED="already_banned",t.ALREADY_EMOTE_ONLY_OFF="already_emote_only_off",t.ALREADY_EMOTE_ONLY_ON="already_emote_only_on",t.ALREADY_R9K_OFF="already_r9k_off",t.ALREADY_R9K_ON="already_r9k_on",t.ALREADY_SUBS_OFF="already_subs_off",t.ALREADY_SUBS_ON="already_subs_on",t.BAD_HOST_HOSTING="bad_host_hosting",t.BAD_MOD_MOD="bad_mod_mod",t.BAN_SUCCESS="ban_success",t.BAD_UNBAN_NO_BAN="bad_unban_no_ban",t.COLOR_CHANGED="color_changed",t.CMDS_AVAILABLE="cmds_available",t.COMMERCIAL_SUCCESS="commercial_success",t.EMOTE_ONLY_OFF="emote_only_off",t.EMOTE_ONLY_ON="emote_only_on",t.FOLLOWERS_OFF="followers_off",t.FOLLOWERS_ON="followers_on",t.FOLLOWERS_ONZERO="followers_onzero",t.HOST_OFF="host_off",t.HOST_ON="host_on",t.HOSTS_REMAINING="hosts_remaining",t.MSG_CHANNEL_SUSPENDED="msg_channel_suspended",t.MOD_SUCCESS="mod_success",t.NOT_HOSTING="not_hosting",t.R9K_OFF="r9k_off",t.R9K_ON="r9k_on",t.ROOM_MODS="room_mods",t.SLOW_OFF="slow_off",t.SLOW_ON="slow_on",t.SUBS_OFF="subs_off",t.SUBS_ON="subs_on",t.TIMEOUT_SUCCESS="timeout_success",t.UNBAN_SUCCESS="unban_success",t.UNMOD_SUCCESS="unmod_success",t.UNRAID_SUCCESS="unraid_success",t.UNRECOGNIZED_CMD="unrecognized_cmd"}(V||(V={}));var Q,X,$=Object.entries(V).reduce((function(t,e){var n,r=z(e,2),o=r[0],i=r[1];return x(x({},t),((n={})[o]=i.toUpperCase(),n))}),{}),tt=Object.keys(V).reduce((function(t,e){var n;return x(x({},t),((n={})[e]=e,n[k.NOTICE+"/"+e.toUpperCase()]=e,n))}),{});!function(t){t.CHEER="CHEER",t.HOSTED_WITHOUT_VIEWERS="HOSTED_WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="HOSTED_WITH_VIEWERS",t.HOSTED_AUTO="HOSTED_AUTO"}(Q||(Q={})),function(t){t.ANON_GIFT_PAID_UPGRADE="anongiftpaidupgrade",t.GIFT_PAID_UPGRADE="giftpaidupgrade",t.RAID="raid",t.RESUBSCRIPTION="resub",t.RITUAL="ritual",t.SUBSCRIPTION="sub",t.SUBSCRIPTION_GIFT="subgift",t.SUBSCRIPTION_GIFT_COMMUNITY="submysterygift"}(X||(X={}));var et,nt,rt=Object.keys(X).reduce((function(t,e){var n;return x(x({},t),((n={})[e]=e,n[k.USER_NOTICE+"/"+e]=e,n))}),{}),ot=x(x(x(x(x(x(x(x({},G),H),B),W),Y),tt),Q),rt);!function(t){t[t.admin=0]="admin",t[t.broadcaster=1]="broadcaster",t[t.globalMod=2]="globalMod",t[t.moderator=3]="moderator",t[t.partner=4]="partner",t[t.premium=5]="premium",t[t.staff=6]="staff",t[t.subGifter=7]="subGifter",t[t.turbo=8]="turbo",t[t.vip=9]="vip"}(et||(et={})),function(t){t[t.bits=0]="bits",t[t.bitsLeader=1]="bitsLeader",t[t.subscriber=2]="subscriber"}(nt||(nt={}));var it,st=function(t){void 0===t&&(t={});var e=t.name,n=K(t,["name"]),r=["TwitchJS"].concat(e||[]).join("/"),o=s(x({name:r,prettyPrint:!0,level:"info"},n));return o.profile=function(t){var e=Date.now();return t&&o.info(t),{done:function(t,n){var r=t+" ("+(Date.now()-e)+"ms)";n?o.error(r,n):o.info(r)}}},o},at=function(t){var e=new Date(parseInt(t,10));return"Invalid Date"!==e.toString()?e:new Date},ut=function(t,e){return void 0===e&&(e=""),t.split(/\r?\n/g).reduce((function(t,n){if(!n.length)return t;var r=c(n),o=r.command,i=r.tags,s=void 0===i?{}:i,a=r.prefix,u=void 0===a?{name:void 0,user:void 0,host:void 0}:a,O=u.name,l=u.user,S=u.host,p=z(r.params,2),d=p[0],f=p[1],T=String(s["tmi-sent-ts"])||Date.now().toString(),N=_(s)?{}:E(s),m=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return t.reduce((function(t,e){return"string"!=typeof e?t:"tmi.twitch.tv"===e?"tmi.twitch.tv":h(e).split(".")[0]}),void 0)}(S,O,l,N.login,N.username,N.displayName);return Z(t,[{_raw:n,timestamp:at(T),command:o,event:o,channel:"*"!==d?d:"",username:m,isSelf:"string"==typeof m&&h(e)===m,tags:N,message:f}])}),[])},ct=function(t){return null==t?"TWITCHJS":t.startsWith("oauth:")?t:"oauth:"+t};!function(t){t.RAW="RAW",t.ALL="*",t.CONNECTED="CONNECTED",t.DISCONNECTED="DISCONNECTED",t.RECONNECT="RECONNECT",t.AUTHENTICATED="AUTHENTICATED",t.AUTHENTICATION_FAILED="AUTHENTICATION_FAILED",t.ERROR_ENCOUNTERED="ERROR_ENCOUNTERED"}(it||(it={}));var Et,_t,ht,Ot,lt,St=x(x({},k),it),pt=function(t){function e(e){var n=t.call(this)||this;n._clientPriority=100,n._options=function(t){var e,n={username:function(t){return T(t)||p(t)},token:function(t){return T(t)||p(t)},server:p,port:d,ssl:f,isKnown:f,isVerified:f},r=S(x(x({},t),{username:(e=t.username,_(e)||"justinfan"===e?"justinfan"+N(8e4,81e3):e),token:t.token?ct(t.token):void 0}),{server:"irc-ws.chat.twitch.tv",port:443,ssl:!0,isKnown:!1,isVerified:!1});return O(l(r,n),"[twitch-js/Chat/Client] options: Expected valid options"),r}(e);var r=n._options,o=r.ssl,i=r.server,s=r.port,c=r.log;n._log=st(x({name:"Chat/Client"},c));var E=o?"wss":"ws";return n._ws=new a(E+"://"+i+":"+s),n._ws.onopen=n._handleOpen.bind(n),n._ws.onmessage=n._handleMessage.bind(n),n._ws.onerror=n._handleError.bind(n),n._ws.onclose=n._handleClose.bind(n),n._queueAuthenticate=n._options.isVerified?new u({intervalCap:200,interval:1e4}):new u({intervalCap:20,interval:1e4}),n._queueJoin=n._options.isVerified?new u({intervalCap:2e3,interval:1e4}):new u({intervalCap:20,interval:1e4}),n._queue=new u({intervalCap:20,interval:3e4}),n._moderatorQueue=new u({intervalCap:100,interval:3e4}),n}return w(e,t),e.prototype.isReady=function(){return 1===this._ws.readyState},e.prototype.send=function(t,e){return J(this,void 0,void 0,(function(){var n,r,o,i=this;return q(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),n=x({priority:0,isModerator:!1},e),r=n.priority,o=n.isModerator,[4,(t.startsWith("JOIN")?this._queueJoin:t.startsWith("PASS")?this._queueAuthenticate:o&&this._moderatorQueue?this._moderatorQueue:this._queue).add((function(){return i._ws.send(t)}),{priority:r})];case 1:return s.sent(),this._log.trace("< "+t),[3,3];case 2:return s.sent(),this._log.error("< "+t),[3,3];case 3:return[2]}}))}))},e.prototype.disconnect=function(){var t,e;this._queueAuthenticate.pause(),this._queueJoin.pause(),this._queue.pause(),null===(t=this._moderatorQueue)||void 0===t||t.pause(),clearTimeout(this._queueAuthenticate._timeoutId),clearTimeout(this._queueJoin._timeoutId),clearTimeout(this._queue._timeoutId),clearTimeout(null===(e=this._moderatorQueue)||void 0===e?void 0:e._timeoutId),this._handleHeartbeatReset(),this._ws.close()},e.prototype._handleOpen=function(){var t=this._clientPriority;this.send("CAP REQ :"+Object.values(F).join(" "),{priority:t});var e=this._options,n=e.token,r=e.username;n&&r&&this.send("PASS "+n,{priority:t}),this.send("NICK "+r,{priority:t}),this._handleHeartbeat()},e.prototype._handleMessage=function(t){var e=this,n=t.data.toString();this._log.trace("> "+n.trim());var r=this._options,o=r.token,i=r.username,s=this._clientPriority;this._handleHeartbeat();var a=[];try{a=ut(n,this._options.username)}catch(t){this._log.error("\nAn error occurred while attempting to parse a message from Twitch. Please use the following stack trace and raw message to resolve the bug in the TwitchJS source code, and then issue a pull request at https://github.com/twitch-js/twitch-js/compare\n\nStack trace:\n"+t+"\n\nRaw message:\n"+n),this.emit(St.ERROR_ENCOUNTERED,t)}a.forEach((function(t){var n=t.command||"";e._log.debug(x(x({},t),{_raw:void 0}),"> %s",n),!function(t){return void 0!==t&&t.command===k.NOTICE&&""===t.channel&&"Login authentication failed"===t.message}(t)?t.command===k.PING?e.send("PONG :tmi.twitch.tv",{priority:s}):o||t.command!==k.WELCOME?t.command===k.GLOBALUSERSTATE?(e._multiEmit([St.ALL,St.GLOBALUSERSTATE],x(x({},t),{event:St.GLOBALUSERSTATE})),o&&i&&e._multiEmit([St.ALL,St.CONNECTED],x(x({},t),{event:St.CONNECTED}))):t.command===k.RECONNECT?e._multiEmit([St.ALL,St.RECONNECT],x(x({},t),{event:St.RECONNECT})):e.emit(St.ALL,t):e._multiEmit([St.ALL,St.CONNECTED],x(x({},t),{event:St.CONNECTED})):(e._multiEmit([St.ALL,St.AUTHENTICATION_FAILED],x(x({},t),{event:St.AUTHENTICATION_FAILED})),e.disconnect())})),this.emit(St.RAW,n)},e.prototype._handleError=function(t){this._log.error(t)},e.prototype._handleClose=function(t){this.emit(St.DISCONNECTED)},e.prototype._handleHeartbeat=function(){var t=this;this._handleHeartbeatReset();var e=this._clientPriority;this._heartbeatTimeoutId=setTimeout((function(){t.send(k.PING,{priority:e})}),15e4),this._reconnectTimeoutId=setTimeout((function(){t.emit(St.RECONNECT)}),151e3)},e.prototype._handleHeartbeatReset=function(){this._heartbeatTimeoutId&&clearTimeout(this._heartbeatTimeoutId),this._reconnectTimeoutId&&clearTimeout(this._reconnectTimeoutId)},e.prototype._multiEmit=function(t,e){var n=this;Array.isArray(t)?t.forEach((function(t){return n.emit(t,e)})):this.emit(t,e)},e}(t),dt=function(t){function e(e){var n=t.call(this,e)||this;return n.timestamp=new Date,n.message="[TwitchJS] "+e,n}return w(e,t),e}(m),ft=function(t){function e(n,r){var o=t.call(this,(n instanceof Error?n.message:n)+" [Chat]")||this;return Object.setPrototypeOf(o,e.prototype),void 0!==r&&"string"!=typeof r&&(o.command=r.command),o}return w(e,t),e}(dt),Tt=function(t){function e(n,r){var o=t.call(this,"Authentication error encountered",r)||this;return Object.setPrototypeOf(o,e.prototype),Object.assign(o,n),Object.assign(o,r),o}return w(e,t),e}(ft),Nt=(function(t){function e(n,r){var o=t.call(this,"Parse error encountered")||this;return Object.setPrototypeOf(o,e.prototype),Object.assign(o,n),o._raw=r,o.command=Y.PARSE_ERROR_ENCOUNTERED,o}w(e,t)}(ft),function(t){function e(n){void 0===n&&(n="Error: join");var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}w(e,t)}(ft),function(t){function e(n){void 0===n&&(n="Error: timeout");var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}w(e,t)}(ft),new RegExp("^msgParam(\\w+)")),mt=/:.+@jtv\.tmi\.twitch\.tv PRIVMSG #?(\w+) :(\w+) is now (?:(auto) )?hosting[A-z ]+(\d+)?/,At=function(t){return"string"==typeof t?R(t,/\\[sn]/g," "):void 0},It=function(t){var e=parseInt(t,10);return d(e)?e:void 0},vt=function(t){return"1"===t},Ct=function(t){return z(t.split(": "),2)[1].split(", ")},Rt=function(t){return Object.entries(t).reduce((function(t,e){var n,r,o,i,s,a,u=z(e,2),c=u[0],E=u[1];switch(c){case"followersOnly":return x(x({},t),((n={})[c]=0===(a=parseInt(E,10))||a>0&&a,n));case"broadcasterLang":return x(x({},t),((r={})[c]=At(E),r));case"slow":return x(x({},t),((o={})[c]=It(E),o));case"emoteOnly":case"r9k":case"subsOnly":return x(x({},t),((i={})[c]=vt(E),i));default:return x(x({},t),((s={})[c]=E,s))}}),{})},yt=function(t){return x(x({},t),{badges:(o=t.badges,"string"==typeof o?o.split(",").reduce((function(t,e){var n,r,o,i=z(e.split("/"),2),s=i[0],a=i[1];if(void 0===a)return t;var u=C(s);return x(x({},t),u in et?((n={})[u]=vt(a),n):u in nt?((r={})[u]=parseInt(a,10),r):((o={})[u]=a,o))}),{}):{}),bits:It(t.bits),color:t.color,displayName:t.displayName,emotes:(r=t.emotes,"string"!=typeof r?[]:r.split("/").reduce((function(t,e){var n=z(e.split(":"),2),r=n[0],o=n[1];return r?Z(t,o.split(",").map((function(t){var e=z(t.split("-"),2),n=e[0],o=e[1];return{id:r,start:parseInt(n,10),end:parseInt(o,10)}}))):t}),[])),emoteSets:(n=t.emoteSets,"string"==typeof n?n.split(","):[]),userType:(e=t.userType,"string"==typeof e?e:void 0),username:t.displayName?h(t.displayName):t.username,isModerator:"1"===t.mod});var e,n,r,o},Dt=function(t){return x(x({},t),yt(t))},gt=yt,Ut=function(t){var e,n=t.tags,r=K(t,["tags"]),o=void 0!==(e=t)&&e.command===k.NOTICE&&""===e.channel&&"Login authentication failed"===e.message?x(x({},n),{msgId:h(ot.AUTHENTICATION_FAILED)}):n,i=v(o.msgId);switch(o.msgId){case V.ROOM_MODS:return x(x({},r),{command:k.NOTICE,event:tt.ROOM_MODS,tags:o,mods:Ct(r.message)});default:return x(x({},r),{command:k.NOTICE,event:i,tags:o})}},Lt=function(t){var e=t.tags,n=K(t,["tags"]);return x(x({},n),{command:k.USER_STATE,event:k.USER_STATE,tags:yt(e)})},Mt=function(t){var e=k.USER_NOTICE,n=x(x({},gt(t.tags)),{systemMsg:At(t.tags.systemMsg)}),r=At(t.tags.systemMsg)||"",o=function(t){return Object.entries(t).reduce((function(t,e){var n,r,o=z(e,2),i=o[0],s=o[1],a=z(Nt.exec(i)||[],2)[1];switch(a){case"Months":case"MassGiftCount":case"PromoGiftTotal":case"SenderCount":case"ViewerCount":return x(x({},t),((n={})[C(a)]=It(s),n));case void 0:return t;default:return x(x({},t),((r={})[C(a)]=At(s),r))}}),{})}(n);switch(n.msgId){case X.ANON_GIFT_PAID_UPGRADE:return x(x({},t),{command:e,event:Y.ANON_GIFT_PAID_UPGRADE,parameters:o,tags:n,systemMessage:r});case X.GIFT_PAID_UPGRADE:return x(x({},t),{command:e,event:Y.GIFT_PAID_UPGRADE,parameters:o,tags:n,systemMessage:r});case X.RAID:return x(x({},t),{command:e,event:Y.RAID,parameters:o,tags:n,systemMessage:r});case X.RESUBSCRIPTION:return x(x({},t),{command:e,event:Y.RESUBSCRIPTION,parameters:o,tags:n,systemMessage:r});case X.RITUAL:return x(x({},t),{command:e,event:Y.RITUAL,parameters:o,tags:n,systemMessage:r});case X.SUBSCRIPTION_GIFT_COMMUNITY:return x(x({},t),{command:e,event:Y.SUBSCRIPTION_GIFT_COMMUNITY,parameters:o,tags:n,systemMessage:r});case X.SUBSCRIPTION_GIFT:return x(x({},t),{command:e,event:Y.SUBSCRIPTION_GIFT,parameters:o,tags:n,systemMessage:r});case X.SUBSCRIPTION:return x(x({},t),{command:e,event:Y.SUBSCRIPTION,parameters:o,tags:n,systemMessage:r});default:return x(x({},t),{command:e,event:v(n.msgId),tags:n,parameters:o,systemMessage:r})}},bt=function(t){return"string"!=typeof t||0===t.length?"":(t=t.toLowerCase()).startsWith("#")?t:"#"+t},wt=function(t){return null==t?"TWITCHJS":t.startsWith("oauth:")?t:"oauth:"+t},Pt=function(t){var e,n={username:function(t){return T(t)||p(t)},token:function(t){return T(t)||p(t)},isKnown:f,isVerified:f,connectionTimeout:d,joinTimeout:d,onAuthenticationFailure:y},r=S(x(x({},t),{username:t.username?(e=t.username,_(e)||"justinfan"===e?"justinfan"+N(8e4,81e3):e):void 0,token:t.token?wt(t.token):void 0}),{isKnown:!1,isVerified:!1,connectionTimeout:5e3,joinTimeout:1e3,onAuthenticationFailure:function(){return Promise.reject()}});return O(l(r,n),"[twitch-js/Chat] options: Expected valid options"),r},Ft=function(t){if(!(t=bt(t)))throw new Error("Channel required");return t};!function(t){t[t.WAITING=0]="WAITING",t[t.CONNECTING=1]="CONNECTING",t[t.RECONNECTING=2]="RECONNECTING",t[t.CONNECTED=3]="CONNECTED",t[t.DISCONNECTING=4]="DISCONNECTING",t[t.DISCONNECTED=5]="DISCONNECTED"}(Et||(Et={})),function(t){t.ALREADY_BANNED="NOTICE/ALREADY_BANNED",t.ALREADY_EMOTE_ONLY_OFF="NOTICE/ALREADY_EMOTE_ONLY_OFF",t.ALREADY_EMOTE_ONLY_ON="NOTICE/ALREADY_EMOTE_ONLY_ON",t.ALREADY_R9K_OFF="NOTICE/ALREADY_R9K_OFF",t.ALREADY_R9K_ON="NOTICE/ALREADY_R9K_ON",t.ALREADY_SUBS_OFF="NOTICE/ALREADY_SUBS_OFF",t.ALREADY_SUBS_ON="NOTICE/ALREADY_SUBS_ON",t.BAD_HOST_HOSTING="NOTICE/BAD_HOST_HOSTING",t.BAD_MOD_MOD="NOTICE/BAD_MOD_MOD",t.BAN_SUCCESS="NOTICE/BAN_SUCCESS",t.BAD_UNBAN_NO_BAN="NOTICE/BAD_UNBAN_NO_BAN",t.COLOR_CHANGED="NOTICE/COLOR_CHANGED",t.CMDS_AVAILABLE="NOTICE/CMDS_AVAILABLE",t.COMMERCIAL_SUCCESS="NOTICE/COMMERCIAL_SUCCESS",t.EMOTE_ONLY_OFF="NOTICE/EMOTE_ONLY_OFF",t.EMOTE_ONLY_ON="NOTICE/EMOTE_ONLY_ON",t.FOLLOWERS_OFF="NOTICE/FOLLOWERS_OFF",t.FOLLOWERS_ON="NOTICE/FOLLOWERS_ON",t.FOLLOWERS_ONZERO="NOTICE/FOLLOWERS_ONZERO",t.HOST_OFF="NOTICE/HOST_OFF",t.HOST_ON="NOTICE/HOST_ON",t.HOSTS_REMAINING="NOTICE/HOSTS_REMAINING",t.MSG_CHANNEL_SUSPENDED="NOTICE/MSG_CHANNEL_SUSPENDED",t.MOD_SUCCESS="NOTICE/MOD_SUCCESS",t.NOT_HOSTING="NOTICE/NOT_HOSTING",t.R9K_OFF="NOTICE/R9K_OFF",t.R9K_ON="NOTICE/R9K_ON",t.ROOM_MODS="NOTICE/ROOM_MODS",t.SLOW_OFF="NOTICE/SLOW_OFF",t.SLOW_ON="NOTICE/SLOW_ON",t.SUBS_OFF="NOTICE/SUBS_OFF",t.SUBS_ON="NOTICE/SUBS_ON",t.TIMEOUT_SUCCESS="NOTICE/TIMEOUT_SUCCESS",t.UNBAN_SUCCESS="NOTICE/UNBAN_SUCCESS",t.UNMOD_SUCCESS="NOTICE/UNMOD_SUCCESS",t.UNRAID_SUCCESS="NOTICE/UNRAID_SUCCESS",t.UNRECOGNIZED_CMD="NOTICE/UNRECOGNIZED_CMD"}(_t||(_t={})),function(t){t.CHEER="PRIVMSG/CHEER",t.HOSTED_WITHOUT_VIEWERS="PRIVMSG/HOSTED_WITHOUT_VIEWERS",t.HOSTED_WITH_VIEWERS="PRIVMSG/HOSTED_WITH_VIEWERS",t.HOSTED_AUTO="PRIVMSG/HOSTED_AUTO"}(ht||(ht={})),function(t){t.ANON_GIFT_PAID_UPGRADE="USERNOTICE/ANON_GIFT_PAID_UPGRADE",t.GIFT_PAID_UPGRADE="USERNOTICE/GIFT_PAID_UPGRADE",t.RAID="USERNOTICE/RAID",t.RESUBSCRIPTION="USERNOTICE/RESUBSCRIPTION",t.RITUAL="USERNOTICE/RITUAL",t.SUBSCRIPTION="USERNOTICE/SUBSCRIPTION",t.SUBSCRIPTION_GIFT="USERNOTICE/SUBSCRIPTION_GIFT",t.SUBSCRIPTION_GIFT_COMMUNITY="USERNOTICE/SUBSCRIPTION_GIFT_COMMUNITY"}(Ot||(Ot={}));var Gt,Ht,Bt=function(t){function s(e){var n=t.call(this)||this;return n._readyState=Et.WAITING,n._connectionAttempts=0,n._channelState={},n._isAuthenticated=!1,n._options=Pt(e),n._log=st(x({name:"Chat"},n._options.log)),n}return w(s,t),s.prototype.connect=function(){return J(this,void 0,void 0,(function(){var t,n;return q(this,(function(r){switch(r.label){case 0:return r.trys.push([0,2,,7]),this._readyState=Et.CONNECTING,this._connectionInProgress?[2,this._connectionInProgress]:(t=this,[4,o(this._handleConnectionAttempt(),this._options.connectionTimeout)]);case 1:return t._connectionInProgress=r.sent(),this._readyState=Et.CONNECTED,this._connectionAttempts=0,[3,7];case 2:return n=r.sent(),this._readyState===Et.DISCONNECTING||this._readyState===Et.DISCONNECTED?[3,5]:(this._log.info("Retrying ..."),[4,e(this._options.connectionTimeout)]);case 3:return r.sent(),[4,this._handleAuthenticationFailure()];case 4:return r.sent(),[2,this.connect()];case 5:throw n;case 6:return[3,7];case 7:return[2]}}))}))},s.prototype.updateOptions=function(t){var e=this._options,n=e.token,r=e.username;this._options=Pt(x(x({},t),{token:n,username:r}))},s.prototype.send=function(t,e){if(!this._client)throw new ft("Not connected");return this._client.send(t,e)},s.prototype.disconnect=function(){var t;this._readyState=Et.DISCONNECTING,null===(t=this._client)||void 0===t||t.disconnect(),this._readyState=Et.DISCONNECTED},s.prototype.reconnect=function(t){return J(this,void 0,void 0,(function(){var e,n=this;return q(this,(function(r){switch(r.label){case 0:return t&&(this._options=Pt(x(x({},this._options),t))),this._connectionInProgress=void 0,this._readyState=Et.RECONNECTING,e=this._getChannels(),this.disconnect(),[4,this.connect()];case 1:return r.sent(),[2,Promise.all(e.map((function(t){return n.join(t)})))]}}))}))},s.prototype.join=function(t){return J(this,void 0,void 0,(function(){var e,n,o,i,s;return q(this,(function(a){switch(a.label){case 0:return t=Ft(t),e=this._log.profile("Joining "+t),[4,Promise.all([r(this,k.ROOM_STATE+"/"+t),this._isAuthenticated?r(this,k.USER_STATE+"/"+t):void 0,this.send(k.JOIN+" "+t)])];case 1:return n=z.apply(void 0,[a.sent(),2]),o=n[0],i=n[1],s={roomState:o.tags,userState:i?i.tags:void 0},this._setChannelState(o.channel,s),e.done("Joined "+t),[2,s]}}))}))},s.prototype.part=function(t){return t=Ft(t),this._log.info("Parting "+t),this._removeChannelState(t),this.send(k.PART+" "+t)},s.prototype.say=function(t,e,n){var o,i;return void 0===n&&(n={}),J(this,void 0,void 0,(function(){var s,a,u;return q(this,(function(c){switch(c.label){case 0:if(!this._isAuthenticated)throw new ft("To send messages, please connect with a token and username");return t=Ft(t),s=e.startsWith("/"),a="1"===(null===(i=null===(o=this._channelState[t])||void 0===o?void 0:o.userState)||void 0===i?void 0:i.mod),s?this._log.info("CMD/"+t+" :"+e):this._log.info("PRIVMSG/"+t+" :"+e),u=s?Promise.resolve():r(this,k.USER_STATE+"/"+t),[4,Promise.all([u,this.send(k.PRIVATE_MESSAGE+" "+t+" :"+e,x({isModerator:a},n))])];case 1:return c.sent(),[2]}}))}))},s.prototype.broadcast=function(t){return J(this,void 0,void 0,(function(){var e=this;return q(this,(function(n){if(!this._isAuthenticated)throw new ft("To broadcast, please connect with a token and username");return[2,this._getChannels().map((function(n){return e.say(n,t)}))]}))}))},s.prototype.ban=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.BAN+" "+e,[4,Promise.all([r(this,[_t.BAN_SUCCESS+"/"+t,_t.ALREADY_BANNED+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.block=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.BLOCK+" "+e,[2,this.say(t,n)]}))}))},s.prototype.delete=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.DELETE+" "+e,[2,this.say(t,n)]}))}))},s.prototype.clear=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.CLEAR,[4,Promise.all([r(this,[k.CLEAR_CHAT+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.color=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.COLOR+" "+e,[4,Promise.all([r(this,[_t.COLOR_CHANGED+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.commercial=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.COMMERCIAL+" "+e,[4,Promise.all([r(this,[_t.COMMERCIAL_SUCCESS+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.emoteOnly=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.EMOTE_ONLY,[4,Promise.all([r(this,[_t.EMOTE_ONLY_ON+"/"+t,_t.ALREADY_EMOTE_ONLY_ON+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.emoteOnlyOff=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.EMOTE_ONLY_OFF,[4,Promise.all([r(this,[_t.EMOTE_ONLY_OFF+"/"+t,_t.ALREADY_EMOTE_ONLY_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.followersOnly=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.FOLLOWERS_ONLY+" "+e,[4,Promise.all([r(this,[_t.FOLLOWERS_ONZERO+"/"+t,_t.FOLLOWERS_ON+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.followersOnlyOff=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.FOLLOWERS_ONLY_OFF,[4,Promise.all([r(this,[_t.FOLLOWERS_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.help=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.HELP,[4,Promise.all([r(this,[_t.CMDS_AVAILABLE+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.host=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.HOST+" "+e,[4,Promise.all([r(this,[_t.HOST_ON+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.marker=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.MARKER+" "+e.slice(0,140),[2,this.say(t,n)]}))}))},s.prototype.me=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.ME+" "+e,[2,this.say(t,n)]}))}))},s.prototype.mod=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.MOD+" "+e,[4,Promise.all([r(this,[_t.MOD_SUCCESS+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.mods=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.MODS,[4,Promise.all([r(this,[_t.ROOM_MODS+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.r9K=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.R9K,[4,Promise.all([r(this,[_t.R9K_ON+"/"+t,_t.ALREADY_R9K_ON+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.r9KOff=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.R9K_OFF,[4,Promise.all([r(this,[_t.R9K_OFF+"/"+t,_t.ALREADY_R9K_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.raid=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.RAID+" "+e,[2,this.say(t,n)]}))}))},s.prototype.slow=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.SLOW+" "+e,[4,Promise.all([r(this,[_t.SLOW_ON+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.slowOff=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.SLOW_OFF,[4,Promise.all([r(this,[_t.SLOW_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.subscribers=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.SUBSCRIBERS,[4,Promise.all([r(this,[_t.SUBS_ON+"/"+t,_t.ALREADY_SUBS_ON+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.subscribersOff=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.SUBSCRIBERS_OFF,[4,Promise.all([r(this,[_t.SUBS_OFF+"/"+t,_t.ALREADY_SUBS_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.timeout=function(t,e,n){return J(this,void 0,void 0,(function(){var o,i,s;return q(this,(function(a){switch(a.label){case 0:return t=Ft(t),o=n?" "+n:"",i="/"+j.TIMEOUT+" "+e+o,[4,Promise.all([r(this,[_t.TIMEOUT_SUCCESS+"/"+t]),this.say(t,i)])];case 1:return s=z.apply(void 0,[a.sent(),1]),[2,s[0]]}}))}))},s.prototype.unban=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.UNBAN+" "+e,[4,Promise.all([r(this,[_t.UNBAN_SUCCESS+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.unblock=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){return t=Ft(t),n="/"+j.UNBLOCK+" "+e,[2,this.say(t,n)]}))}))},s.prototype.unhost=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.UNHOST,[4,Promise.all([r(this,[_t.HOST_OFF+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.unmod=function(t,e){return J(this,void 0,void 0,(function(){var n,o;return q(this,(function(i){switch(i.label){case 0:return t=Ft(t),n="/"+j.UNMOD+" "+e,[4,Promise.all([r(this,[_t.UNMOD_SUCCESS+"/"+t]),this.say(t,n)])];case 1:return o=z.apply(void 0,[i.sent(),1]),[2,o[0]]}}))}))},s.prototype.unraid=function(t){return J(this,void 0,void 0,(function(){var e,n;return q(this,(function(o){switch(o.label){case 0:return t=Ft(t),e="/"+j.UNRAID,[4,Promise.all([r(this,[_t.UNRAID_SUCCESS+"/"+t]),this.say(t,e)])];case 1:return n=z.apply(void 0,[o.sent(),1]),[2,n[0]]}}))}))},s.prototype.unvip=function(t,e){t=Ft(t);var n="/"+j.UNVIP+" "+e;return this.say(t,n)},s.prototype.vip=function(t,e){t=Ft(t);var n="/"+j.VIP+" "+e;return this.say(t,n)},s.prototype.vips=function(t){t=Ft(t);var e="/"+j.VIPS;return this.say(t,e)},s.prototype.whisper=function(t,e){return J(this,void 0,void 0,(function(){var n;return q(this,(function(r){if(!this._isAuthenticated)throw new ft("To whisper, please connect with a token and username");return n="/"+j.WHISPER+" "+t+" "+e,[2,this.send(n)]}))}))},s.prototype._handleConnectionAttempt=function(){var t=this;return new n((function(e,n){var r=t._log.profile("Connecting ..."),o=t._options,i=o.token,s=o.username;t._readyState=Et.CONNECTING,t._connectionAttempts+=1,t._client&&t._client.removeAllListeners(),t._client=new pt(t._options),t._client.on(St.DISCONNECTED,t._handleDisconnect,t),t._client.once(St.RECONNECT,(function(){return t.reconnect()})),t._client.once(St.AUTHENTICATION_FAILED,n),t._client.once(St.CONNECTED,(function(n){i&&s&&t._handleAuthenticated(n),t._handleJoinsAfterConnect(),e(),r.done("Connected")})),t._client.on(St.ALL,t._handleMessage,t)}))},s.prototype._handleDisconnect=function(){this._log.info("Disconnecting ..."),this._connectionInProgress&&this._connectionInProgress.clear(),this._connectionInProgress=void 0,this._isAuthenticated=!1,this._clearChannelState(),this._log.info("Disconnected")},s.prototype._handleAuthenticated=function(t){var e,n,r,o=(n=(e=t).tags,r=K(e,["tags"]),x(x({},r),{command:k.GLOBALUSERSTATE,event:k.GLOBALUSERSTATE,tags:Dt(n)}));this._globalUserState=o.tags,this._isAuthenticated=!0},s.prototype._handleAuthenticationFailure=function(){var t,e;return J(this,void 0,void 0,(function(){var n,r;return q(this,(function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),this._log.info("Retrying ..."),[4,null===(e=(t=this._options).onAuthenticationFailure)||void 0===e?void 0:e.call(t)];case 1:return(n=o.sent())?(this._log.info("Re-authenticating ..."),this._options=x(x({},this._options),{token:n}),[2,this.connect()]):[3,3];case 2:throw r=o.sent(),this._log.error("Re-authentication failed"),new Tt(r);case 3:return[2]}}))}))},s.prototype._handleMessage=function(t){if(t instanceof Error)this.emit("error",t);else try{var e=z(this._parseMessageForEmitter(t),2),n=e[0],r=e[1];this._emit(n,r)}catch(e){this._log.error("\nAn error occurred while attempting to parse a message into a event. Please use the following stack trace and raw message to resolve the bug in the TwitchJS source code, and then issue a pull request at https://github.com/twitch-js/twitch-js/compare\n\nStack trace:\n"+e+"\n\nBase message:\n"+JSON.stringify(t)),this.emit(St.ERROR_ENCOUNTERED,e)}},s.prototype._handleJoinsAfterConnect=function(){return J(this,void 0,void 0,(function(){var t,e=this;return q(this,(function(n){switch(n.label){case 0:return t=this._getChannels(),[4,Promise.all(t.map((function(t){return e.join(t)})))];case 1:return n.sent(),[2]}}))}))},s.prototype._getChannels=function(){return Object.keys(this._channelState)},s.prototype._getChannelState=function(t){return this._channelState[t]},s.prototype._setChannelState=function(t,e){this._channelState[t]=e},s.prototype._removeChannelState=function(t){this._channelState=Object.entries(this._channelState).reduce((function(e,n){var r,o=z(n,2),i=o[0],s=o[1];return i===t?e:x(x({},e),((r={})[i]=s,r))}),{})},s.prototype._clearChannelState=function(){this._channelState={}},s.prototype._parseMessageForEmitter=function(t){var e=bt(t.channel),n=t.event||t.command;switch(t.command){case ot.JOIN:return[o=n+"/"+e,r=function(t){var e=z(/:(.+)!(.+)@(.+).tmi.twitch.tv JOIN (#.+)/g.exec(t._raw),5),n=e[1],r=e[4];return x(x({},t),{channel:r,command:k.JOIN,event:k.JOIN,username:n})}(t)];case ot.PART:return[o=n+"/"+e,r=function(t){var e=z(/:(.+)!(.+)@(.+).tmi.twitch.tv PART (#.+)/g.exec(t._raw),5),n=e[1],r=e[4];return x(x({},t),{channel:r,command:k.PART,event:k.PART,username:n})}(t)];case ot.NAMES:return[o=n+"/"+e,r=function(t){var e=z(/:(.+).tmi.twitch.tv 353 (.+) = (#.+) :(.+)/g.exec(t._raw),5),n=e[3],r=e[4].split(" ");return x(x({},t),{channel:n,command:k.NAMES,event:k.NAMES,usernames:r})}(t)];case ot.NAMES_END:return[o=n+"/"+e,r=function(t){var e=z(/:(.+).tmi.twitch.tv 366 (.+) (#.+) :(.+)/g.exec(t._raw),4),n=e[1],r=e[3];return x(x({},t),{channel:r,command:k.NAMES_END,event:k.NAMES_END,username:n})}(t)];case ot.CLEAR_CHAT:return[o=n+"/"+(r=function(t){var e=t.tags,n=t.message,r=K(t,["tags","message"]);return x(x({},r),void 0!==n?{tags:x(x({},e),{banReason:At(e.banReason),banDuration:It(e.banDuration)}),command:k.CLEAR_CHAT,event:Y.USER_BANNED,username:n}:{command:k.CLEAR_CHAT,event:k.CLEAR_CHAT})}(t)).event+"/"+e,r];case ot.CLEAR_MESSAGE:return[o=n+"/"+e,r=function(t){var e=t.tags;return x(x({},t),{tags:{login:e.login,targetMsgId:e.targetMsgId},command:k.CLEAR_MESSAGE,event:k.CLEAR_MESSAGE,targetMessageId:e.targetMsgId})}(t)];case ot.HOST_TARGET:return[o=n+"/"+e,r=function(t){var e=z(/:tmi.twitch.tv HOSTTARGET (#[^\s]+) :([^\s]+)?\s?(\d+)?/g.exec(t._raw),4),n=e[1],r=e[2],o=e[3],i="-"===r;return x(x({},t),{channel:n,username:r,command:k.HOST_TARGET,event:i?Y.HOST_OFF:Y.HOST_ON,numberOfViewers:d(I(o))?parseInt(o,10):void 0})}(t)];case ot.MODE:var r=function(t){var e=z(/:[^\s]+ MODE (#[^\s]+) (-|\+)o ([^\s]+)/g.exec(t._raw),4),n=e[1],r=e[2],o=e[3],i="+"===r,s=x(x({},t),{command:k.MODE,channel:n,username:o});return x(x({},s),i?{event:Y.MOD_GAINED,message:"+o",isModerator:!0}:{event:Y.MOD_LOST,message:"-o",isModerator:!1})}(t),o=n+"/"+e,i=this._getChannelState(e);return this._isAuthenticated&&void 0!==(null==i?void 0:i.userState)&&r.username===this._options.username&&this._setChannelState(e,x(x({},i),{userState:x(x({},i.userState),{mod:r.isModerator?"1":"0",isModerator:r.isModerator})})),[o,r];case ot.USER_STATE:r=Lt(t),o=n+"/"+e;return(i=this._getChannelState(e))&&this._setChannelState(e,x(x({},i),{userState:r.tags})),[o,r];case ot.ROOM_STATE:r=function(t){var e=t.tags,n=K(t,["tags"]);return x(x({},n),{command:k.ROOM_STATE,event:k.ROOM_STATE,tags:Rt(e)})}(t),o=n+"/"+e;return this._setChannelState(e,x(x({},this._getChannelState(e)),{roomState:r})),[o,r];case ot.NOTICE:return[o=n+"/"+(r=Ut(t)).event+"/"+e,r];case ot.USER_NOTICE:return[o=n+"/"+(r=Mt(t)).event+"/"+e,r];case ot.PRIVATE_MESSAGE:return[o=n+"/"+(r=function(t){var e=t._raw,n=t.tags;if(A(n.bits,0))return x(x({},Lt(t)),{command:k.PRIVATE_MESSAGE,event:Y.CHEER,bits:parseInt(n.bits,10)});var r=z(mt.exec(e)||[],5),o=r[0],i=r[1],s=r[2],a=r[3],u=r[4];return o?x(x({},t),a?{command:k.PRIVATE_MESSAGE,event:Y.HOSTED_AUTO,channel:"#"+i,tags:{displayName:s},numberOfViewers:It(u)}:u?{command:k.PRIVATE_MESSAGE,event:Y.HOSTED_WITH_VIEWERS,channel:"#"+i,tags:{displayName:s},numberOfViewers:It(u)}:{command:k.PRIVATE_MESSAGE,event:Y.HOSTED_WITHOUT_VIEWERS,channel:"#"+i,tags:{displayName:s}}):x(x({},Lt(t)),{command:k.PRIVATE_MESSAGE,event:k.PRIVATE_MESSAGE})}(t)).event+"/"+e,r];default:return[o=e?n+"/"+e:n,t]}},s.prototype._emit=function(e,n){var r=this;try{if(e)this._log.info(n,e),i(e.split("/")).filter((function(t){return"#"!==t})).reduce((function(e,o){var i=Z(e,[o]),s=i.join("/");return i.length>1&&t.prototype.emit.call(r,o,n),t.prototype.emit.call(r,s,n),i}),[]);t.prototype.emit.call(this,ot.ALL,n)}catch(t){this._log.error("\nWhile attempting to handle the "+n.command+" event, an error occurred in your implementation. To avoid seeing this message, please resolve the error:\n\n"+t.stack+"\n\nParsed messages:\n"+JSON.stringify(n)),this.emit(St.ERROR_ENCOUNTERED,t)}},s.Commands=k,s.Events=ot,s.CompoundEvents=((lt={})[ot.NOTICE]=_t,lt[ot.PRIVATE_MESSAGE]=ht,lt[ot.USER_NOTICE]=Ot,lt),s}(t),Wt=function(t){function e(n,r){var o=this,i=(null==r?void 0:r.message)||n.url+" "+n.statusText;return o=t.call(this,i)||this,Object.setPrototypeOf(o,e.prototype),o.ok=!1,o.status=n.status,o.statusText=n.statusText,o.url=n.url,o.body=r,o}return w(e,t),e}(dt),kt=function(t){var e={token:p,clientId:function(t){return p(t)||M(t)},onAuthenticationFailure:function(t){return y(t)||M(t)}};return t=S(t,{clientId:void 0,onAuthenticationFailure:void 0}),O(l(t,e),"Expected valid options"),t};!function(t){t[t.NOT_READY=0]="NOT_READY",t[t.READY=1]="READY",t[t.INITIALIZED=2]="INITIALIZED"}(Ht||(Ht={}));var Yt=((Gt={})[P.Helix]={baseUrl:"https://api.twitch.tv/helix",authorizationHeader:"Bearer"},Gt[P.Kraken]={baseUrl:"https://api.twitch.tv/kraken",authorizationHeader:"OAuth"},Gt),jt=function(){function t(t){this._readyState=Ht.READY,this._options=kt(t),this._log=st(x({name:"Api"},this._options.log))}return Object.defineProperty(t.prototype,"readyState",{get:function(){return this._readyState},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),t.prototype.updateOptions=function(t){var e=this._options,n=e.clientId,r=e.token;this._options=kt(x(x({},t),{clientId:n,token:r}))},t.prototype.initialize=function(t){return J(this,void 0,void 0,(function(){var e;return q(this,(function(n){switch(n.label){case 0:return t&&(this._options=kt(x(x({},this._options),t))),t||2!==this.readyState?[4,this.get("",{version:P.Kraken})]:[2,Promise.resolve()];case 1:return"token"in(e=n.sent())&&(this._readyState=Ht.INITIALIZED,this._status=e),[2,e]}}))}))},t.prototype.hasScope=function(t){var e=this;return new Promise((function(n,r){return 2===e.readyState&&e.status&&D(e.status.token.authorization.scopes,t)?n(!0):r(!1)}))},t.prototype.get=function(t,e){return void 0===t&&(t=""),this._handleFetch(t,e)},t.prototype.post=function(t,e){return this._handleFetch(t,x(x({},e),{method:"post"}))},t.prototype.put=function(t,e){return this._handleFetch(t,x(x({},e),{method:"put"}))},t.prototype._isVersionHelix=function(t){return h(t)===P.Helix},t.prototype._getBaseUrl=function(t){return Yt[t].baseUrl},t.prototype._getHeaders=function(t){var e=this._options,n=e.clientId,r=e.token,o={};return this._isVersionHelix(t)||(o.Accept="application/vnd.twitchtv.v5+json"),n&&(o["Client-ID"]=n),r&&(o.Authorization=Yt[t].authorizationHeader+" "+r),o},t.prototype._handleFetch=function(t,e){return void 0===t&&(t=""),void 0===e&&(e={}),J(this,void 0,void 0,(function(){var n,r,o,i,s,a,u,c,_,h,O,l,S,p,d,f,T,N,m,A;return q(this,(function(I){switch(I.label){case 0:n=e.version,r=void 0===n?P.Helix:n,o=K(e,["version"]),i=this._getBaseUrl(r),s=i+"/"+t,a=(v(o.method)||"GET")+" "+s,u=this._log.profile(),c=this._getHeaders(r),_=Object.entries(o.headers||{});try{for(h=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(_),O=h.next();!O.done;O=h.next())l=z(O.value,2),S=l[0],p=l[1],c[String(S)]=p}catch(t){m={error:t}}finally{try{O&&!O.done&&(A=h.return)&&A.call(h)}finally{if(m)throw m.error}}d=function(){return function(t,e,n){return void 0===e&&(e={}),J(void 0,void 0,void 0,(function(){var r,o,i,s,a,u,c,_;return q(this,(function(h){switch(h.label){case 0:return r=e.body&&!(e.body instanceof U)&&"object"==typeof e.body,o=r?JSON.stringify(e.body):e.body,i=r?x(x({},e.headers),{"Content-Type":"application/json"}):e.headers,s="object"==typeof e.search?"?"+L(e.search,n):"",a=x(x({},e),o?{method:e.method||"get",headers:i,body:o}:{method:e.method||"get",headers:i}),[4,g(""+t+s,a)];case 1:return[4,(u=h.sent()).json().catch((function(){}))];case 2:if(c=h.sent(),_=c?E(c,{deep:!0}):void 0,!u.ok)throw new Wt(u,_);return _?[2,_]:[2,u]}}))}))}(s,x(x({},o),{headers:c}))},I.label=1;case 1:return I.trys.push([1,3,9,10]),[4,d()];case 2:return[2,I.sent()];case 3:return T=I.sent(),f=T,"function"==typeof this._options.onAuthenticationFailure&&T instanceof Wt&&401===T.status?[4,this._options.onAuthenticationFailure()]:[3,8];case 4:return(N=I.sent())?[4,this.initialize({token:N})]:[3,6];case 5:I.sent(),this._log.info(a+" ... re-initializing with new token"),I.label=6;case 6:return this._log.info(a+" ... retrying"),[4,d()];case 7:return[2,I.sent()];case 8:throw T;case 9:return u.done(a,f),[7];case 10:return[2]}}))}))},t}(),Vt=function(){function t(t){var e=t.token,n=t.username,r=t.clientId,o=t.log,i=t.onAuthenticationFailure,s=t.chat,a=t.api;this.chat=new Bt(x(x({log:o},s),{token:e,username:n,onAuthenticationFailure:i})),this.api=new jt(x(x({log:o},a),{token:e,clientId:r,onAuthenticationFailure:i}))}return t.prototype.updateOptions=function(t){var e=t.chat,n=t.api;e&&this.chat.updateOptions(e),n&&this.api.updateOptions(n)},t.Chat=Bt,t.Api=jt,t}();export default Vt;export{jt as Api,P as ApiVersions,W as BaseCommands,et as BooleanBadges,F as Capabilities,Bt as Chat,j as ChatCommands,Y as ChatEvents,k as Commands,ot as Events,V as KnownNoticeMessageIds,$ as KnownNoticeMessageIdsUpperCase,X as KnownUserNoticeMessageIds,G as MembershipCommands,tt as NoticeEvents,nt as NumberBadges,B as OtherCommands,Q as PrivateMessageEvents,H as TagCommands,rt as UserNoticeEvents}; //# sourceMappingURL=index.js.map