@mkody/twitch-emoticons 2.9.6 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +530 -169
  2. package/dist/TwitchEmoticons.cjs +950 -0
  3. package/dist/TwitchEmoticons.esm.min.js +7 -0
  4. package/dist/TwitchEmoticons.esm.min.js.map +7 -0
  5. package/dist/TwitchEmoticons.min.js +2 -20
  6. package/dist/TwitchEmoticons.min.js.map +4 -4
  7. package/package.json +99 -72
  8. package/src/index.js +38 -12
  9. package/src/struct/BTTVEmote.js +72 -74
  10. package/src/struct/Channel.js +48 -48
  11. package/src/struct/Emote.js +71 -71
  12. package/src/struct/EmoteFetcher.js +358 -322
  13. package/src/struct/EmoteParser.js +95 -84
  14. package/src/struct/EmoteTypeMapper.js +9 -9
  15. package/src/struct/FFZEmote.js +91 -93
  16. package/src/struct/SevenTVEmote.js +88 -90
  17. package/src/struct/TwitchEmote.js +72 -71
  18. package/src/util/Collection.js +69 -55
  19. package/src/util/Constants.js +30 -30
  20. package/typings/index.d.cts +254 -0
  21. package/typings/index.d.ts +216 -99
  22. package/.jsdoc.json +0 -46
  23. package/.nvmrc +0 -1
  24. package/docs/BTTVEmote.html +0 -1532
  25. package/docs/Channel.html +0 -824
  26. package/docs/Collection.html +0 -798
  27. package/docs/Emote.html +0 -832
  28. package/docs/EmoteFetcher.html +0 -3741
  29. package/docs/EmoteParser.html +0 -1187
  30. package/docs/FFZEmote.html +0 -1686
  31. package/docs/SevenTVEmote.html +0 -1596
  32. package/docs/TwitchEmote.html +0 -1528
  33. package/docs/fonts/Montserrat/Montserrat-Bold.eot +0 -0
  34. package/docs/fonts/Montserrat/Montserrat-Bold.ttf +0 -0
  35. package/docs/fonts/Montserrat/Montserrat-Bold.woff +0 -0
  36. package/docs/fonts/Montserrat/Montserrat-Bold.woff2 +0 -0
  37. package/docs/fonts/Montserrat/Montserrat-Regular.eot +0 -0
  38. package/docs/fonts/Montserrat/Montserrat-Regular.ttf +0 -0
  39. package/docs/fonts/Montserrat/Montserrat-Regular.woff +0 -0
  40. package/docs/fonts/Montserrat/Montserrat-Regular.woff2 +0 -0
  41. package/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.eot +0 -0
  42. package/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.svg +0 -978
  43. package/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.ttf +0 -0
  44. package/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.woff +0 -0
  45. package/docs/fonts/Source-Sans-Pro/sourcesanspro-light-webfont.woff2 +0 -0
  46. package/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.eot +0 -0
  47. package/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.svg +0 -1049
  48. package/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.ttf +0 -0
  49. package/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.woff +0 -0
  50. package/docs/fonts/Source-Sans-Pro/sourcesanspro-regular-webfont.woff2 +0 -0
  51. package/docs/index.html +0 -233
  52. package/docs/scripts/collapse.js +0 -39
  53. package/docs/scripts/commonNav.js +0 -28
  54. package/docs/scripts/linenumber.js +0 -25
  55. package/docs/scripts/nav.js +0 -12
  56. package/docs/scripts/polyfill.js +0 -4
  57. package/docs/scripts/prettify/Apache-License-2.0.txt +0 -202
  58. package/docs/scripts/prettify/lang-css.js +0 -2
  59. package/docs/scripts/prettify/prettify.js +0 -28
  60. package/docs/scripts/search.js +0 -99
  61. package/docs/struct_BTTVEmote.js.html +0 -162
  62. package/docs/struct_Channel.js.html +0 -132
  63. package/docs/struct_Emote.js.html +0 -159
  64. package/docs/struct_EmoteFetcher.js.html +0 -429
  65. package/docs/struct_EmoteParser.js.html +0 -172
  66. package/docs/struct_FFZEmote.js.html +0 -185
  67. package/docs/struct_SevenTVEmote.js.html +0 -180
  68. package/docs/struct_TwitchEmote.js.html +0 -159
  69. package/docs/styles/jsdoc.css +0 -776
  70. package/docs/styles/prettify.css +0 -80
  71. package/docs/util_Collection.js.html +0 -151
  72. package/eslint.config.mjs +0 -215
  73. package/jest.config.js +0 -198
  74. package/test/BTTV.test.js +0 -48
  75. package/test/FFZ.test.js +0 -71
  76. package/test/SevenTV.test.js +0 -71
  77. package/test/ToFromObject.test.js +0 -156
  78. package/test/Twitch.test.js +0 -64
  79. package/test/__snapshots__/ToFromObject.test.js.snap +0 -121
  80. package/test/other.test.js +0 -72
@@ -0,0 +1,7 @@
1
+ var Gn=Object.create;var ni=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Vn=Object.getOwnPropertyNames;var $n=Object.getPrototypeOf,zn=Object.prototype.hasOwnProperty;var s=(n,e)=>ni(n,"name",{value:e,configurable:!0});var tr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Kn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Vn(e))!zn.call(n,a)&&a!==t&&ni(n,a,{get:()=>e[a],enumerable:!(r=Wn(e,a))||r.enumerable});return n};var nt=(n,e,t)=>(t=n!=null?Gn($n(n)):{},Kn(e||!n||!n.__esModule?ni(t,"default",{value:n,enumerable:!0}):t,n));var ct=tr((ks,Oi)=>{Oi.exports.isNode=!1});var Ji=tr((Dc,Zi)=>{function F(n,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}s(F,"RetryOperation");Zi.exports=F;F.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};F.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};F.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var e=new Date().getTime();if(n&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},t),this._options.unref&&this._timer.unref(),!0};F.prototype.attempt=function(n,e){this._fn=n,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};F.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};F.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};F.prototype.start=F.prototype.try;F.prototype.errors=function(){return this._errors};F.prototype.attempts=function(){return this._attempts};F.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},e=null,t=0,r=0;r<this._errors.length;r++){var a=this._errors[r],c=a.message,m=(n[c]||0)+1;n[c]=m,m>=t&&(e=a,t=m)}return e}});var Yi=tr(we=>{var as=Ji();we.operation=function(n){var e=we.timeouts(n);return new as(e,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};we.timeouts=function(n){if(n instanceof Array)return[].concat(n);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in n)e[t]=n[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],a=0;a<e.retries;a++)r.push(this.createTimeout(a,e));return n&&n.forever&&!r.length&&r.push(this.createTimeout(a,e)),r.sort(function(c,m){return c-m}),r};we.createTimeout=function(n,e){var t=e.randomize?Math.random()+1:1,r=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,n));return r=Math.min(r,e.maxTimeout),r};we.wrap=function(n,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var r in n)typeof n[r]=="function"&&t.push(r)}for(var a=0;a<t.length;a++){var c=t[a],m=n[c];n[c]=s(function(f){var C=we.operation(e),T=Array.prototype.slice.call(arguments,1),k=T.pop();T.push(function(q){C.retry(q)||(q&&(arguments[0]=C.mainError()),k.apply(this,arguments))}),C.attempt(function(){f.apply(n,T)})},"retryWrapper").bind(n,m),n[c].options=e}}});var en=tr((Oc,Xi)=>{Xi.exports=Yi()});var si=class n{static{s(this,"Emote")}constructor(e,t,r){if(new.target.name===n.name)throw new Error("Base Emote class cannot be used");this.fetcher=e.fetcher,this.channel=e,this.id=t,this.type=null,this._setup(r)}_setup(e){this.code=e.code}toLink(){return null}toString(){return this.code}toObject(){return{code:this.code,id:this.id,channel_id:this.channel.channel_id}}},V=si;var B={Twitch:{CDN:s((n,e=0,t=!1,r="dark")=>`https://static-cdn.jtvnw.net/emoticons/v2/${n}/${t?"static":"default"}/${r}/${e+1}.0`,"CDN")},BTTV:{Global:"https://api.betterttv.net/3/cached/emotes/global",Channel:s(n=>`https://api.betterttv.net/3/cached/users/twitch/${n}`,"Channel"),CDN:s((n,e=0,t=!1)=>`https://cdn.betterttv.net/emote/${n}/${e+1}x.${t?"png":"webp"}`,"CDN")},SevenTV:{Global:"https://7tv.io/v3/emote-sets/global",Channel:s(n=>`https://7tv.io/v3/users/twitch/${n}`,"Channel"),CDN:s((n,e,t=1,r=!1)=>`https://cdn.7tv.app/emote/${n}/${t}x${r?"_static":""}.${e}`,"CDN")},FFZ:{sets:{Global:3,Modifiers:1532818},Set:s(n=>`https://api.frankerfacez.com/v1/set/${n}`,"Set"),Channel:s(n=>`https://api.frankerfacez.com/v1/room/id/${n}`,"Channel"),CDN:s((n,e=1)=>`https://cdn.frankerfacez.com/emote/${n}/${e}`,"CDN"),CDNAnimated:s((n,e=1)=>`https://cdn.frankerfacez.com/emote/${n}/animated/${e}.webp`,"CDNAnimated")},Templates:{html:'<img alt="{name}" title="{name}" class="twitch-emote" src="{link}">',markdown:'![{name}]({link} "{name}")',bbcode:"[img]{link}[/img]",plain:"{link}"}};var ai=class n extends V{static{s(this,"BTTVEmote")}constructor(e,t,r){super(e,t,r),this.type="bttv"}_setup(e){super._setup(e),this.ownerName="user"in e?e.user.name:null,this.animated=e.animated,this.imageType="webp"}toLink(e){let{size:t=0,forceStatic:r=this.fetcher.forceStatic||!1}=e||{};return B.BTTV.CDN(this.id,t,r)}toObject(){return{...super.toObject(),animated:this.animated,ownerName:this.ownerName,type:this.type}}static fromObject(e,t){return new n(t,e.id,{code:e.code,animated:e.animated,user:{name:e.ownerName}})}},st=ai;var oi=class extends Map{static{s(this,"Collection")}find(e,t){if(typeof e=="string"){if(t===void 0)return null;for(let r of this.values())if(r[e]===t)return r;return null}if(typeof e=="function"){let r=0;for(let a of this.values()){if(e(a,r,this))return a;r++}return null}return null}filter(e,t){t&&(e=e.bind(t));let r=new this.constructor,a=0;for(let[c,m]of this)e(m,a,this)&&r.set(c,m),a++;return r}map(e,t){t&&(e=e.bind(t));let r=new Array(this.size),a=0;for(let c of this.values())r[a]=e(c,a,this),a++;return r}},ye=oi;var li=class{static{s(this,"Channel")}constructor(e,t){this.fetcher=e,this.channel_id=t||null,this.emotes=new ye}fetchBTTVEmotes(){return this.fetcher.fetchBTTVEmotes(this.id)}fetchFFZEmotes(){return this.fetcher.fetchFFZEmotes(this.id)}fetchSevenTVEmotes(){return this.fetcher.fetchSevenTVEmotes(this.id)}},rr=li;var ci=class n extends V{static{s(this,"FFZEmote")}constructor(e,t,r){super(e,t,r),this.type="ffz"}_setup(e){super._setup(e),this.code=e.name,this.ownerName="owner"in e?e.owner.name:null,this.sizes="animated"in e?Object.keys(e.animated):Object.keys(e.urls),this.animated="animated"in e,this.imageType="animated"in e?"webp":"png",this.modifier=e.modifier&&(e.modifier_flags&1)!==0}toLink(e){let{size:t=0,forceStatic:r=this.fetcher.forceStatic||!1}=e||{},a=this.sizes[t];return this.animated&&!r?B.FFZ.CDNAnimated(this.id,a):B.FFZ.CDN(this.id,a)}toObject(){return{...super.toObject(),animated:this.animated,sizes:this.sizes,ownerName:this.ownerName,type:this.type,modifier:this.modifier}}static fromObject(e,t){let r=e.sizes.reduce((a,c)=>(a[c]=c,a),{});return new n(t,e.id,{code:e.code,name:e.code,urls:r,...e.animated?{animated:r}:{},owner:{name:e.ownerName},modifier:e.modifier,modifier_flags:e.modifier})}},at=ci;var ui=class n extends V{static{s(this,"SevenTVEmote")}constructor(e,t,r){super(e,t,r),this.type="7tv"}_setup(e){super._setup(e),this.code=e.name,this.ownerName="owner"in e.data?e.data.owner.display_name:null,this.sizes=e.data.host.files.filter(t=>t.format===this.channel.format.toUpperCase()).map(t=>t.name.replace(/x\.(\w+)/,"")),this.animated=e.data.animated,this.imageType=this.channel.format}toLink(e){let{size:t=0,forceStatic:r=this.fetcher.forceStatic||!1}=e||{},a=this.sizes[t];return B.SevenTV.CDN(this.id,this.imageType,a,r)}toObject(){return{...super.toObject(),animated:this.animated,sizes:this.sizes,ownerName:this.ownerName,type:this.type,imageType:this.imageType}}static fromObject(e,t){let r=e.sizes.map(a=>({format:t.format.toUpperCase(),name:a}));return new n(t,e.id,{code:e.code,name:e.code,data:{animated:e.animated,owner:{display_name:e.ownerName},host:{files:r}}})}},ot=ui;var di=class n extends V{static{s(this,"TwitchEmote")}constructor(e,t,r){super(e,t,r),this.type="twitch"}_setup(e){super._setup(e),this.set=e.emoticon_set,this.animated="animated"in e.formats,this.imageType="animated"in e.formats?"gif":"png"}toLink(e){let{size:t=0,forceStatic:r=this.fetcher.forceStatic||!1,themeMode:a=this.fetcher.twitchThemeMode||"dark"}=e||{};return B.Twitch.CDN(this.id,t,r,a)}toObject(){return{...super.toObject(),animated:this.animated,set:this.set,type:this.type}}static fromObject(e,t){return new n(t,e.id,{code:e.code,animated:e.animated,emoticon_set:e.set,formats:e.animated?{animated:e.animated}:{}})}},lt=di;var mi=s(function(n,e){return mi=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])},mi(n,e)},"extendStatics");function ir(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");mi(n,e);function t(){this.constructor=n}s(t,"__"),n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}s(ir,"__extends");function o(n,e,t,r){var a=arguments.length,c=a<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")c=Reflect.decorate(n,e,t,r);else for(var _=n.length-1;_>=0;_--)(m=n[_])&&(c=(a<3?m(c):a>3?m(e,t,c):m(e,t))||c);return a>3&&c&&Object.defineProperty(e,t,c),c}s(o,"__decorate");function nr(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),a,c=[],m;try{for(;(e===void 0||e-- >0)&&!(a=r.next()).done;)c.push(a.value)}catch(_){m={error:_}}finally{try{a&&!a.done&&(t=r.return)&&t.call(r)}finally{if(m)throw m.error}}return c}s(nr,"__read");function sr(n,e,t){if(t||arguments.length===2)for(var r=0,a=e.length,c;r<a;r++)(c||!(r in e))&&(c||(c=Array.prototype.slice.call(e,0,r)),c[r]=e[r]);return n.concat(c||Array.prototype.slice.call(e))}s(sr,"__spreadArray");var jn=nt(ct(),1);var Vi=nt(ct(),1);var Mi=nt(ct(),1);var re,g;(function(n){n[n.CRITICAL=0]="CRITICAL",n[n.ERROR=1]="ERROR",n[n.WARNING=2]="WARNING",n[n.INFO=3]="INFO",n[n.DEBUG=4]="DEBUG",n[n.TRACE=7]="TRACE"})(g||(g={}));function Re(n){if(typeof n=="number"){if(Object.prototype.hasOwnProperty.call(g,n))return n;var e=Object.keys(g).map(function(r){return parseInt(r,10)}).filter(function(r){return!isNaN(r)&&r<n});return e.length?Math.max.apply(Math,e):g.WARNING}var t=n.replace(/\d+$/,"").toUpperCase();if(!Object.prototype.hasOwnProperty.call(g,t))throw new Error("Unknown log level string: ".concat(n));return g[t]}s(Re,"resolveLogLevel");var Zn=Mi.isNode?console.log.bind(console):console.debug.bind(console),ar=(re={},re[g.CRITICAL]=console.error.bind(console),re[g.ERROR]=console.error.bind(console),re[g.WARNING]=console.warn.bind(console),re[g.INFO]=console.info.bind(console),re[g.DEBUG]=Zn.bind(console),re[g.TRACE]=console.trace.bind(console),re);function h(n){return n===void 0&&(n=!0),function(e,t){Object.defineProperty(e,t,{get:s(function(){},"get"),set:s(function(r){Object.defineProperty(this,t,{value:r,writable:!0,enumerable:n})},"set"),enumerable:n})}}s(h,"Enumerable");function or(n){var e;return(e=[]).concat.apply(e,sr([],nr(n),!1))}s(or,"flatten");function Ni(n,e){return Object.assign.apply(Object,sr([{}],nr(n.map(e)),!1))}s(Ni,"arrayToObject");function ut(n,e){if(typeof e!="function"){var t=e;e=s((function(r){return r[t].toString()}),"keyFn")}return Ni(n,function(r){var a;return a={},a[e(r)]=r,a})}s(ut,"indexBy");function hi(n){return n==null}s(hi,"isNullish");function H(n,e){return hi(n)?null:e(n)}s(H,"mapNullable");function D(n,e){return hi(n)?void 0:e(n)}s(D,"mapOptional");function ie(){var n,e,t=new Promise(function(r,a){n=r,e=a});return{promise:t,resolve:n,reject:e}}s(ie,"promiseWithResolvers");var ji=nt(ct(),1);var pi,_i,lr=typeof process>"u"?[]:(_i=(pi=process.env.LOGGING)===null||pi===void 0?void 0:pi.split(";").map(function(n){var e=n.split("=",2),t=e[0],r=e[1];return r?[t==="default"?void 0:t.split(":"),Re(r)]:null}).filter(function(n){return!!n}).sort(function(n,e){var t,r,a=n[0],c=e[0];return((t=c?.length)!==null&&t!==void 0?t:0)-((r=a?.length)!==null&&r!==void 0?r:0)}))!==null&&_i!==void 0?_i:[],fi=lr.findIndex(function(n){var e=n[0];return!e}),Fi=void 0;fi!==-1&&(Fi=lr[fi][1],lr.splice(fi));function Jn(n,e){return e.length<=n.length&&e.every(function(t,r){return t===n[r]})}s(Jn,"isPrefix");function cr(n){for(var e=n.split(":"),t=0,r=lr;t<r.length;t++){var a=r[t],c=a[0],m=a[1];if(Jn(e,c))return m}return Fi}s(cr,"getMinLogLevelFromEnv");var ur=(function(){function n(e){var t=e.name,r=e.minLevel,a=e.emoji,c=a===void 0?!1:a,m=e.colors,_=e.timestamps,f=_===void 0?ji.isNode:_,C,T;this._name=t,this._minLevel=(T=(C=D(r,function(k){return Re(k)}))!==null&&C!==void 0?C:cr(t))!==null&&T!==void 0?T:g.WARNING,this._emoji=c,this._colors=m,this._timestamps=f}return s(n,"BaseLogger"),n.prototype.crit=function(e){this.log(g.CRITICAL,e)},n.prototype.error=function(e){this.log(g.ERROR,e)},n.prototype.warn=function(e){this.log(g.WARNING,e)},n.prototype.info=function(e){this.log(g.INFO,e)},n.prototype.debug=function(e){this.log(g.DEBUG,e)},n.prototype.trace=function(e){this.log(g.TRACE,e)},n})();var Li=(function(n){ir(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return s(e,"BrowserLogger"),e.prototype.log=function(t,r){if(!(t>this._minLevel)){var a=ar[t],c="[".concat(this._name,"] ").concat(r);this._timestamps&&(c="[".concat(new Date().toISOString(),"] ").concat(r)),a(c)}},e})(ur);var Qi=(function(){function n(e){var t=e.name,r=e.minLevel,a=e.custom,c;this._minLevel=(c=D(r,function(m){return Re(m)}))!==null&&c!==void 0?c:cr(t),this._override=typeof a=="function"?{log:a}:a}return s(n,"CustomLoggerWrapper"),n.prototype.log=function(e,t){this._shouldLog(e)&&this._override.log(e,t)},n.prototype.crit=function(e){this._override.crit?this._shouldLog(g.CRITICAL)&&this._override.crit(e):this.log(g.CRITICAL,e)},n.prototype.error=function(e){this._override.error?this._shouldLog(g.ERROR)&&this._override.error(e):this.log(g.ERROR,e)},n.prototype.warn=function(e){this._override.warn?this._shouldLog(g.WARNING)&&this._override.warn(e):this.log(g.WARNING,e)},n.prototype.info=function(e){this._override.info?this._shouldLog(g.INFO)&&this._override.info(e):this.log(g.INFO,e)},n.prototype.debug=function(e){this._override.debug?this._shouldLog(g.DEBUG)&&this._override.debug(e):this.log(g.DEBUG,e)},n.prototype.trace=function(e){this._override.trace?this._shouldLog(g.TRACE)&&this._override.trace(e):this.log(g.TRACE,e)},n.prototype._shouldLog=function(e){return this._minLevel===void 0||this._minLevel>=e},n})();var ne,se,ae,Yn=(ne={},ne[g.CRITICAL]="\u{1F6D1}",ne[g.ERROR]="\u274C",ne[g.WARNING]="\u26A0\uFE0F ",ne[g.INFO]="\u2139\uFE0F ",ne[g.DEBUG]="\u{1F41E}",ne[g.TRACE]="\u{1F43E}",ne),Xn={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,blackBright:90,redBright:91,greenBright:92,yellowBright:93,blueBright:94,magentaBright:95,cyanBright:96,whiteBright:97},es={bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgBlackBright:100,bgRedBright:101,bgGreenBright:102,bgYellowBright:103,bgBlueBright:104,bgMagentaBright:105,bgCyanBright:106,bgWhiteBright:107};function dr(n,e,t){return function(r){return"\x1B[".concat(n,"m").concat(t?t(r):r,"\x1B[").concat(e,"m")}}s(dr,"createGenericWrapper");function $(n){return dr(Xn[n],39)}s($,"createColorWrapper");function dt(n,e){return dr(es[n],49,e)}s(dt,"createBgWrapper");var ts=(se={},se[g.CRITICAL]=$("red"),se[g.ERROR]=$("redBright"),se[g.WARNING]=$("yellow"),se[g.INFO]=$("blue"),se[g.DEBUG]=$("magenta"),se[g.TRACE]=dr(0,0),se),Gi=(ae={},ae[g.CRITICAL]=dt("bgRed",$("white")),ae[g.ERROR]=dt("bgRedBright",$("white")),ae[g.WARNING]=dt("bgYellow",$("black")),ae[g.INFO]=dt("bgBlue",$("white")),ae[g.DEBUG]=dt("bgMagenta",$("black")),ae[g.TRACE]=dr(7,27),ae),Wi=(function(n){ir(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return s(e,"NodeLogger"),e.prototype.log=function(t,r){var a,c,m;if(!(t>this._minLevel)){var _=ar[t],f="";if(this._timestamps&&(f+="[".concat(new Date().toISOString(),"] ")),this._emoji){var C=Yn[t];f+="".concat(C," ")}var T=(m=(a=this._colors)!==null&&a!==void 0?a:(c=process.stdout)===null||c===void 0?void 0:c.isTTY)!==null&&m!==void 0?m:!0;T?f+="".concat(Gi[t](this._name)," ").concat(Gi[t](g[t])," ").concat(ts[t](r)):f+="[".concat(this._name,":").concat(g[t].toLowerCase(),"] ").concat(r),_(f)}},e})(ur);function xe(n){return n.custom?new Qi(n):Vi.isNode?new Wi(n):new Li(n)}s(xe,"createLogger");var oe=class extends Error{static{s(this,"CustomError")}constructor(...e){var t;super(...e),Object.setPrototypeOf(this,new.target.prototype),(t=Error.captureStackTrace)===null||t===void 0||t.call(Error,this,new.target.constructor)}get name(){return this.constructor.name}};var mt=class extends oe{static{s(this,"RateLimiterDestroyedError")}};var De=class extends oe{static{s(this,"RateLimitReachedError")}};var ht=class extends oe{static{s(this,"RetryAfterError")}constructor(e){super(`Need to retry after ${e} ms`),this._retryAt=Date.now()+e}get retryAt(){return this._retryAt}};var K=class{static{s(this,"ResponseBasedRateLimiter")}constructor({logger:e}){this._queue=[],this._batchRunning=!1,this._paused=!1,this._logger=xe({name:"rate-limiter",emoji:!0,...e})}async request(e,t){return this._logger.trace("request start"),await new Promise((r,a)=>{var c;let m={req:e,resolve:r,reject:a,limitReachedBehavior:(c=t?.limitReachedBehavior)!==null&&c!==void 0?c:"enqueue"};this._batchRunning||this._nextBatchTimer||this._paused?(this._logger.trace(`request queued batchRunning:${this._batchRunning.toString()} hasNextBatchTimer:${(!!this._nextBatchTimer).toString()} paused:${this._paused.toString()}`),this._queue.push(m)):this._runRequestBatch([m])})}clear(){this._queue=[]}pause(){this._paused=!0}resume(){this._paused=!1,this._runNextBatch()}get stats(){var e,t,r,a,c;return{lastKnownLimit:(t=(e=this._parameters)===null||e===void 0?void 0:e.limit)!==null&&t!==void 0?t:null,lastKnownRemainingRequests:(a=(r=this._parameters)===null||r===void 0?void 0:r.remaining)!==null&&a!==void 0?a:null,lastKnownResetDate:H((c=this._parameters)===null||c===void 0?void 0:c.resetsAt,m=>new Date(m))}}async _runRequestBatch(e){this._logger.trace(`runRequestBatch start specs:${e.length}`),this._batchRunning=!0,this._parameters&&this._logger.debug(`Remaining requests: ${this._parameters.remaining}`),this._logger.debug(`Doing ${e.length} requests, new queue length is ${this._queue.length}`);let t=e.map(async m=>{let{req:_,resolve:f,reject:C}=m;try{let T=await this.doRequest(_),k=this.needsToRetryAfter(T);if(k!==null)throw this._queue.unshift(m),this._logger.info(`Retrying after ${k} ms`),new ht(k);let q=this.getParametersFromResponse(T);return f(T),q}catch(T){if(T instanceof ht)throw T;C(T);return}}),r=await Promise.allSettled(t),a=r.filter(m=>m.status==="rejected"),c=Date.now();if(a.length){this._logger.trace("runRequestBatch some rejected");let _=Math.max(c,...a.map(f=>f.reason.retryAt))-c;this._logger.warn(`Waiting for ${_} ms because the rate limit was exceeded`),this._nextBatchTimer=setTimeout(()=>{this._parameters=void 0,this._runNextBatch()},_)}else{this._logger.trace("runRequestBatch none rejected");let m=r.filter(_=>_.status==="fulfilled"&&_.value!==void 0).map(_=>_.value).reduce((_,f)=>_?f.remaining<_.remaining?f:_:f,void 0);if(this._batchRunning=!1,m)if(this._parameters=m,m.resetsAt<c||m.remaining>0)this._logger.trace("runRequestBatch canRunMore"),this._runNextBatch();else{let _=m.resetsAt-c;this._logger.trace(`runRequestBatch delay:${_}`),this._logger.warn(`Waiting for ${_} ms because the rate limit was reached`),this._queue=this._queue.filter(f=>{switch(f.limitReachedBehavior){case"enqueue":return!0;case"null":return f.resolve(null),!1;case"throw":return f.reject(new De("Request removed from queue because the rate limit was reached")),!1;default:throw new Error("this should never happen")}}),this._nextBatchTimer=setTimeout(()=>{this._parameters=void 0,this._runNextBatch()},_)}}this._logger.trace("runRequestBatch end")}_runNextBatch(){if(this._paused)return;this._logger.trace("runNextBatch start"),this._nextBatchTimer&&(clearTimeout(this._nextBatchTimer),this._nextBatchTimer=void 0);let e=this._parameters?Math.min(this._parameters.remaining,this._parameters.limit/10):1,t=this._queue.splice(0,e);t.length&&this._runRequestBatch(t),this._logger.trace("runNextBatch end")}};var pt=class{static{s(this,"PartitionedRateLimiter")}constructor(e){this._children=new Map,this._paused=!1,this._partitionKeyCallback=e.getPartitionKey,this._createChildCallback=e.createChild}async request(e,t){let r=this._partitionKeyCallback(e);return await this._getChild(r).request(e,t)}clear(){for(let e of this._children.values())e.clear()}pause(){this._paused=!0;for(let e of this._children.values())e.pause()}resume(){this._paused=!1;for(let e of this._children.values())e.resume()}getChildStats(e){if(!this._children.has(e))return null;let t=this._children.get(e);return t instanceof K?t.stats:null}_getChild(e){if(this._children.has(e))return this._children.get(e);let t=this._createChildCallback(e);return this._paused&&t.pause(),this._children.set(e,t),t}};var _t=class{static{s(this,"PartitionedTimeBasedRateLimiter")}constructor({logger:e,bucketSize:t,timeFrame:r,doRequest:a,getPartitionKey:c}){this._partitionedQueue=new Map,this._usedFromBucket=new Map,this._counterTimers=new Set,this._paused=!1,this._destroyed=!1,this._logger=xe({name:"rate-limiter",emoji:!0,...e}),this._bucketSize=t,this._timeFrame=r,this._callback=a,this._partitionKeyCallback=c}async request(e,t){return await new Promise((r,a)=>{var c,m;if(this._destroyed){a(new mt("Rate limiter was destroyed"));return}let _={req:e,resolve:r,reject:a,limitReachedBehavior:(c=t?.limitReachedBehavior)!==null&&c!==void 0?c:"enqueue"},f=this._partitionKeyCallback(e),C=(m=this._usedFromBucket.get(f))!==null&&m!==void 0?m:0;if(C>=this._bucketSize||this._paused)switch(_.limitReachedBehavior){case"enqueue":{let T=this._getPartitionedQueue(f);T.push(_),C+T.length>=this._bucketSize?this._logger.warn(`Rate limit of ${this._bucketSize} for ${f?`partition ${f}`:"default partition"} was reached, waiting for ${this._paused?"the limiter to be unpaused":"a free bucket entry"}; queue size is ${T.length}`):this._logger.info(`Enqueueing request for ${f?`partition ${f}`:"default partition"} because the rate limiter is paused; queue size is ${T.length}`);break}case"null":{_.resolve(null),this._paused?this._logger.info(`Returning null for request for ${f?`partition ${f}`:"default partition"} because the rate limiter is paused`):this._logger.warn(`Rate limit of ${this._bucketSize} for ${f?`partition ${f}`:"default partition"} was reached, dropping request and returning null`);break}case"throw":{_.reject(new De(`Request dropped because ${this._paused?"the rate limiter is paused":`the rate limit for ${f?`partition ${f}`:"default partition"} was reached`}`));break}default:throw new Error("this should never happen")}else this._runRequest(_,f)})}clear(){this._partitionedQueue.clear()}pause(){this._paused=!0}resume(){this._paused=!1;for(let e of this._partitionedQueue.keys())this._runNextRequest(e)}destroy(){this._paused=!1,this._destroyed=!0,this._counterTimers.forEach(e=>{clearTimeout(e)});for(let e of this._partitionedQueue.values())for(let t of e)t.reject(new mt("Rate limiter was destroyed"));this._partitionedQueue.clear()}_getPartitionedQueue(e){if(this._partitionedQueue.has(e))return this._partitionedQueue.get(e);let t=[];return this._partitionedQueue.set(e,t),t}async _runRequest(e,t){var r;let a=this._getPartitionedQueue(t);this._logger.debug(`doing a request for ${t?`partition ${t}`:"default partition"}, new queue length is ${a.length}`),this._usedFromBucket.set(t,((r=this._usedFromBucket.get(t))!==null&&r!==void 0?r:0)+1);let{req:c,resolve:m,reject:_}=e;try{m(await this._callback(c))}catch(f){_(f)}finally{let f=setTimeout(()=>{this._counterTimers.delete(f);let C=this._usedFromBucket.get(t)-1;this._usedFromBucket.set(t,C),a.length&&C<this._bucketSize&&this._runNextRequest(t)},this._timeFrame);this._counterTimers.add(f)}}_runNextRequest(e){if(this._paused)return;let r=this._getPartitionedQueue(e).shift();r&&this._runRequest(r,e)}};var i=Symbol("twurpleRawData");var d=class{static{s(this,"DataObject")}[i];constructor(e){this[i]=e}};function gi(){try{return process.env.TWURPLE_MOCK_API_PORT??null}catch{try{return import.meta.env.TWURPLE_MOCK_API_PORT??null}catch{return null}}}s(gi,"getMockApiPort");function ft(n){if(!n)return"";let e=new URLSearchParams;for(let[r,a]of Object.entries(n))if(a===null)e.append(r,"");else if(Array.isArray(a))for(let c of a)e.append(r,c.toString());else a!==void 0&&e.append(r,a.toString());let t=e.toString();return t?`?${t}`:""}s(ft,"qsStringify");var P=class extends Error{static{s(this,"CustomError")}constructor(e,t){super(e,t),Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,new.target.constructor)}get name(){return this.constructor.name}};var mr=class extends P{static{s(this,"RelationAssertionError")}constructor(){super("Relation returned null - this may be a library bug or a race condition in your own code")}};function p(n){if(n==null)throw new mr;return n}s(p,"checkRelationAssertion");function u(n,e,t){return r=>{let a=t?function(){return`[${e}#${this[t]} - please check https://twurple.js.org/reference/${n}/classes/${e}.html for available properties]`}:function(){return`[${e} - please check https://twurple.js.org/reference/${n}/classes/${e}.html for available properties]`};Object.defineProperty(r.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:a,enumerable:!1})}}s(u,"rtfm");var gt=class extends d{static{s(this,"HelixExtension")}get authorName(){return this[i].author_name}get bitsEnabled(){return this[i].bits_enabled}get installable(){return this[i].can_install}get configurationLocation(){return this[i].configuration_location}get description(){return this[i].description}get tosUrl(){return this[i].eula_tos_url}get hasChatSupport(){return this[i].has_chat_support}get iconUrl(){return this[i].icon_url}getIconUrl(e){return this[i].icon_urls[e]}get id(){return this[i].id}get name(){return this[i].name}get privacyPolicyUrl(){return this[i].privacy_policy_url}get requestsIdentityLink(){return this[i].request_identity_link}get screenshotUrls(){return this[i].screenshot_urls}get state(){return this[i].state}get subscriptionsSupportLevel(){return this[i].subscriptions_support_level}get summary(){return this[i].summary}get supportEmail(){return this[i].support_email}get version(){return this[i].version}get viewerSummary(){return this[i].viewer_summary}get viewerSummery(){return this[i].viewer_summary}get allowedConfigUrls(){return this[i].allowlisted_config_urls}get allowedPanelUrls(){return this[i].allowlisted_panel_urls}get mobileViewerUrl(){return this[i].views.mobile?.viewer_url??null}get panelViewerUrl(){return this[i].views.panel?.viewer_url??null}get panelHeight(){return this[i].views.panel?.height??null}get panelCanLinkExternalContent(){return this[i].views.panel?.can_link_external_content??null}get overlayViewerUrl(){return this[i].views.video_overlay?.viewer_url??null}get overlayCanLinkExternalContent(){return this[i].views.video_overlay?.can_link_external_content??null}get componentViewerUrl(){return this[i].views.component?.viewer_url??null}get componentAspectWidth(){return this[i].views.component?.aspect_width??null}get componentAspectHeight(){return this[i].views.component?.aspect_height??null}get componentAspectRatioX(){return this[i].views.component?.aspect_ratio_x??null}get componentAspectRatioY(){return this[i].views.component?.aspect_ratio_y??null}get componentAutoScales(){return this[i].views.component?.autoscale??null}get componentScalePixels(){return this[i].views.component?.scale_pixels??null}get componentTargetHeight(){return this[i].views.component?.target_height??null}get componentSize(){return this[i].views.component?.size??null}get componentZoom(){return this[i].views.component?.zoom??null}get componentZoomPixels(){return this[i].views.component?.zoom_pixels??null}get componentCanLinkExternalContent(){return this[i].views.component?.can_link_external_content??null}get configViewerUrl(){return this[i].views.config?.viewer_url??null}get configCanLinkExternalContent(){return this[i].views.config?.can_link_external_content??null}};gt=o([u("api","HelixExtension","id")],gt);var M=class extends P{static{s(this,"HellFreezesOverError")}constructor(e){super(`${e} - this should never happen, please file a bug in the GitHub issue tracker`)}};function l(n){return typeof n=="string"?n:typeof n=="number"?n.toString(10):n.id}s(l,"extractUserId");function le(n){return typeof n=="string"?n:n.name}s(le,"extractUserName");var O=class extends P{static{s(this,"HttpStatusCodeError")}_statusCode;_url;_method;_body;constructor(e,t,r,a,c,m){super(`Encountered HTTP status code ${e}: ${t}
2
+
3
+ URL: ${r}
4
+ Method: ${a}
5
+ Body:
6
+ ${!m&&c.length>150?`${c.slice(0,147)}...`:c}`),this._statusCode=e,this._url=r,this._method=a,this._body=c}get statusCode(){return this._statusCode}get url(){return this._url}get method(){return this._method}get body(){return this._body}};async function Pe(n,e){if(!n.ok){let t=n.headers.get("Content-Type")==="application/json",r=t?JSON.stringify(await n.json(),null,2):await n.text(),a=ft(e.query),c=`${e.url}${a}`;throw new O(n.status,n.statusText,c,e.method??"GET",r,t)}}s(Pe,"handleTwitchApiResponseError");async function yt(n){if(n.status===204)return;let e=await n.text();if(e)return JSON.parse(e)}s(yt,"transformTwitchApiResponse");function $i(n,e){let t=gi();switch(e){case"helix":{let r=n.replace(/^\//,"");return t?r==="eventsub/subscriptions"?`http://localhost:${t}/${r}`:`http://localhost:${t}/mock/${r}`:`https://api.twitch.tv/helix/${r}`}case"auth":{let r=n.replace(/^\//,"");return t?`http://localhost:${t}/auth/${r}`:`https://id.twitch.tv/oauth2/${r}`}case"custom":return n;default:return n}}s($i,"getTwitchApiUrl");async function ce(n,e,t,r,a={}){let c=n.type??"helix",m=$i(n.url,c),_=ft(n.query),f=new Headers({Accept:"application/json"}),C;n.jsonBody&&(C=JSON.stringify(n.jsonBody),f.append("Content-Type","application/json")),e&&c!=="auth"&&f.append("Client-ID",e),t&&f.append("Authorization",`${c==="helix"?r??"Bearer":"OAuth"} ${t}`);let T={...a,method:n.method??"GET",headers:f,body:C};return await fetch(`${m}${_}`,T)}s(ce,"callTwitchApiRaw");async function xt(n,e,t,r,a={}){let c=await ce(n,e,t,r,a);return await Pe(c,n),await yt(c)}s(xt,"callTwitchApi");function w(n){return{broadcaster_id:l(n)}}s(w,"createBroadcasterQuery");var hr=class extends P{static{s(this,"ConfigError")}};var pr=class extends K{static{s(this,"HelixRateLimiter")}async doRequest({options:e,clientId:t,accessToken:r,authorizationType:a,fetchOptions:c}){return await ce(e,t,r,a,c)}needsToRetryAfter(e){return e.status===429&&(!e.headers.has("ratelimit-remaining")||Number(e.headers.get("ratelimit-remaining"))===0)?+e.headers.get("ratelimit-reset")*1e3-Date.now():null}getParametersFromResponse(e){let{headers:t}=e;return{limit:+t.get("ratelimit-limit"),remaining:+t.get("ratelimit-remaining"),resetsAt:+t.get("ratelimit-reset")*1e3}}};function rs(n){switch(typeof n){case"undefined":return"";case"object":{if(n===null)return"";if("cacheKey"in n)return n.cacheKey;let e=JSON.stringify(n);if(e!=="{}")return e}default:return n.toString()}}s(rs,"createSingleCacheKey");function _r(n,e,t){return[n,...e.map(rs)].join("/")+(t?"/":"")}s(_r,"createCacheKey");var Z=Symbol("cache");function J(n){var e,t;return t=class extends n{static{s(this,"_b")}constructor(){super(...arguments),this[e]=new Map}getFromCache(r){if(this._cleanCache(),this[Z].has(r)){let a=this[Z].get(r);if(a)return a.value}}setCache(r,a,c){this[Z].set(r,{value:a,expires:Date.now()+c*1e3})}removeFromCache(r,a){let c=this._getInternalCacheKey(r,a);a?this[Z].forEach((m,_)=>{_.startsWith(c)&&this[Z].delete(_)}):this[Z].delete(c)}_cleanCache(){let r=Date.now();this[Z].forEach((a,c)=>{a.expires<r&&this[Z].delete(c)})}_getInternalCacheKey(r,a){if(typeof r=="string"){let c=r;return c.endsWith("/")||(c+="/"),c}else{let c=r.shift();return _r(c,r,a)}}},e=Z,t}s(J,"Cacheable");function A(n=1/0){return function(e,t,r){if(r.get){let a=r.get;r.get=function(){let c=_r(t,[]),m=this.getFromCache(c);if(m)return m;let _=a.call(this);return this.setCache(c,_,n),_}}return r}}s(A,"CachedGetter");var fr=class{static{s(this,"Listener")}constructor(e,t,r,a=!1){this.owner=e,this.event=t,this.listener=r,this._internal=a}unbind(){this.owner.removeListener(this)}};var wt=class{static{s(this,"EventEmitter")}constructor(){this._eventListeners=new Map,this._internalEventListeners=new Map}on(e,t){return this._addListener(!1,e,t)}addListener(e,t){return this._addListener(!1,e,t)}removeListener(e,t){this._removeListener(!1,e,t)}registerEvent(){let e=s(t=>this.addListener(e,t),"eventBinder");return e}emit(e,...t){if(this._eventListeners.has(e))for(let r of this._eventListeners.get(e))r(...t);if(this._internalEventListeners.has(e))for(let r of this._internalEventListeners.get(e))r(...t)}registerInternalEvent(){let e=s(t=>this.addInternalListener(e,t),"eventBinder");return e}addInternalListener(e,t){return this._addListener(!0,e,t)}removeInternalListener(e,t){this._removeListener(!0,e,t)}_addListener(e,t,r){let a=e?this._eventListeners:this._internalEventListeners;return a.has(t)?a.get(t).push(r):a.set(t,[r]),new fr(this,t,r,e)}_removeListener(e,t,r){let a=e?this._eventListeners:this._internalEventListeners;if(!t)a.clear();else if(typeof t=="object"){let c=t;this._removeListener(c._internal,c.event,c.listener)}else{let c=t;if(a.has(c))if(r){let m=a.get(c),_=0;for(;(_=m.indexOf(r))!==-1;)m.splice(_,1)}else a.delete(c)}}};var is=6e4;function ns(n){return H(n.expiresIn,e=>n.obtainmentTimestamp+e*1e3-is)}s(ns,"getExpiryMillis");function ke(n){return H(ns(n),e=>Date.now()>e)??!1}s(ke,"accessTokenIsExpired");var bt=class extends P{static{s(this,"InvalidTokenError")}constructor(e){super("Invalid token supplied",e)}};function zi(n,e){return{grant_type:"client_credentials",client_id:n,client_secret:e}}s(zi,"createGetAppTokenQuery");var St=class extends d{static{s(this,"TokenInfo")}_obtainmentDate;constructor(e){super(e),this._obtainmentDate=new Date}get clientId(){return this[i].client_id}get userId(){return this[i].user_id??null}get userName(){return this[i].login??null}get scopes(){return this[i].scopes}get expiryDate(){return H(this[i].expires_in,e=>new Date(this._obtainmentDate.getTime()+e*1e3))}};St=o([u("auth","TokenInfo","clientId")],St);function ss(n){return{accessToken:n.access_token,refreshToken:n.refresh_token||null,scope:n.scope??[],expiresIn:n.expires_in??null,obtainmentTimestamp:Date.now()}}s(ss,"createAccessTokenFromData");async function Ki(n,e){return ss(await xt({type:"auth",url:"token",method:"POST",query:zi(n,e)}))}s(Ki,"getAppToken");var gr=class{static{s(this,"TokenFetcher")}_executor;_newTokenScopeSets=[];_newTokenPromise=null;_queuedScopeSets=[];_queueExecutor=null;_queuePromise=null;constructor(e){this._executor=e}async fetch(...e){let t=e.filter(m=>!!m);if(this._newTokenPromise){if(!t.length)return await this._newTokenPromise;if(this._queueExecutor?this._queuedScopeSets.push(...t):this._queuedScopeSets=[...t],!this._queuePromise){let{promise:m,resolve:_,reject:f}=ie();this._queuePromise=m,this._queueExecutor=async()=>{if(this._queuePromise){this._newTokenScopeSets=this._queuedScopeSets,this._queuedScopeSets=[],this._newTokenPromise=this._queuePromise,this._queuePromise=null,this._queueExecutor=null;try{_(await this._executor(this._newTokenScopeSets))}catch(C){f(C)}finally{this._newTokenPromise=null,this._newTokenScopeSets=[],this._queueExecutor?.()}}}}return await this._queuePromise}this._newTokenScopeSets=[...t];let{promise:r,resolve:a,reject:c}=ie();this._newTokenPromise=r;try{a(await this._executor(this._newTokenScopeSets))}catch(m){c(m)}finally{this._newTokenPromise=null,this._newTokenScopeSets=[],this._queueExecutor?.()}return await r}};var ue=class{static{s(this,"AppTokenAuthProvider")}_clientId;_clientSecret;_token;_fetcher;_impliedScopes;constructor(e,t,r=[]){this._clientId=e,this._clientSecret=t,this._impliedScopes=r,this._fetcher=new gr(async a=>await this._fetch(a))}get clientId(){return this._clientId}get currentScopes(){return this._impliedScopes}async getAccessTokenForUser(e,...t){if(t.every(r=>r?.some(a=>this._impliedScopes.includes(a))??!0))return{...await this.getAppAccessToken(),userId:l(e)};throw new Error("Can not get user access token for AppTokenAuthProvider")}getCurrentScopesForUser(){return this._impliedScopes}async getAnyAccessToken(){return await this._fetcher.fetch()}async getAppAccessToken(e=!1){return e&&(this._token=void 0),await this._fetcher.fetch()}async _fetch(e){if(e.length>0)for(let t of e)if(this._impliedScopes.length){if(t.every(r=>!this._impliedScopes.includes(r)))throw new Error(`One of the scopes ${t.join(", ")} requested but only the scope ${this._impliedScopes.join(", ")} is implied`)}else throw new Error(`One of the scopes ${t.join(", ")} requested but the client credentials flow does not support scopes`);return!this._token||ke(this._token)?this._token=await Ki(this._clientId,this._clientSecret):this._token}};o([h(!1)],ue.prototype,"_clientSecret",void 0);o([h(!1)],ue.prototype,"_token",void 0);o([h(!1)],ue.prototype,"_fetcher",void 0);ue=o([u("auth","AppTokenAuthProvider","clientId")],ue);var Fn=nt(en(),1);function tn(n={}){let{count:e=10,period:t="all",startDate:r,contextUserId:a}=n;return{count:e.toString(),period:t,started_at:r?.toISOString(),user_id:a}}s(tn,"createBitsLeaderboardQuery");var y=class{static{s(this,"BaseApi")}_client;constructor(e){this._client=e}_getUserContextIdWithDefault(e){return this._client._getUserIdFromRequestContext(e)??e}};o([h(!1)],y.prototype,"_client",void 0);var Ct=class extends d{static{s(this,"HelixBitsLeaderboardEntry")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}get rank(){return this[i].rank}get amount(){return this[i].score}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],Ct.prototype,"_client",void 0);Ct=o([u("api","HelixBitsLeaderboardEntry","userId")],Ct);var qe=class extends d{static{s(this,"HelixBitsLeaderboard")}_client;constructor(e,t){super(e),this._client=t}get entries(){return this[i].data.map(e=>new Ct(e,this._client))}get totalCount(){return this[i].total}};o([h(!1)],qe.prototype,"_client",void 0);o([A()],qe.prototype,"entries",null);qe=o([J,u("api","HelixBitsLeaderboard")],qe);var yr=class extends d{static{s(this,"HelixCheermoteList")}constructor(e){super(ut(e,t=>t.prefix.toLowerCase()))}getCheermoteDisplayInfo(e,t,r){e=e.toLowerCase();let{background:a,state:c,scale:m}=r,{tiers:_}=this[i][e],f=_.sort((C,T)=>T.min_bits-C.min_bits).find(C=>C.min_bits<=t);if(!f)throw new M(`Cheermote "${e}" does not have an applicable tier for ${t} bits`);return{url:f.images[a][c][m],color:f.color}}getPossibleNames(){return Object.keys(this[i])}};yr=o([u("api","HelixCheermoteList")],yr);var xr=class extends y{static{s(this,"HelixBitsApi")}async getLeaderboard(e,t={}){let r=await this._client.callApi({type:"helix",url:"bits/leaderboard",userId:l(e),scopes:["bits:read"],query:tn(t)});return new qe(r,this._client)}async getCheermotes(e){let t=await this._client.callApi({type:"helix",url:"bits/cheermotes",userId:D(e,l),query:D(e,w)});return new yr(t.data)}};xr=o([u("api","HelixBitsApi")],xr);function rn(n){return{game_id:n.gameId,broadcaster_language:n.language,title:n.title,delay:n.delay?.toString(),tags:n.tags,content_classification_labels:n.contentClassificationLabels,is_branded_content:n.isBrandedContent}}s(rn,"createChannelUpdateBody");function nn(n,e){return{broadcaster_id:l(n),length:e}}s(nn,"createChannelCommercialBody");function yi(n,e){return{broadcaster_id:l(n),user_id:l(e)}}s(yi,"createChannelVipUpdateQuery");function wr(n,e){return{broadcaster_id:l(n),user_id:D(e,l)}}s(wr,"createChannelFollowerQuery");function xi(n,e){return{broadcaster_id:D(e,l),user_id:l(n)}}s(xi,"createFollowedChannelQuery");function I(n,e){return{[n]:e}}s(I,"createSingleKeyQuery");function wi(n){return{user_id:l(n)}}s(wi,"createUserQuery");function br(n,e){return{broadcaster_id:n,moderator_id:e}}s(br,"createModeratorActionQuery");function de(n,e){return{broadcaster_id:l(n),id:e}}s(de,"createGetByIdsQuery");function Sr(n,e){return{broadcaster_id:l(n),user_id:e.map(l)}}s(Sr,"createChannelUsersCheckQuery");var Y=class extends d{static{s(this,"HelixUserRelation")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].user_id}get name(){return this[i].user_login}get displayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],Y.prototype,"_client",void 0);Y=o([u("api","HelixUserRelation","id")],Y);var U=class{static{s(this,"HelixRequestBatcher")}_callOptions;_queryParamName;_matchKey;_mapper;_limitPerRequest;_client;_requestedIds=[];_requestResolversById=new Map;_delay;_waitTimer=null;constructor(e,t,r,a,c,m=100){this._callOptions=e,this._queryParamName=t,this._matchKey=r,this._mapper=c,this._limitPerRequest=m,this._client=a,this._delay=a._batchDelay}async request(e){let{promise:t,resolve:r,reject:a}=ie();return this._requestedIds.includes(e)||this._requestedIds.push(e),this._requestResolversById.has(e)?this._requestResolversById.get(e).push({resolve:r,reject:a}):this._requestResolversById.set(e,[{resolve:r,reject:a}]),this._waitTimer&&(clearTimeout(this._waitTimer),this._waitTimer=null),this._requestedIds.length>=this._limitPerRequest?this._handleBatch(this._requestedIds.splice(0,this._limitPerRequest)):this._waitTimer=setTimeout(()=>{this._handleBatch(this._requestedIds.splice(0,this._limitPerRequest))},this._delay),await t}async _handleBatch(e){try{let{data:t}=await this._doRequest(e),r=ut(t,this._matchKey);for(let a of e){for(let c of this._requestResolversById.get(a)??[])Object.prototype.hasOwnProperty.call(r,a)?c.resolve(this._mapper(r[a])):c.resolve(null);this._requestResolversById.delete(a)}}catch{await Promise.all(e.map(async r=>{try{let a=await this._doRequest([r]);for(let c of this._requestResolversById.get(r)??[])c.resolve(a.data.length?this._mapper(a.data[0]):null)}catch(a){for(let c of this._requestResolversById.get(r)??[])c.reject(a)}this._requestResolversById.delete(r)}))}}async _doRequest(e){return await this._client.callApi({type:"helix",...this._callOptions,query:{...this._callOptions.query,[this._queryParamName]:e}})}};o([h(!1)],U.prototype,"_client",void 0);Object.prototype.hasOwnProperty.call(Symbol,"asyncIterator")||(Symbol.asyncIterator=Symbol.asyncIterator??Symbol.for("Symbol.asyncIterator"));var S=class{static{s(this,"HelixPaginatedRequest")}_callOptions;_mapper;_limitPerPage;_client;_currentCursor;_isFinished=!1;_currentData;constructor(e,t,r,a=100){this._callOptions=e,this._mapper=r,this._limitPerPage=a,this._client=t}get current(){return this._currentData?.data}async getNext(){if(this._isFinished)return[];let e=await this._fetchData();return e.data?.length?this._processResult(e):(this._isFinished=!0,[])}async getAll(){this.reset();let e=[];do{let t=await this.getNext();if(!t.length)break;e.push(...t)}while(this._currentCursor);return this.reset(),e}get currentCursor(){return this._currentCursor}reset(){this._currentCursor=void 0,this._isFinished=!1,this._currentData=void 0}async*[Symbol.asyncIterator](){for(this.reset();;){let e=await this.getNext();if(!e.length)break;yield*e[Symbol.iterator]()}}async _fetchData(e={}){return await this._client.callApi({type:"helix",...this._callOptions,...e,query:{...this._callOptions.query,after:this._currentCursor,first:this._limitPerPage.toString(),...e.query}})}_processResult(e){return this._currentCursor=typeof e.pagination=="string"?e.pagination:e.pagination?.cursor,this._currentCursor===void 0&&(this._isFinished=!0),this._currentData=e,e.data.reduce((t,r)=>{let a=this._mapper(r);return Array.isArray(a)?[...t,...a]:[...t,a]},[])}};o([h(!1)],S.prototype,"_client",void 0);S=o([u("api","HelixPaginatedRequest")],S);var L=class extends S{static{s(this,"HelixPaginatedRequestWithTotal")}async getTotalCount(){return(this._currentData??await this._fetchData({query:{after:void 0}})).total}};L=o([u("api","HelixPaginatedRequestWithTotal")],L);function v(n,e,t){let r;return{get data(){return r??=n.data?.map(a=>new e(a,t))??[]},cursor:typeof n.pagination=="string"?n.pagination:n.pagination?.cursor}}s(v,"createPaginatedResult");function j(n,e,t){let r;return{get data(){return r??=n.data?.map(a=>new e(a,t))??[]},cursor:n.pagination.cursor,total:n.total}}s(j,"createPaginatedResultWithTotal");function x({after:n,before:e,limit:t}={}){return{after:n,before:e,first:t?.toString()}}s(x,"createPaginationQuery");var be=class extends d{static{s(this,"HelixChannel")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].broadcaster_id}get name(){return this[i].broadcaster_login}get displayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get language(){return this[i].broadcaster_language}get gameId(){return this[i].game_id}get gameName(){return this[i].game_name}async getGame(){return this[i].game_id?p(await this._client.games.getGameById(this[i].game_id)):null}get title(){return this[i].title}get delay(){return this[i].delay}get tags(){return this[i].tags}get contentClassificationLabels(){return this[i].content_classification_labels}get isBrandedContent(){return this[i].is_branded_content}};o([h(!1)],be.prototype,"_client",void 0);be=o([u("api","HelixChannel","id")],be);var vt=class extends d{static{s(this,"HelixChannelEditor")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get creationDate(){return new Date(this[i].created_at)}};o([h(!1)],vt.prototype,"_client",void 0);vt=o([u("api","HelixChannelEditor","userId")],vt);var Oe=class extends d{static{s(this,"HelixChannelFollower")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get followDate(){return new Date(this[i].followed_at)}};o([h(!1)],Oe.prototype,"_client",void 0);Oe=o([u("api","HelixChannelFollower","userId")],Oe);var Me=class extends d{static{s(this,"HelixFollowedChannel")}_client;constructor(e,t){super(e),this._client=t}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get followDate(){return new Date(this[i].followed_at)}};o([h(!1)],Me.prototype,"_client",void 0);Me=o([u("api","HelixFollowedChannel","broadcasterId")],Me);var Cr=class extends d{static{s(this,"HelixAdSchedule")}get snoozeCount(){return this[i].snooze_count}get snoozeRefreshDate(){return this[i].snooze_refresh_at?new Date(this[i].snooze_refresh_at*1e3):null}get nextAdDate(){return this[i].next_ad_at?new Date(this[i].next_ad_at*1e3):null}get duration(){return this[i].duration}get lastAdDate(){return this[i].last_ad_at?new Date(this[i].last_ad_at*1e3):null}get prerollFreeTime(){return this[i].preroll_free_time}};Cr=o([u("api","HelixAdSchedule")],Cr);var vr=class extends d{static{s(this,"HelixSnoozeNextAdResult")}get snoozeCount(){return this[i].snooze_count}get snoozeRefreshDate(){return new Date(this[i].snooze_refresh_at*1e3)}get nextAdDate(){return new Date(this[i].next_ad_at*1e3)}};vr=o([u("api","HelixSnoozeNextAdResult")],vr);var It=class extends y{static{s(this,"HelixChannelApi")}_getChannelByIdBatcher=new U({url:"channels"},"broadcaster_id","broadcaster_id",this._client,e=>new be(e,this._client));async getChannelInfoById(e){let t=l(e),r=await this._client.callApi({type:"helix",url:"channels",userId:t,query:w(t)});return H(r.data[0],a=>new be(a,this._client))}async getChannelInfoByIdBatched(e){return await this._getChannelByIdBatcher.request(l(e))}async getChannelInfoByIds(e){let t=e.map(l);return(await this._client.callApi({type:"helix",url:"channels",query:I("broadcaster_id",t)})).data.map(a=>new be(a,this._client))}async updateChannelInfo(e,t){await this._client.callApi({type:"helix",url:"channels",method:"PATCH",userId:l(e),scopes:["channel:manage:broadcast"],query:w(e),jsonBody:rn(t)})}async startChannelCommercial(e,t){await this._client.callApi({type:"helix",url:"channels/commercial",method:"POST",userId:l(e),scopes:["channel:edit:commercial"],jsonBody:nn(e,t)})}async getChannelEditors(e){return(await this._client.callApi({type:"helix",url:"channels/editors",userId:l(e),scopes:["channel:read:editors"],query:w(e)})).data.map(r=>new vt(r,this._client))}async getVips(e,t){let r=await this._client.callApi({type:"helix",url:"channels/vips",userId:l(e),scopes:["channel:read:vips","channel:manage:vips"],query:{...w(e),...x(t)}});return v(r,Y,this._client)}getVipsPaginated(e){return new S({url:"channels/vips",userId:l(e),scopes:["channel:read:vips","channel:manage:vips"],query:w(e)},this._client,t=>new Y(t,this._client))}async checkVipForUsers(e,t){return(await this._client.callApi({type:"helix",url:"channels/vips",userId:l(e),scopes:["channel:read:vips","channel:manage:vips"],query:Sr(e,t)})).data.map(a=>new Y(a,this._client))}async checkVipForUser(e,t){let r=l(t);return(await this.checkVipForUsers(e,[r])).some(c=>c.id===r)}async addVip(e,t){await this._client.callApi({type:"helix",url:"channels/vips",method:"POST",userId:l(e),scopes:["channel:manage:vips"],query:yi(e,t)})}async removeVip(e,t){await this._client.callApi({type:"helix",url:"channels/vips",method:"DELETE",userId:l(e),scopes:["channel:manage:vips"],query:yi(e,t)})}async getChannelFollowerCount(e){return(await this._client.callApi({type:"helix",url:"channels/followers",method:"GET",userId:l(e),query:{...wr(e),...x({limit:1})}})).total}async getChannelFollowers(e,t,r){let a=await this._client.callApi({type:"helix",url:"channels/followers",method:"GET",userId:l(e),canOverrideScopedUserContext:!0,scopes:["moderator:read:followers"],query:{...wr(e,t),...x(r)}});return j(a,Oe,this._client)}getChannelFollowersPaginated(e){return new L({url:"channels/followers",method:"GET",userId:l(e),canOverrideScopedUserContext:!0,scopes:["moderator:read:followers"],query:wr(e)},this._client,t=>new Oe(t,this._client))}async getFollowedChannels(e,t,r){let a=await this._client.callApi({type:"helix",url:"channels/followed",method:"GET",userId:l(e),scopes:["user:read:follows"],query:{...xi(e,t),...x(r)}});return j(a,Me,this._client)}getFollowedChannelsPaginated(e,t){return new L({url:"channels/followed",method:"GET",userId:l(e),scopes:["user:read:follows"],query:xi(e,t)},this._client,r=>new Me(r,this._client))}async getAdSchedule(e){let t=await this._client.callApi({type:"helix",url:"channels/ads",method:"GET",userId:l(e),scopes:["channel:read:ads"],query:w(e)});return new Cr(t.data[0])}async snoozeNextAd(e){let t=await this._client.callApi({type:"helix",url:"channels/ads/schedule/snooze",method:"POST",userId:l(e),scopes:["channel:manage:ads"],query:w(e)});return new vr(t.data[0])}};o([h(!1)],It.prototype,"_getChannelByIdBatcher",void 0);It=o([u("api","HelixChannelApi")],It);function sn(n,e){return{broadcaster_id:l(n),only_manageable_rewards:e?.toString()}}s(sn,"createCustomRewardsQuery");function bi(n,e){return{broadcaster_id:l(n),id:e}}s(bi,"createCustomRewardChangeQuery");function Si(n){let e={title:n.title,cost:n.cost,prompt:n.prompt,background_color:n.backgroundColor,is_enabled:n.isEnabled,is_user_input_required:n.userInputRequired,should_redemptions_skip_request_queue:n.autoFulfill};return n.maxRedemptionsPerStream!==void 0&&(e.is_max_per_stream_enabled=!!n.maxRedemptionsPerStream,e.max_per_stream=n.maxRedemptionsPerStream??0),n.maxRedemptionsPerUserPerStream!==void 0&&(e.is_max_per_user_per_stream_enabled=!!n.maxRedemptionsPerUserPerStream,e.max_per_user_per_stream=n.maxRedemptionsPerUserPerStream??0),n.globalCooldown!==void 0&&(e.is_global_cooldown_enabled=!!n.globalCooldown,e.global_cooldown_seconds=n.globalCooldown??0),"isPaused"in n&&(e.is_paused=n.isPaused),e}s(Si,"createCustomRewardBody");function Ci(n,e,t){return{broadcaster_id:l(n),reward_id:e,id:t}}s(Ci,"createRewardRedemptionsByIdsQuery");function vi(n,e,t,r){return{broadcaster_id:l(n),reward_id:e,status:t,sort:r.newestFirst?"NEWEST":"OLDEST"}}s(vi,"createRedemptionsForBroadcasterQuery");var me=class extends d{static{s(this,"HelixCustomReward")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}getImageUrl(e){let t=`url_${e}x`;return this[i].image?.[t]??this[i].default_image[t]}get backgroundColor(){return this[i].background_color}get isEnabled(){return this[i].is_enabled}get cost(){return this[i].cost}get title(){return this[i].title}get prompt(){return this[i].prompt}get userInputRequired(){return this[i].is_user_input_required}get maxRedemptionsPerStream(){return this[i].max_per_stream_setting.is_enabled?this[i].max_per_stream_setting.max_per_stream:null}get maxRedemptionsPerUserPerStream(){return this[i].max_per_user_per_stream_setting.is_enabled?this[i].max_per_user_per_stream_setting.max_per_user_per_stream:null}get globalCooldown(){return this[i].global_cooldown_setting.is_enabled?this[i].global_cooldown_setting.global_cooldown_seconds:null}get isPaused(){return this[i].is_paused}get isInStock(){return this[i].is_in_stock}get redemptionsThisStream(){return this[i].redemptions_redeemed_current_stream}get autoFulfill(){return this[i].should_redemptions_skip_request_queue}get cooldownExpiryDate(){return this[i].cooldown_expires_at?new Date(this[i].cooldown_expires_at):null}};o([h(!1)],me.prototype,"_client",void 0);me=o([u("api","HelixCustomReward","id")],me);var he=class extends d{static{s(this,"HelixCustomRewardRedemption")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get userInput(){return this[i].user_input}get isFulfilled(){return this[i].status==="FULFILLED"}get isCanceled(){return this[i].status==="CANCELED"}get redemptionDate(){return new Date(this[i].redeemed_at)}get rewardId(){return this[i].reward.id}get rewardTitle(){return this[i].reward.title}get rewardPrompt(){return this[i].reward.prompt}get rewardCost(){return this[i].reward.cost}async getReward(){return p(await this._client.channelPoints.getCustomRewardById(this[i].broadcaster_id,this[i].reward.id))}async updateStatus(e){return(await this._client.channelPoints.updateRedemptionStatusByIds(this[i].broadcaster_id,this[i].reward.id,[this[i].id],e))[0]}};o([h(!1)],he.prototype,"_client",void 0);he=o([u("api","HelixCustomRewardRedemption","id")],he);var Ir=class extends y{static{s(this,"HelixChannelPointsApi")}async getCustomRewards(e,t){return(await this._client.callApi({type:"helix",url:"channel_points/custom_rewards",userId:l(e),scopes:["channel:read:redemptions","channel:manage:redemptions"],query:sn(e,t)})).data.map(a=>new me(a,this._client))}async getCustomRewardsByIds(e,t){return t.length?(await this._client.callApi({type:"helix",url:"channel_points/custom_rewards",userId:l(e),scopes:["channel:read:redemptions","channel:manage:redemptions"],query:de(e,t)})).data.map(a=>new me(a,this._client)):[]}async getCustomRewardById(e,t){let r=await this.getCustomRewardsByIds(e,[t]);return r.length?r[0]:null}async createCustomReward(e,t){let r=await this._client.callApi({type:"helix",url:"channel_points/custom_rewards",method:"POST",userId:l(e),scopes:["channel:manage:redemptions"],query:w(e),jsonBody:Si(t)});return new me(r.data[0],this._client)}async updateCustomReward(e,t,r){let a=await this._client.callApi({type:"helix",url:"channel_points/custom_rewards",method:"PATCH",userId:l(e),scopes:["channel:manage:redemptions"],query:bi(e,t),jsonBody:Si(r)});return new me(a.data[0],this._client)}async deleteCustomReward(e,t){await this._client.callApi({type:"helix",url:"channel_points/custom_rewards",method:"DELETE",userId:l(e),scopes:["channel:manage:redemptions"],query:bi(e,t)})}async getRedemptionsByIds(e,t,r){return r.length?(await this._client.callApi({type:"helix",url:"channel_points/custom_rewards/redemptions",userId:l(e),scopes:["channel:read:redemptions","channel:manage:redemptions"],query:Ci(e,t,r)})).data.map(c=>new he(c,this._client)):[]}async getRedemptionById(e,t,r){let a=await this.getRedemptionsByIds(e,t,[r]);return a.length?a[0]:null}async getRedemptionsForBroadcaster(e,t,r,a){let c=await this._client.callApi({type:"helix",url:"channel_points/custom_rewards/redemptions",userId:l(e),scopes:["channel:read:redemptions","channel:manage:redemptions"],query:{...vi(e,t,r,a),...x(a)}});return v(c,he,this._client)}getRedemptionsForBroadcasterPaginated(e,t,r,a){return new S({url:"channel_points/custom_rewards/redemptions",userId:l(e),scopes:["channel:read:redemptions","channel:manage:redemptions"],query:vi(e,t,r,a)},this._client,c=>new he(c,this._client),50)}async updateRedemptionStatusByIds(e,t,r,a){return r.length?(await this._client.callApi({type:"helix",url:"channel_points/custom_rewards/redemptions",method:"PATCH",userId:l(e),scopes:["channel:manage:redemptions"],query:Ci(e,t,r),jsonBody:{status:a}})).data.map(m=>new he(m,this._client)):[]}};Ir=o([u("api","HelixChannelPointsApi")],Ir);var Se=class extends d{static{s(this,"HelixCharityCampaignAmount")}get value(){return this[i].value}get decimalPlaces(){return this[i].decimal_places}get localizedValue(){return this.value/10**this.decimalPlaces}get currency(){return this[i].currency}};Se=o([u("api","HelixCharityCampaignAmount")],Se);var At=class extends d{static{s(this,"HelixCharityCampaign")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get charityName(){return this[i].charity_name}get charityDescription(){return this[i].charity_description}get charityLogo(){return this[i].charity_logo}get charityWebsite(){return this[i].charity_website}get currentAmount(){return new Se(this[i].current_amount)}get targetAmount(){return new Se(this[i].target_amount)}};o([h(!1)],At.prototype,"_client",void 0);At=o([u("api","HelixCharityCampaign","id")],At);var Et=class extends d{static{s(this,"HelixCharityCampaignDonation")}_client;constructor(e,t){super(e),this._client=t}get campaignId(){return this[i].campaign_id}get donorId(){return this[i].user_id}get donorName(){return this[i].user_login}get donorDisplayName(){return this[i].user_name}async getDonor(){return p(await this._client.users.getUserById(this[i].user_id))}get amount(){return new Se(this[i].amount)}};o([h(!1)],Et.prototype,"_client",void 0);Et=o([u("api","HelixCharityCampaignDonation")],Et);var Ar=class extends y{static{s(this,"HelixCharityApi")}async getCharityCampaign(e){let t=await this._client.callApi({type:"helix",url:"charity/campaigns",method:"GET",userId:l(e),scopes:["channel:read:charity"],query:w(e)});return new At(t.data[0],this._client)}async getCharityCampaignDonations(e,t){let r=await this._client.callApi({type:"helix",url:"charity/donations",userId:l(e),scopes:["channel:read:charity"],query:{...w(e),...x(t)}});return v(r,Et,this._client)}};Ar=o([u("api","HelixCharityApi")],Ar);var Er=class extends P{static{s(this,"ChatMessageDroppedError")}_code;constructor(e,t,r){super(`Chat message to channel ${e} dropped: ${t??"unknown reason"}`),this._code=r}get code(){return this._code}};function an(n){return{slow_mode:n.slowModeEnabled,slow_mode_wait_time:n.slowModeDelay,follower_mode:n.followerOnlyModeEnabled,follower_mode_duration:n.followerOnlyModeDelay,subscriber_mode:n.subscriberOnlyModeEnabled,emote_mode:n.emoteOnlyModeEnabled,unique_chat_mode:n.uniqueChatModeEnabled,non_moderator_chat_delay:n.nonModeratorChatDelayEnabled,non_moderator_chat_delay_duration:n.nonModeratorChatDelay}}s(an,"createChatSettingsUpdateBody");function on(n,e){return{user_id:l(n),color:e}}s(on,"createChatColorUpdateQuery");function ln(n,e,t){return{from_broadcaster_id:l(n),to_broadcaster_id:l(e),moderator_id:t}}s(ln,"createShoutoutQuery");function Ii(n,e){return{broadcaster_id:n,sender_id:e}}s(Ii,"createSendChatMessageQuery");function cn(n,e){return{message:n,reply_parent_message_id:e?.replyParentMessageId}}s(cn,"createSendChatMessageBody");function un(n,e){return{message:n,reply_parent_message_id:e?.replyParentMessageId,for_source_only:e?.forSourceOnly}}s(un,"createSendChatMessageAsAppBody");function dn(n){return{broadcaster_id:l(n)}}s(dn,"createSharedChatSessionQuery");var Ne=class extends d{static{s(this,"HelixEmoteBase")}get id(){return this[i].id}get name(){return this[i].name}get formats(){return this[i].format}get scales(){return this[i].scale}get themeModes(){return this[i].theme_mode}getStaticImageUrl(e="1.0",t="light"){return this[i].format.includes("static")&&this[i].scale.includes(e)?this.getFormattedImageUrl(e,"static",t):null}getAnimatedImageUrl(e="1.0",t="light"){return this[i].format.includes("animated")&&this[i].scale.includes(e)?this.getFormattedImageUrl(e,"animated",t):null}getFormattedImageUrl(e="1.0",t="static",r="light"){return`https://static-cdn.jtvnw.net/emoticons/v2/${this[i].id}/${t}/${r}/${e}`}};var pe=class extends Ne{static{s(this,"HelixEmote")}getImageUrl(e){return this[i].images[`url_${e}x`]}};pe=o([u("api","HelixEmote","id")],pe);var Tt=class extends pe{static{s(this,"HelixChannelEmote")}_client;constructor(e,t){super(e),this._client=t}get tier(){return this[i].tier||null}get type(){return this[i].emote_type}get emoteSetId(){return this[i].emote_set_id}async getAllEmotesFromSet(){return await this._client.chat.getEmotesFromSets([this[i].emote_set_id])}};o([h(!1)],Tt.prototype,"_client",void 0);Tt=o([u("api","HelixChannelEmote","id")],Tt);var Tr=class extends d{static{s(this,"HelixChatBadgeVersion")}get id(){return this[i].id}getImageUrl(e){return this[i][`image_url_${e}x`]}get title(){return this[i].title}get description(){return this[i].description}get clickAction(){return this[i].click_action}get clickUrl(){return this[i].click_url}};Tr=o([u("api","HelixChatBadgeVersion","id")],Tr);var Fe=class extends d{static{s(this,"HelixChatBadgeSet")}get id(){return this[i].set_id}get versions(){return this[i].versions.map(e=>new Tr(e))}getVersion(e){return this.versions.find(t=>t.id===e)??null}};o([A()],Fe.prototype,"versions",null);Fe=o([J,u("api","HelixChatBadgeSet","id")],Fe);var je=class extends d{static{s(this,"HelixChatChatter")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],je.prototype,"_client",void 0);je=o([u("api","HelixChatChatter")],je);var Le=class extends d{static{s(this,"HelixChatSettings")}get broadcasterId(){return this[i].broadcaster_id}get slowModeEnabled(){return this[i].slow_mode}get slowModeDelay(){return this[i].slow_mode_wait_time}get followerOnlyModeEnabled(){return this[i].follower_mode}get followerOnlyModeDelay(){return this[i].follower_mode_duration}get subscriberOnlyModeEnabled(){return this[i].subscriber_mode}get emoteOnlyModeEnabled(){return this[i].emote_mode}get uniqueChatModeEnabled(){return this[i].unique_chat_mode}};Le=o([u("api","HelixChatSettings","broadcasterId")],Le);var Ht=class extends pe{static{s(this,"HelixEmoteFromSet")}_client;constructor(e,t){super(e),this._client=t}get type(){return this[i].emote_type}get emoteSetId(){return this[i].emote_set_id}get ownerId(){switch(this[i].owner_id){case"0":case"twitch":return null;default:return this[i].owner_id}}async getOwner(){switch(this[i].owner_id){case"0":case"twitch":return null;default:return await this._client.users.getUserById(this[i].owner_id)}}};o([h(!1)],Ht.prototype,"_client",void 0);Ht=o([u("api","HelixEmoteFromSet","id")],Ht);var Bt=class extends Le{static{s(this,"HelixPrivilegedChatSettings")}get nonModeratorChatDelayEnabled(){return this[i].non_moderator_chat_delay}get nonModeratorChatDelay(){return this[i].non_moderator_chat_delay_duration}};Bt=o([u("api","HelixPrivilegedChatSettings","broadcasterId")],Bt);var Ut=class extends d{static{s(this,"HelixSentChatMessage")}get id(){return this[i].message_id}get isSent(){return this[i].is_sent}get dropReasonCode(){return this[i].drop_reason?.code}get dropReasonMessage(){return this[i].drop_reason?.message}};Ut=o([u("api","HelixSentChatMessage","id")],Ut);var Rt=class extends d{static{s(this,"HelixSharedChatSessionParticipant")}_client;constructor(e,t){super(e),this._client=t}get broadcasterId(){return this[i].broadcaster_id}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}};o([h(!1)],Rt.prototype,"_client",void 0);Rt=o([u("api","HelixSharedChatSessionParticipant","broadcasterId")],Rt);var Dt=class extends d{static{s(this,"HelixSharedChatSession")}_client;constructor(e,t){super(e),this._client=t}get sessionId(){return this[i].session_id}get hostBroadcasterId(){return this[i].host_broadcaster_id}async getHostBroadcaster(){return p(await this._client.users.getUserById(this[i].host_broadcaster_id))}get participants(){return this[i].participants.map(e=>new Rt(e,this._client))}get createdDate(){return new Date(this[i].created_at)}get updatedDate(){return new Date(this[i].updated_at)}};o([h(!1)],Dt.prototype,"_client",void 0);Dt=o([u("api","HelixSharedChatSession","sessionId")],Dt);var Qe=class extends Ne{static{s(this,"HelixUserEmote")}_client;constructor(e,t){super(e),this._client=t}get type(){return this[i].emote_type}get emoteSetId(){return this[i].emote_set_id||null}get ownerId(){return this[i].owner_id||null}async getAllEmotesFromSet(){return this[i].emote_set_id?await this._client.chat.getEmotesFromSets([this[i].emote_set_id]):null}async getOwner(){return this[i].owner_id?await this._client.users.getUserById(this[i].owner_id):null}};o([h(!1)],Qe.prototype,"_client",void 0);Qe=o([u("api","HelixUserEmote","id")],Qe);var Hr=class extends y{static{s(this,"HelixChatApi")}async getChatters(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"chat/chatters",userId:r,canOverrideScopedUserContext:!0,scopes:["moderator:read:chatters"],query:{...this._createModeratorActionQuery(r),...x(t)}});return j(a,je,this._client)}getChattersPaginated(e){let t=l(e);return new L({url:"chat/chatters",userId:t,canOverrideScopedUserContext:!0,scopes:["moderator:read:chatters"],query:this._createModeratorActionQuery(t)},this._client,r=>new je(r,this._client),1e3)}async getGlobalBadges(){return(await this._client.callApi({type:"helix",url:"chat/badges/global"})).data.map(t=>new Fe(t))}async getChannelBadges(e){return(await this._client.callApi({type:"helix",url:"chat/badges",userId:l(e),query:w(e)})).data.map(r=>new Fe(r))}async getGlobalEmotes(){return(await this._client.callApi({type:"helix",url:"chat/emotes/global"})).data.map(t=>new pe(t))}async getChannelEmotes(e){return(await this._client.callApi({type:"helix",url:"chat/emotes",userId:l(e),query:w(e)})).data.map(r=>new Tt(r,this._client))}async getEmotesFromSets(e){return(await this._client.callApi({type:"helix",url:"chat/emotes/set",query:I("emote_set_id",e)})).data.map(r=>new Ht(r,this._client))}async getUserEmotes(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"chat/emotes/user",userId:l(e),scopes:["user:read:emotes"],query:{...I("user_id",r),...I("broadcasterId",t?.broadcaster?l(t.broadcaster):void 0),...x(t)}});return v(a,Qe,this._client)}getUserEmotesPaginated(e,t){let r=l(e);return new S({url:"chat/emotes/user",userId:r,scopes:["user:read:emotes"],query:{...I("user_id",r),...I("broadcasterId",t?l(t):void 0)}},this._client,a=>new Qe(a,this._client))}async getSettings(e){let t=await this._client.callApi({type:"helix",url:"chat/settings",userId:l(e),query:w(e)});return new Le(t.data[0])}async getSettingsPrivileged(e){let t=l(e),r=await this._client.callApi({type:"helix",url:"chat/settings",userId:t,canOverrideScopedUserContext:!0,scopes:["moderator:read:chat_settings"],query:this._createModeratorActionQuery(t)});return new Bt(r.data[0])}async updateSettings(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"chat/settings",method:"PATCH",userId:r,canOverrideScopedUserContext:!0,scopes:["moderator:manage:chat_settings"],query:this._createModeratorActionQuery(r),jsonBody:an(t)});return new Bt(a.data[0])}async sendChatMessage(e,t,r){let a=l(e),c=await this._client.callApi({type:"helix",url:"chat/messages",method:"POST",userId:a,canOverrideScopedUserContext:!0,scopes:["user:write:chat"],query:Ii(a,this._getUserContextIdWithDefault(a)),jsonBody:cn(t,r)}),m=new Ut(c.data[0]);return this._handleUnsentChatMessage(a,m),m}async sendChatMessageAsApp(e,t,r,a){let c=l(e),m=l(t),_=await this._client.callApi({type:"helix",url:"chat/messages",method:"POST",forceType:"app",query:Ii(m,c),jsonBody:un(r,a)}),f=new Ut(_.data[0]);return this._handleUnsentChatMessage(m,f),f}async sendAnnouncement(e,t){let r=l(e);await this._client.callApi({type:"helix",url:"chat/announcements",method:"POST",userId:r,canOverrideScopedUserContext:!0,scopes:["moderator:manage:announcements"],query:this._createModeratorActionQuery(r),jsonBody:{message:t.message,color:t.color}})}async getColorsForUsers(e){let t=await this._client.callApi({type:"helix",url:"chat/color",query:I("user_id",e.map(l))});return new Map(t.data.map(r=>[r.user_id,r.color||null]))}async getColorForUser(e){let t=await this._client.callApi({type:"helix",url:"chat/color",userId:l(e),query:I("user_id",l(e))});if(t.data.length)return t.data[0].color||null}async setColorForUser(e,t){await this._client.callApi({type:"helix",url:"chat/color",method:"PUT",userId:l(e),scopes:["user:manage:chat_color"],query:on(e,t)})}async shoutoutUser(e,t){let r=l(e);await this._client.callApi({type:"helix",url:"chat/shoutouts",method:"POST",userId:r,canOverrideScopedUserContext:!0,scopes:["moderator:manage:shoutouts"],query:ln(e,t,this._getUserContextIdWithDefault(r))})}async getSharedChatSession(e){let t=l(e),r=await this._client.callApi({type:"helix",url:"shared_chat/session",userId:t,query:dn(t)});return r.data.length===0?null:new Dt(r.data[0],this._client)}_createModeratorActionQuery(e){return br(e,this._getUserContextIdWithDefault(e))}_handleUnsentChatMessage(e,t){if(!t.isSent)throw new Er(e,t.dropReasonMessage,t.dropReasonCode)}};Hr=o([u("api","HelixChatApi")],Hr);function mn(n){let{channel:e,createAfterDelay:t=!1,title:r,duration:a}=n;return{broadcaster_id:l(e),has_delay:t.toString(),title:r,duration:a?.toFixed(1)}}s(mn,"createClipCreateQuery");function hn(n,e){let{channel:t,title:r,duration:a,vodId:c,vodOffset:m}=n;return{broadcaster_id:l(t),editor_id:e,title:r,duration:a?.toFixed(1),vod_id:c,vod_offset:m.toString()}}s(hn,"createClipCreateFromVodQuery");function Ai(n){let{filterType:e,ids:t,startDate:r,endDate:a,isFeatured:c}=n;return{[e]:t,started_at:r,ended_at:a,is_featured:c?.toString()}}s(Ai,"createClipQuery");var Ce=class extends d{static{s(this,"HelixClip")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get url(){return this[i].url}get embedUrl(){return this[i].embed_url}get broadcasterId(){return this[i].broadcaster_id}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get creatorId(){return this[i].creator_id}get creatorDisplayName(){return this[i].creator_name}async getCreator(){return p(await this._client.users.getUserById(this[i].creator_id))}get videoId(){return this[i].video_id}async getVideo(){return p(await this._client.videos.getVideoById(this[i].video_id))}get gameId(){return this[i].game_id}async getGame(){return this[i].game_id?p(await this._client.games.getGameById(this[i].game_id)):null}get language(){return this[i].language}get title(){return this[i].title}get views(){return this[i].view_count}get creationDate(){return new Date(this[i].created_at)}get thumbnailUrl(){return this[i].thumbnail_url}get duration(){return this[i].duration}get vodOffset(){return this[i].vod_offset}get isFeatured(){return this[i].is_featured}};o([h(!1)],Ce.prototype,"_client",void 0);Ce=o([u("api","HelixClip","id")],Ce);var Pt=class extends y{static{s(this,"HelixClipApi")}_getClipByIdBatcher=new U({url:"clips"},"id","id",this._client,e=>new Ce(e,this._client));async getClipsForBroadcaster(e,t={}){return await this._getClips({...t,filterType:"broadcaster_id",ids:l(e),userId:l(e)})}getClipsForBroadcasterPaginated(e,t={}){return this._getClipsPaginated({...t,filterType:"broadcaster_id",ids:l(e),userId:l(e)})}async getClipsForGame(e,t={}){return await this._getClips({...t,filterType:"game_id",ids:e})}getClipsForGamePaginated(e,t={}){return this._getClipsPaginated({...t,filterType:"game_id",ids:e})}async getClipsByIds(e){return(await this._getClips({filterType:"id",ids:e})).data}async getClipById(e){let t=await this.getClipsByIds([e]);return t.length?t[0]:null}async getClipByIdBatched(e){return await this._getClipByIdBatcher.request(e)}async createClip(e){return(await this._client.callApi({type:"helix",url:"clips",method:"POST",userId:l(e.channel),scopes:["clips:edit"],canOverrideScopedUserContext:!0,query:mn(e)})).data[0].id}async createClipFromVod(e){let t=l(e.channel);return(await this._client.callApi({type:"helix",url:"videos/clips",method:"POST",userId:t,scopes:["editor:manage:clips","channel:manage:clips"],canOverrideScopedUserContext:!0,query:hn(e,this._getUserContextIdWithDefault(t))})).data[0].id}async _getClips(e){if(!e.ids.length)return{data:[]};let t=await this._client.callApi({type:"helix",url:"clips",userId:e.userId,query:{...Ai(e),...x(e)}});return v(t,Ce,this._client)}_getClipsPaginated(e){return new S({url:"clips",userId:e.userId,query:Ai(e)},this._client,t=>new Ce(t,this._client))}};o([h(!1)],Pt.prototype,"_getClipByIdBatcher",void 0);Pt=o([u("api","HelixClipApi")],Pt);var Br=class extends d{static{s(this,"HelixContentClassificationLabel")}get id(){return this[i].id}get name(){return this[i].name}get description(){return this[i].description}};var Ur=class extends y{static{s(this,"HelixContentClassificationLabelApi")}async getAll(e){return(await this._client.callApi({url:"content_classification_labels",query:{locale:e}})).data.map(r=>new Br(r))}};Ur=o([u("api","HelixContentClassificationLabelApi")],Ur);function Ei(n,e){return{user_id:e?D(n.user,l):void 0,game_id:n.gameId,fulfillment_status:n.fulfillmentStatus}}s(Ei,"createDropsEntitlementQuery");function pn(n,e){return{fulfillment_status:e,entitlement_ids:n}}s(pn,"createDropsEntitlementUpdateBody");var _e=class extends d{static{s(this,"HelixDropsEntitlement")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get rewardId(){return this[i].benefit_id}get grantDate(){return new Date(this[i].timestamp)}get userId(){return this[i].user_id}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get gameId(){return this[i].game_id}async getGame(){return p(await this._client.games.getGameById(this[i].game_id))}get fulfillmentStatus(){return this[i].fulfillment_status}get updateDate(){return new Date(this[i].last_updated)}};o([h(!1)],_e.prototype,"_client",void 0);_e=o([u("api","HelixDropsEntitlement")],_e);var kt=class extends y{static{s(this,"HelixEntitlementApi")}_getDropsEntitlementByIdBatcher=new U({url:"entitlements/drops"},"id","id",this._client,e=>new _e(e,this._client));async getDropsEntitlements(e,t=!1){let r=await this._client.callApi({type:"helix",url:"entitlements/drops",userId:D(e.user,l),forceType:e.user&&t?"app":void 0,query:{...Ei(e,t),...x(e)}});return v(r,_e,this._client)}getDropsEntitlementsPaginated(e,t=!1){return new S({url:"entitlements/drops",userId:D(e.user,l),forceType:e.user&&t?"app":void 0,query:Ei(e,t)},this._client,r=>new _e(r,this._client))}async getDropsEntitlementsByIds(e){return(await this._client.callApi({type:"helix",url:"entitlements/drops",query:{id:e}})).data.map(r=>new _e(r,this._client))}async getDropsEntitlementById(e){return(await this.getDropsEntitlementsByIds([e]))[0]??null}async getDropsEntitlementByIdBatched(e){return await this._getDropsEntitlementByIdBatcher.request(e)}async updateDropsEntitlements(e,t){let r=await this._client.callApi({type:"helix",url:"entitlements/drops",method:"PATCH",jsonBody:pn(e,t)});return new Map(r.data.flatMap(a=>a.ids.map(c=>[c,a.status])))}};o([h(!1)],kt.prototype,"_getDropsEntitlementByIdBatcher",void 0);kt=o([u("api","HelixEntitlementApi")],kt);function b(n){return{broadcaster_user_id:l(n)}}s(b,"createEventSubBroadcasterCondition");function qt(n,e){return{broadcaster_user_id:l(n),reward_id:e}}s(qt,"createEventSubRewardCondition");function R(n,e){return{broadcaster_user_id:n,moderator_user_id:e}}s(R,"createEventSubModeratorCondition");function X(n,e){return{broadcaster_user_id:n,user_id:e}}s(X,"createEventSubUserCondition");function _n(n){return{organization_id:n.organizationId,category_id:n.categoryId,campaign_id:n.campaignId}}s(_n,"createEventSubDropEntitlementGrantCondition");function Ti(n,e){return{conduit_id:n,status:e}}s(Ti,"createEventSubConduitCondition");function fn(n,e){return{id:n,shard_count:e.toString()}}s(fn,"createEventSubConduitUpdateCondition");function gn(n,e){return{conduit_id:n,shards:e}}s(gn,"createEventSubConduitShardsUpdateCondition");var Q=class extends d{static{s(this,"HelixEventSubSubscription")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get status(){return this[i].status}get type(){return this[i].type}get cost(){return this[i].cost}get condition(){return this[i].condition}get creationDate(){return new Date(this[i].created_at)}get transportMethod(){return this[i].transport.method}async unsubscribe(){await this._client.eventSub.deleteSubscription(this[i].id)}get _transport(){return this[i].transport}set _status(e){this[i].status=e}};o([h(!1)],Q.prototype,"_client",void 0);Q=o([u("api","HelixEventSubSubscription","id")],Q);var ve=class extends L{static{s(this,"HelixPaginatedEventSubSubscriptionsRequest")}constructor(e,t,r){super({url:"eventsub/subscriptions",userId:t,query:e},r,a=>new Q(a,r))}async getTotalCost(){return(this._currentData??await this._fetchData({query:{after:void 0}})).total_cost}async getMaxTotalCost(){return(this._currentData??await this._fetchData({query:{after:void 0}})).max_total_cost}};ve=o([u("api","HelixPaginatedEventSubSubscriptionsRequest")],ve);var Ie=class extends d{static{s(this,"HelixEventSubConduit")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get shardCount(){return this[i].shard_count}async update(e){return await this._client.eventSub.updateConduit(this[i].id,e)}async delete(){await this._client.eventSub.deleteConduit(this[i].id)}async getShards(){return await this._client.eventSub.getConduitShards(this[i].id)}};o([h(!1)],Ie.prototype,"_client",void 0);Ie=o([u("api","HelixEventSubConduit")],Ie);var Ge=class extends d{static{s(this,"HelixEventSubConduitShard")}get id(){return this[i].id}get status(){return this[i].status}get transportMethod(){return this[i].transport.method}};Ge=o([u("api","HelixEventSubConduitShard")],Ge);var Rr=class extends y{static{s(this,"HelixEventSubApi")}async getSubscriptions(e){let t=await this._client.callApi({type:"helix",url:"eventsub/subscriptions",query:x(e)});return{...j(t,Q,this._client),totalCost:t.total_cost,maxTotalCost:t.max_total_cost}}getSubscriptionsPaginated(){return new ve({},void 0,this._client)}async getSubscriptionsForStatus(e,t){let r=await this._client.callApi({type:"helix",url:"eventsub/subscriptions",query:{...x(t),status:e}});return{...j(r,Q,this._client),totalCost:r.total_cost,maxTotalCost:r.max_total_cost}}getSubscriptionsForStatusPaginated(e){return new ve({status:e},void 0,this._client)}async getSubscriptionsForType(e,t){let r=await this._client.callApi({type:"helix",url:"eventsub/subscriptions",query:{...x(t),type:e}});return{...j(r,Q,this._client),totalCost:r.total_cost,maxTotalCost:r.max_total_cost}}getSubscriptionsForTypePaginated(e){return new ve({type:e},void 0,this._client)}async getSubscriptionsForUser(e,t){let r=await this._client.callApi({type:"helix",url:"eventsub/subscriptions",userId:l(e),query:{...I("user_id",l(e)),...x(t)}});return{...j(r,Q,this._client),totalCost:r.total_cost,maxTotalCost:r.max_total_cost}}getSubscriptionsForUserPaginated(e){let t=l(e);return new ve(I("user_id",t),t,this._client)}async createSubscription(e,t,r,a,c,m,_,f){let C=a.method==="webhook"||a.method==="conduit",T=C?void 0:m;if(!C&&!c)throw new Error(`Transport ${a.method} can only handle subscriptions with user context`);let k={type:e,version:t,condition:r,transport:a};f&&(k.is_batching_enabled=!0);let q=await this._client.callApi({type:"helix",url:"eventsub/subscriptions",method:"POST",scopes:T,userId:D(c,l),canOverrideScopedUserContext:_,forceType:C?"app":"user",jsonBody:k});return new Q(q.data[0],this._client)}async deleteSubscription(e){await this._client.callApi({type:"helix",url:"eventsub/subscriptions",method:"DELETE",query:{id:e}})}async deleteAllSubscriptions(){await this._deleteSubscriptionsWithCondition()}async deleteBrokenSubscriptions(){await this._deleteSubscriptionsWithCondition(e=>e.status!=="enabled"&&e.status!=="webhook_callback_verification_pending")}async subscribeToStreamOnlineEvents(e,t){return await this.createSubscription("stream.online","1",b(e),t,e)}async subscribeToStreamOfflineEvents(e,t){return await this.createSubscription("stream.offline","1",b(e),t,e)}async subscribeToChannelUpdateEvents(e,t){return await this.createSubscription("channel.update","2",b(e),t,e)}async subscribeToChannelFollowEvents(e,t){let r=l(e);return await this.createSubscription("channel.follow","2",R(r,this._getUserContextIdWithDefault(r)),t,r,["moderator:read:followers"],!0)}async subscribeToChannelSubscriptionEvents(e,t){return await this.createSubscription("channel.subscribe","1",b(e),t,e,["channel:read:subscriptions"])}async subscribeToChannelSubscriptionGiftEvents(e,t){return await this.createSubscription("channel.subscription.gift","1",b(e),t,e,["channel:read:subscriptions"])}async subscribeToChannelSubscriptionMessageEvents(e,t){return await this.createSubscription("channel.subscription.message","1",b(e),t,e,["channel:read:subscriptions"])}async subscribeToChannelSubscriptionEndEvents(e,t){return await this.createSubscription("channel.subscription.end","1",b(e),t,e,["channel:read:subscriptions"])}async subscribeToChannelCheerEvents(e,t){return await this.createSubscription("channel.cheer","1",b(e),t,e,["bits:read"])}async subscribeToChannelCharityCampaignStartEvents(e,t){return await this.createSubscription("channel.charity_campaign.start","1",b(e),t,e,["channel:read:charity"])}async subscribeToChannelCharityCampaignStopEvents(e,t){return await this.createSubscription("channel.charity_campaign.stop","1",b(e),t,e,["channel:read:charity"])}async subscribeToChannelCharityDonationEvents(e,t){return await this.createSubscription("channel.charity_campaign.donate","1",b(e),t,e,["channel:read:charity"])}async subscribeToChannelCharityCampaignProgressEvents(e,t){return await this.createSubscription("channel.charity_campaign.progress","1",b(e),t,e,["channel:read:charity"])}async subscribeToChannelBanEvents(e,t){return await this.createSubscription("channel.ban","1",b(e),t,e,["channel:moderate"])}async subscribeToChannelUnbanEvents(e,t){return await this.createSubscription("channel.unban","1",b(e),t,e,["channel:moderate"])}async subscribeToChannelShieldModeBeginEvents(e,t){let r=l(e);return await this.createSubscription("channel.shield_mode.begin","1",R(r,this._getUserContextIdWithDefault(r)),t,r,["moderator:read:shield_mode","moderator:manage:shield_mode"],!0)}async subscribeToChannelShieldModeEndEvents(e,t){let r=l(e);return await this.createSubscription("channel.shield_mode.end","1",R(r,this._getUserContextIdWithDefault(r)),t,r,["moderator:read:shield_mode","moderator:manage:shield_mode"],!0)}async subscribeToChannelModeratorAddEvents(e,t){return await this.createSubscription("channel.moderator.add","1",b(e),t,e,["moderation:read"])}async subscribeToChannelModeratorRemoveEvents(e,t){return await this.createSubscription("channel.moderator.remove","1",b(e),t,e,["moderation:read"])}async subscribeToChannelRaidEventsFrom(e,t){return await this.createSubscription("channel.raid","1",I("from_broadcaster_user_id",l(e)),t,e)}async subscribeToChannelRaidEventsTo(e,t){return await this.createSubscription("channel.raid","1",I("to_broadcaster_user_id",l(e)),t,e)}async subscribeToChannelRewardAddEvents(e,t){return await this.createSubscription("channel.channel_points_custom_reward.add","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRewardUpdateEvents(e,t){return await this.createSubscription("channel.channel_points_custom_reward.update","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRewardUpdateEventsForReward(e,t,r){return await this.createSubscription("channel.channel_points_custom_reward.update","1",qt(e,t),r,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRewardRemoveEvents(e,t){return await this.createSubscription("channel.channel_points_custom_reward.remove","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRewardRemoveEventsForReward(e,t,r){return await this.createSubscription("channel.channel_points_custom_reward.remove","1",qt(e,t),r,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRedemptionAddEvents(e,t){return await this.createSubscription("channel.channel_points_custom_reward_redemption.add","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRedemptionAddEventsForReward(e,t,r){return await this.createSubscription("channel.channel_points_custom_reward_redemption.add","1",qt(e,t),r,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRedemptionUpdateEvents(e,t){return await this.createSubscription("channel.channel_points_custom_reward_redemption.update","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelRedemptionUpdateEventsForReward(e,t,r){return await this.createSubscription("channel.channel_points_custom_reward_redemption.update","1",qt(e,t),r,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelAutomaticRewardRedemptionAddEvents(e,t){return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add","1",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelAutomaticRewardRedemptionAddV2Events(e,t){return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add","2",b(e),t,e,["channel:read:redemptions","channel:manage:redemptions"])}async subscribeToChannelPollBeginEvents(e,t){return await this.createSubscription("channel.poll.begin","1",b(e),t,e,["channel:read:polls","channel:manage:polls"])}async subscribeToChannelPollProgressEvents(e,t){return await this.createSubscription("channel.poll.progress","1",b(e),t,e,["channel:read:polls","channel:manage:polls"])}async subscribeToChannelPollEndEvents(e,t){return await this.createSubscription("channel.poll.end","1",b(e),t,e,["channel:read:polls","channel:manage:polls"])}async subscribeToChannelPredictionBeginEvents(e,t){return await this.createSubscription("channel.prediction.begin","1",b(e),t,e,["channel:read:predictions","channel:manage:predictions"])}async subscribeToChannelPredictionProgressEvents(e,t){return await this.createSubscription("channel.prediction.progress","1",b(e),t,e,["channel:read:predictions","channel:manage:predictions"])}async subscribeToChannelPredictionLockEvents(e,t){return await this.createSubscription("channel.prediction.lock","1",b(e),t,e,["channel:read:predictions","channel:manage:predictions"])}async subscribeToChannelPredictionEndEvents(e,t){return await this.createSubscription("channel.prediction.end","1",b(e),t,e,["channel:read:predictions","channel:manage:predictions"])}async subscribeToChannelGoalBeginEvents(e,t){return await this.createSubscription("channel.goal.begin","1",b(e),t,e,["channel:read:goals"])}async subscribeToChannelGoalProgressEvents(e,t){return await this.createSubscription("channel.goal.progress","1",b(e),t,e,["channel:read:goals"])}async subscribeToChannelGoalEndEvents(e,t){return await this.createSubscription("channel.goal.end","1",b(e),t,e,["channel:read:goals"])}async subscribeToChannelHypeTrainBeginEvents(e,t){return await this.createSubscription("channel.hype_train.begin","1",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelHypeTrainProgressEvents(e,t){return await this.createSubscription("channel.hype_train.progress","1",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelHypeTrainEndEvents(e,t){return await this.createSubscription("channel.hype_train.end","1",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelHypeTrainBeginV2Events(e,t){return await this.createSubscription("channel.hype_train.begin","2",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelHypeTrainProgressV2Events(e,t){return await this.createSubscription("channel.hype_train.progress","2",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelHypeTrainEndV2Events(e,t){return await this.createSubscription("channel.hype_train.end","2",b(e),t,e,["channel:read:hype_train"])}async subscribeToChannelShoutoutCreateEvents(e,t){let r=l(e);return await this.createSubscription("channel.shoutout.create","1",R(r,this._getUserContextIdWithDefault(r)),t,r,["moderator:read:shoutouts","moderator:manage:shoutouts"],!0)}async subscribeToChannelShoutoutReceiveEvents(e,t){let r=l(e);return await this.createSubscription("channel.shoutout.receive","1",R(r,this._getUserContextIdWithDefault(r)),t,r,["moderator:read:shoutouts","moderator:manage:shoutouts"],!0)}async subscribeToChannelAdBreakBeginEvents(e,t){return await this.createSubscription("channel.ad_break.begin","1",b(e),t,e,["channel:read:ads"])}async subscribeToChannelChatClearEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.clear","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatClearUserMessagesEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.clear_user_messages","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatMessageDeleteEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.message_delete","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatNotificationEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.notification","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatMessageEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.message","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatSettingsUpdateEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat_settings.update","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelUnbanRequestCreateEvents(e,t){let r=l(e);return await this.createSubscription("channel.unban_request.create","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:unban_requests","moderator:manage:unban_requests"],!0)}async subscribeToChannelUnbanRequestResolveEvents(e,t){let r=l(e);return await this.createSubscription("channel.unban_request.resolve","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:unban_requests","moderator:manage:unban_requests"],!0)}async subscribeToChannelModerateEvents(e,t){let r=l(e);return await this.createSubscription("channel.moderate","2",R(r,this._getUserContextIdWithDefault(r)),t,e,[],!0)}async subscribeToChannelWarningAcknowledgeEvents(e,t){let r=l(e);return await this.createSubscription("channel.warning.acknowledge","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:warnings","moderator:manage:warnings"],!0)}async subscribeToChannelWarningSendEvents(e,t){let r=l(e);return await this.createSubscription("channel.warning.send","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:warnings","moderator:manage:warnings"],!0)}async subscribeToChannelVipAddEvents(e,t){return await this.createSubscription("channel.vip.add","1",b(e),t,e,["channel:read:vips","channel:manage:vips"])}async subscribeToChannelVipRemoveEvents(e,t){return await this.createSubscription("channel.vip.remove","1",b(e),t,e,["channel:read:vips","channel:manage:vips"])}async subscribeToExtensionBitsTransactionCreateEvents(e,t){return await this.createSubscription("extension.bits_transaction.create","1",I("extension_client_id",e),t)}async subscribeToUserAuthorizationGrantEvents(e,t){return await this.createSubscription("user.authorization.grant","1",I("client_id",e),t)}async subscribeToUserAuthorizationRevokeEvents(e,t){return await this.createSubscription("user.authorization.revoke","1",I("client_id",e),t)}async subscribeToUserUpdateEvents(e,t,r){return await this.createSubscription("user.update","1",I("user_id",l(e)),t,e,r?["user:read:email"]:void 0)}async subscribeToUserWhisperMessageEvents(e,t){return await this.createSubscription("user.whisper.message","1",I("user_id",l(e)),t,e,["user:read:whispers","user:manage:whispers"])}async subscribeToDropEntitlementGrantEvents(e,t){return await this.createSubscription("drop.entitlement.grant","1",_n(e),t,void 0,void 0,!1,!0)}async subscribeToAutoModMessageHoldEvents(e,t){let r=l(e);return await this.createSubscription("automod.message.hold","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:manage:automod"],!0)}async subscribeToAutoModMessageUpdateEvents(e,t){let r=l(e);return await this.createSubscription("automod.message.update","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:manage:automod"],!0)}async subscribeToAutoModMessageHoldV2Events(e,t){let r=l(e);return await this.createSubscription("automod.message.hold","2",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:manage:automod"],!0)}async subscribeToAutoModMessageUpdateV2Events(e,t){let r=l(e);return await this.createSubscription("automod.message.update","2",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:manage:automod"],!0)}async subscribeToAutoModSettingsUpdateEvents(e,t){let r=l(e);return await this.createSubscription("automod.settings.update","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:automod_settings"],!0)}async subscribeToAutoModTermsUpdateEvents(e,t){let r=l(e);return await this.createSubscription("automod.terms.update","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:manage:automod"],!0)}async subscribeToChannelChatUserMessageHoldEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.user_message_hold","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelChatUserMessageUpdateEvents(e,t){let r=l(e);return await this.createSubscription("channel.chat.user_message_update","1",X(r,this._getUserContextIdWithDefault(r)),t,e,["user:read:chat"],!0)}async subscribeToChannelSuspiciousUserUpdateEvents(e,t){let r=l(e);return await this.createSubscription("channel.suspicious_user.update","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:suspicious_users"],!0)}async subscribeToChannelSuspiciousUserMessageEvents(e,t){let r=l(e);return await this.createSubscription("channel.suspicious_user.message","1",R(r,this._getUserContextIdWithDefault(r)),t,e,["moderator:read:suspicious_users"],!0)}async subscribeToChannelSharedChatSessionBeginEvents(e,t){let r=l(e);return await this.createSubscription("channel.shared_chat.begin","1",b(r),t,r)}async subscribeToChannelSharedChatSessionUpdateEvents(e,t){let r=l(e);return await this.createSubscription("channel.shared_chat.update","1",b(r),t,r)}async subscribeToChannelSharedChatSessionEndEvents(e,t){let r=l(e);return await this.createSubscription("channel.shared_chat.end","1",b(r),t,r)}async subscribeToChannelBitsUseEvents(e,t){let r=l(e);return await this.createSubscription("channel.bits.use","1",b(r),t,r,["bits:read"])}async getConduits(){return(await this._client.callApi({type:"helix",url:"eventsub/conduits"})).data.map(t=>new Ie(t,this._client))}async createConduit(e){let t=await this._client.callApi({type:"helix",url:"eventsub/conduits",method:"POST",query:{...I("shard_count",e.toString())}});return new Ie(t.data[0],this._client)}async updateConduit(e,t){let r=await this._client.callApi({type:"helix",url:"eventsub/conduits",method:"PATCH",query:fn(e,t)});return new Ie(r.data[0],this._client)}async deleteConduit(e){await this._client.callApi({type:"helix",url:"eventsub/conduits",method:"DELETE",query:{...I("id",e)}})}async getConduitShards(e,t,r){let a=await this._client.callApi({type:"helix",url:"eventsub/conduits/shards",query:{...Ti(e,t),...x(r)}});return{...v(a,Ge,this._client)}}getConduitShardsPaginated(e,t){return new S({url:"eventsub/conduits/shards",query:Ti(e,t)},this._client,r=>new Ge(r))}async updateConduitShards(e,t){return(await this._client.callApi({type:"helix",url:"eventsub/conduits/shards",method:"PATCH",jsonBody:gn(e,t)})).data.map(a=>new Ge(a))}async _deleteSubscriptionsWithCondition(e){let t=this.getSubscriptionsPaginated();for await(let r of t)(!e||e(r))&&await r.unsubscribe()}};Rr=o([u("api","HelixEventSubApi")],Rr);function yn(n,e){return{extension_id:n,extension_version:e}}s(yn,"createReleasedExtensionFilter");function xn(n){return{sku:n.sku,cost:{amount:n.cost,type:"bits"},display_name:n.displayName,in_development:n.inDevelopment,expiration:n.expirationDate,is_broadcast:n.broadcast}}s(xn,"createExtensionProductBody");function Hi(n,e){return{extension_id:n,id:e.transactionIds}}s(Hi,"createExtensionTransactionQuery");var We=class extends d{static{s(this,"HelixChannelReference")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].broadcaster_id}get displayName(){return this[i].broadcaster_name}async getChannel(){return p(await this._client.channels.getChannelInfoById(this[i].broadcaster_id))}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get gameId(){return this[i].game_id}get gameName(){return this[i].game_name}async getGame(){return this[i].game_id?p(await this._client.games.getGameById(this[i].game_id)):null}get title(){return this[i].title}};o([h(!1)],We.prototype,"_client",void 0);We=o([u("api","HelixChannelReference","id")],We);var Ot=class extends d{static{s(this,"HelixExtensionBitsProduct")}get sku(){return this[i].sku}get cost(){return this[i].cost.amount}get displayName(){return this[i].display_name}get inDevelopment(){return this[i].in_development}get isBroadcast(){return this[i].is_broadcast}get expirationDate(){return H(this[i].expiration,e=>new Date(e))}};Ot=o([u("api","HelixExtensionBitsProduct","sku")],Ot);var Ve=class extends d{static{s(this,"HelixExtensionTransaction")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get transactionDate(){return new Date(this[i].timestamp)}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_name}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get productType(){return this[i].product_type}get productSku(){return this[i].product_data.sku}get productCost(){return this[i].product_data.cost.amount}get productDisplayName(){return this[i].product_data.displayName}get productInDevelopment(){return this[i].product_data.inDevelopment}};o([h(!1)],Ve.prototype,"_client",void 0);Ve=o([u("api","HelixExtensionTransaction","id")],Ve);var Dr=class extends y{static{s(this,"HelixExtensionsApi")}async getReleasedExtension(e,t){let r=await this._client.callApi({type:"helix",url:"extensions/released",query:yn(e,t)});return new gt(r.data[0])}async getLiveChannelsWithExtension(e,t){let r=await this._client.callApi({type:"helix",url:"extensions/live",query:{...I("extension_id",e),...x(t)}});return v(r,We,this._client)}getLiveChannelsWithExtensionPaginated(e){return new S({url:"extensions/live",query:I("extension_id",e)},this._client,t=>new We(t,this._client))}async getExtensionBitsProducts(e){return(await this._client.callApi({type:"helix",url:"bits/extensions",forceType:"app",query:I("should_include_all",e?.toString())})).data.map(r=>new Ot(r))}async putExtensionBitsProduct(e){let t=await this._client.callApi({type:"helix",url:"bits/extensions",method:"PUT",forceType:"app",jsonBody:xn(e)});return new Ot(t.data[0])}async getExtensionTransactions(e,t={}){let r=await this._client.callApi({type:"helix",url:"extensions/transactions",forceType:"app",query:{...Hi(e,t),...x(t)}});return v(r,Ve,this._client)}getExtensionTransactionsPaginated(e,t={}){return new S({url:"extensions/transactions",forceType:"app",query:Hi(e,t)},this._client,r=>new Ve(r,this._client))}};Dr=o([u("api","HelixExtensionsApi")],Dr);var N=class extends d{static{s(this,"HelixGame")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get name(){return this[i].name}get boxArtUrl(){return this[i].box_art_url}get igdbId(){return this[i].igdb_id||null}getBoxArtUrl(e,t){return this[i].box_art_url.replace("{width}",e.toString()).replace("{height}",t.toString())}async getStreams(e){return await this._client.streams.getStreams({...e,game:this[i].id})}getStreamsPaginated(){return this._client.streams.getStreamsPaginated({game:this[i].id})}};o([h(!1)],N.prototype,"_client",void 0);N=o([u("api","HelixGame","id")],N);var Ae=class extends y{static{s(this,"HelixGameApi")}_getGameByIdBatcher=new U({url:"games"},"id","id",this._client,e=>new N(e,this._client));_getGameByNameBatcher=new U({url:"games"},"name","name",this._client,e=>new N(e,this._client));_getGameByIgdbIdBatcher=new U({url:"games"},"igdb_id","igdb_id",this._client,e=>new N(e,this._client));async getGamesByIds(e){return await this._getGames("id",e)}async getGamesByNames(e){return await this._getGames("name",e)}async getGamesByIgdbIds(e){return await this._getGames("igdb_id",e)}async getGameById(e){return(await this._getGames("id",[e]))[0]??null}async getGameByName(e){return(await this._getGames("name",[e]))[0]??null}async getGameByIgdbId(e){return(await this._getGames("igdb_id",[e]))[0]??null}async getGameByIdBatched(e){return await this._getGameByIdBatcher.request(e)}async getGameByNameBatched(e){return await this._getGameByNameBatcher.request(e)}async getGameByIgdbIdBatched(e){return await this._getGameByIgdbIdBatcher.request(e)}async getTopGames(e){let t=await this._client.callApi({type:"helix",url:"games/top",query:x(e)});return v(t,N,this._client)}getTopGamesPaginated(){return new S({url:"games/top"},this._client,e=>new N(e,this._client))}async _getGames(e,t){return t.length?(await this._client.callApi({type:"helix",url:"games",query:{[e]:t}})).data.map(a=>new N(a,this._client)):[]}};o([h(!1)],Ae.prototype,"_getGameByIdBatcher",void 0);o([h(!1)],Ae.prototype,"_getGameByNameBatcher",void 0);o([h(!1)],Ae.prototype,"_getGameByIgdbIdBatcher",void 0);Ae=o([u("api","HelixGameApi")],Ae);var Mt=class extends d{static{s(this,"HelixGoal")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterDisplayName(){return this[i].broadcaster_name}get broadcasterName(){return this[i].broadcaster_login}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get type(){return this[i].type}get description(){return this[i].description}get currentAmount(){return this[i].current_amount}get targetAmount(){return this[i].target_amount}get creationDate(){return this[i].created_at}};o([h(!1)],Mt.prototype,"_client",void 0);Mt=o([u("api","HelixGoal","id")],Mt);var Pr=class extends y{static{s(this,"HelixGoalApi")}async getGoals(e){return(await this._client.callApi({type:"helix",url:"goals",userId:l(e),scopes:["channel:read:goals"],query:w(e)})).data.map(r=>new Mt(r,this._client))}};Pr=o([u("api","HelixGoalApi")],Pr);var Nt=class extends d{static{s(this,"HelixHypeTrainContribution")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get type(){return this[i].type}get total(){return this[i].total}};o([h(!1)],Nt.prototype,"_client",void 0);Nt=o([u("api","HelixHypeTrainContribution","userId")],Nt);var Ft=class extends d{static{s(this,"HelixHypeTrain")}_client;constructor(e,t){super(e),this._client=t}get eventId(){return this[i].id}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_user_id}get broadcasterName(){return this[i].broadcaster_user_login}get broadcasterDisplayName(){return this[i].broadcaster_user_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_user_id))}get level(){return this[i].level}get total(){return this[i].total}get progress(){return this[i].progress}get goal(){return this[i].goal}get topContributions(){return this[i].top_contributions.map(e=>new Nt(e,this._client))}get startDate(){return new Date(this[i].started_at)}get expiryDate(){return new Date(this[i].expires_at)}get type(){return this[i].type}get isSharedTrain(){return this[i].is_shared_train}};o([h(!1)],Ft.prototype,"_client",void 0);Ft=o([u("api","HelixHypeTrain","id")],Ft);var jt=class extends d{static{s(this,"HelixHypeTrainAllTimeHigh")}get level(){return this[i].level}get total(){return this[i].total}get achievementDate(){return new Date(this[i].achieved_at)}};jt=o([u("api","HelixHypeTrainAllTimeHigh")],jt);var Lt=class extends d{static{s(this,"HelixHypeTrainStatus")}_client;constructor(e,t){super(e),this._client=t}get current(){return H(this[i].current,e=>new Ft(e,this._client))}get allTimeHigh(){return H(this[i].all_time_high,e=>new jt(e))}get sharedAllTimeHigh(){return H(this[i].shared_all_time_high,e=>new jt(e))}};o([h(!1)],Lt.prototype,"_client",void 0);Lt=o([u("api","HelixHypeTrainStatus")],Lt);var kr=class extends y{static{s(this,"HelixHypeTrainApi")}async getHypeTrainStatusForBroadcaster(e){let t=await this._client.callApi({type:"helix",url:"hypetrain/status",userId:l(e),scopes:["channel:read:hype_train"],query:{...w(e)}});return new Lt(t.data[0],this._client)}};function Bi(n,e){return{broadcaster_id:l(n),user_id:e?.userId}}s(Bi,"createModerationUserListQuery");function Ui(n,e){return{broadcaster_id:l(n),user_id:l(e)}}s(Ui,"createModeratorModifyQuery");function wn(n,e,t,r,a){return{unban_request_id:t,broadcaster_id:l(n),moderator_id:l(e),status:r?"approved":"denied",resolution_text:a}}s(wn,"createResolveUnbanRequestQuery");function bn(n,e,t){return{user_id:l(n),msg_id:e,action:t?"ALLOW":"DENY"}}s(bn,"createAutoModProcessBody");function Sn(n){return{overall_level:n.overallLevel,aggression:n.aggression,bullying:n.bullying,disability:n.disability,misogyny:n.misogyny,race_ethnicity_or_religion:n.raceEthnicityOrReligion,sex_based_terms:n.sexBasedTerms,sexuality_sex_or_gender:n.sexualitySexOrGender,swearing:n.swearing}}s(Sn,"createAutoModSettingsBody");function Cn(n){return{data:{duration:n.duration,reason:n.reason,user_id:l(n.user)}}}s(Cn,"createBanUserBody");function vn(n){return{is_active:n}}s(vn,"createUpdateShieldModeStatusBody");function In(n){return{data:n.map(e=>({msg_id:e.messageId,msg_text:e.messageText}))}}s(In,"createCheckAutoModStatusBody");function An(n,e){return{data:{user_id:l(n),reason:e}}}s(An,"createWarnUserBody");var Qt=class extends d{static{s(this,"HelixAutoModSettings")}get broadcasterId(){return this[i].broadcaster_id}get moderatorId(){return this[i].moderator_id}get overallLevel(){return this[i].overall_level?this[i].overall_level:null}get disability(){return this[i].disability}get aggression(){return this[i].aggression}get sexualitySexOrGender(){return this[i].sexuality_sex_or_gender}get misogyny(){return this[i].misogyny}get bullying(){return this[i].bullying}get swearing(){return this[i].swearing}get raceEthnicityOrReligion(){return this[i].race_ethnicity_or_religion}get sexBasedTerms(){return this[i].sex_based_terms}};Qt=o([u("api","HelixAutoModSettings","broadcasterId")],Qt);var qr=class extends d{static{s(this,"HelixAutoModStatus")}get messageId(){return this[i].msg_id}get isPermitted(){return this[i].is_permitted}};qr=o([u("api","HelixAutoModStatus","messageId")],qr);var fe=class extends d{static{s(this,"HelixBanUser")}_client;_expiryTimestamp;constructor(e,t,r){super(e),this._expiryTimestamp=t,this._client=r}get creationDate(){return new Date(this[i].created_at)}get expiryDate(){return H(this._expiryTimestamp,e=>new Date(e))}get moderatorId(){return this[i].moderator_id}async getModerator(){return p(await this._client.users.getUserById(this[i].moderator_id))}get userId(){return this[i].user_id}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],fe.prototype,"_client",void 0);o([h(!1)],fe.prototype,"_expiryTimestamp",void 0);fe=o([u("api","HelixBanUser","userId")],fe);var Gt=class extends fe{static{s(this,"HelixBan")}constructor(e,t){super(e,e.expires_at||null,t)}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}get moderatorName(){return this[i].moderator_login}get moderatorDisplayName(){return this[i].moderator_name}get reason(){return this[i].reason||null}};Gt=o([u("api","HelixBan","userId")],Gt);var Wt=class extends d{static{s(this,"HelixBlockedTerm")}get broadcasterId(){return this[i].broadcaster_id}get creationDate(){return new Date(this[i].created_at)}get expirationDate(){return this[i].expires_at?new Date(this[i].expires_at):null}get id(){return this[i].id}get moderatorId(){return this[i].moderator_id}get text(){return this[i].text}get updatedDate(){return new Date(this[i].updated_at)}};Wt=o([u("api","HelixBlockedTerm","id")],Wt);var $e=class extends d{static{s(this,"HelixModeratedChannel")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].broadcaster_id}get name(){return this[i].broadcaster_login}get displayName(){return this[i].broadcaster_name}async getChannel(){return p(await this._client.channels.getChannelInfoById(this[i].broadcaster_id))}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}};o([h(!1)],$e.prototype,"_client",void 0);$e=o([u("api","HelixModeratedChannel","id")],$e);var ze=class extends d{static{s(this,"HelixModerator")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],ze.prototype,"_client",void 0);ze=o([u("api","HelixModerator","userId")],ze);var Ke=class extends d{static{s(this,"HelixShieldModeStatus")}_client;constructor(e,t){super(e),this._client=t}get isActive(){return this[i].is_active}get moderatorId(){return this[i].moderator_id}get moderatorName(){return this[i].moderator_login}get moderatorDisplayName(){return this[i].moderator_name}async getModerator(){return p(await this._client.users.getUserById(this[i].moderator_id))}get lastActivationDate(){return this[i].last_activated_at===""?null:new Date(this[i].last_activated_at)}};o([h(!1)],Ke.prototype,"_client",void 0);Ke=o([u("api","HelixShieldModeStatus")],Ke);var Ee=class extends d{static{s(this,"HelixUnbanRequest")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_id}get broadcasterDisplayName(){return this[i].broadcaster_id}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get moderatorId(){return this[i].moderator_id}get moderatorName(){return this[i].moderator_login}get moderatorDisplayName(){return this[i].moderator_name}async getModerator(){return p(await this._client.users.getUserById(this[i].moderator_id))}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get message(){return this[i].text}get creationDate(){return new Date(this[i].created_at)}get resolutionMessage(){return this[i].resolution_text||null}get resolutionDate(){return H(this[i].resolved_at,e=>new Date(e))}};o([h(!1)],Ee.prototype,"_client",void 0);Ee=o([u("api","HelixUnbanRequest","id")],Ee);var Vt=class extends d{static{s(this,"HelixWarning")}_client;constructor(e,t){super(e),this._client=t}get broadcasterId(){return this[i].user_id}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get moderatorId(){return this[i].moderator_id}async getModerator(){return p(await this._client.users.getUserById(this[i].moderator_id))}get userId(){return this[i].user_id}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get reason(){return this[i].reason}};o([h(!1)],Vt.prototype,"_client",void 0);Vt=o([u("api","HelixWarning","userId")],Vt);var Or=class extends y{static{s(this,"HelixModerationApi")}async getBannedUsers(e,t){let r=await this._client.callApi({type:"helix",url:"moderation/banned",userId:l(e),scopes:["moderation:read"],query:{...Bi(e,t),...x(t)}});return v(r,Gt,this._client)}getBannedUsersPaginated(e){return new S({url:"moderation/banned",userId:l(e),scopes:["moderation:read"],query:w(e)},this._client,t=>new Gt(t,this._client),50)}async checkUserBan(e,t){let r=l(t);return(await this.getBannedUsers(e,{userId:r})).data.some(c=>c.userId===r)}async getModerators(e,t){let r=await this._client.callApi({type:"helix",url:"moderation/moderators",userId:l(e),scopes:["moderation:read","channel:manage:moderators"],query:{...Bi(e,t),...x(t)}});return v(r,ze,this._client)}getModeratorsPaginated(e){return new S({url:"moderation/moderators",userId:l(e),scopes:["moderation:read","channel:manage:moderators"],query:w(e)},this._client,t=>new ze(t,this._client))}async getModeratedChannels(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"moderation/channels",userId:r,scopes:["user:read:moderated_channels"],query:{...I("user_id",r),...x(t)}});return v(a,$e,this._client)}getModeratedChannelsPaginated(e){let t=l(e);return new S({url:"moderation/channels",userId:t,scopes:["user:read:moderated_channels"],query:I("user_id",t)},this._client,r=>new $e(r,this._client))}async checkUserMod(e,t){let r=l(t);return(await this.getModerators(e,{userId:r})).data.some(c=>c.userId===r)}async addModerator(e,t){await this._client.callApi({type:"helix",url:"moderation/moderators",method:"POST",userId:l(e),scopes:["channel:manage:moderators"],query:Ui(e,t)})}async removeModerator(e,t){await this._client.callApi({type:"helix",url:"moderation/moderators",method:"DELETE",userId:l(e),scopes:["channel:manage:moderators"],query:Ui(e,t)})}async checkAutoModStatus(e,t){return(await this._client.callApi({type:"helix",url:"moderation/enforcements/status",method:"POST",userId:l(e),scopes:["moderation:read"],query:w(e),jsonBody:In(t)})).data.map(a=>new qr(a))}async processHeldAutoModMessage(e,t,r){await this._client.callApi({type:"helix",url:"moderation/automod/message",method:"POST",userId:l(e),scopes:["moderator:manage:automod"],jsonBody:bn(e,t,r)})}async getAutoModSettings(e){let t=l(e);return(await this._client.callApi({type:"helix",url:"moderation/automod/settings",userId:t,scopes:["moderator:read:automod_settings"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(t)})).data.map(a=>new Qt(a))}async updateAutoModSettings(e,t){let r=l(e);return(await this._client.callApi({type:"helix",url:"moderation/automod/settings",method:"PUT",userId:r,scopes:["moderator:manage:automod_settings"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(r),jsonBody:Sn(t)})).data.map(c=>new Qt(c))}async banUser(e,t){let r=l(e);return(await this._client.callApi({type:"helix",url:"moderation/bans",method:"POST",userId:r,scopes:["moderator:manage:banned_users"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(r),jsonBody:Cn(t)})).data.map(c=>new fe(c,c.end_time,this._client))}async unbanUser(e,t){let r=l(e);await this._client.callApi({type:"helix",url:"moderation/bans",method:"DELETE",userId:r,scopes:["moderator:manage:banned_users"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(r),...I("user_id",l(t))}})}async getBlockedTerms(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"moderation/blocked_terms",userId:r,scopes:["moderator:read:blocked_terms"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(r),...x(t)}});return v(a,Wt,this._client)}async addBlockedTerm(e,t){let r=l(e);return(await this._client.callApi({type:"helix",url:"moderation/blocked_terms",method:"POST",userId:r,scopes:["moderator:manage:blocked_terms"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(r),jsonBody:{text:t}})).data.map(c=>new Wt(c))}async removeBlockedTerm(e,t,r){let a=l(e);await this._client.callApi({type:"helix",url:"moderation/blocked_terms",method:"DELETE",userId:a,scopes:["moderator:manage:blocked_terms"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(a),id:r}})}async deleteChatMessages(e,t){let r=l(e);await this._client.callApi({type:"helix",url:"moderation/chat",method:"DELETE",userId:r,scopes:["moderator:manage:chat_messages"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(r),...I("message_id",t)}})}async getShieldModeStatus(e){let t=l(e),r=await this._client.callApi({type:"helix",url:"moderation/shield_mode",method:"GET",userId:t,scopes:["moderator:read:shield_mode","moderator:manage:shield_mode"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(t)});return new Ke(r.data[0],this._client)}async updateShieldModeStatus(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"moderation/shield_mode",method:"PUT",userId:r,scopes:["moderator:manage:shield_mode"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(r),jsonBody:vn(t)});return new Ke(a.data[0],this._client)}async getUnbanRequests(e,t,r){let a=l(e),c=await this._client.callApi({type:"helix",url:"moderation/unban_requests",method:"GET",userId:a,scopes:["moderator:read:unban_requests","moderator:manage:unban_requests"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(a),...I("status",t),...x(r)}});return v(c,Ee,this._client)}getUnbanRequestsPaginated(e,t){let r=l(e);return new S({url:"moderation/unban_requests",method:"GET",userId:r,scopes:["moderator:read:unban_requests","moderator:manage:unban_requests"],canOverrideScopedUserContext:!0,query:{...this._createModeratorActionQuery(r),...I("status",t)}},this._client,a=>new Ee(a,this._client))}async resolveUnbanRequest(e,t,r,a){let c=l(e),m=await this._client.callApi({type:"helix",url:"moderation/unban_requests",method:"PATCH",userId:c,scopes:["moderator:manage:unban_requests"],canOverrideScopedUserContext:!0,query:wn(c,this._getUserContextIdWithDefault(c),t,r,a?.slice(0,500))});return new Ee(m.data[0],this._client)}async warnUser(e,t,r){let a=l(e),c=await this._client.callApi({type:"helix",url:"moderation/warnings",method:"POST",userId:a,scopes:["moderator:manage:warnings"],canOverrideScopedUserContext:!0,query:this._createModeratorActionQuery(a),jsonBody:An(t,r.slice(0,500))});return new Vt(c.data[0],this._client)}_createModeratorActionQuery(e){return br(e,this._getUserContextIdWithDefault(e))}};Or=o([u("api","HelixModerationApi")],Or);function En(n,e){return{broadcaster_id:l(n),title:e.title,choices:e.choices.map(t=>({title:t})),duration:e.duration,channel_points_voting_enabled:e.channelPointsPerVote!=null,channel_points_per_vote:e.channelPointsPerVote??0}}s(En,"createPollBody");function Tn(n,e,t){return{broadcaster_id:l(n),id:e,status:t?"TERMINATED":"ARCHIVED"}}s(Tn,"createPollEndBody");var Mr=class extends d{static{s(this,"HelixPollChoice")}get id(){return this[i].id}get title(){return this[i].title}get totalVotes(){return this[i].votes}get channelPointsVotes(){return this[i].channel_points_votes}};Mr=o([u("api","HelixPollChoice","id")],Mr);var ee=class extends d{static{s(this,"HelixPoll")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get title(){return this[i].title}get isChannelPointsVotingEnabled(){return this[i].channel_points_voting_enabled}get channelPointsPerVote(){return this[i].channel_points_per_vote}get status(){return this[i].status}get durationInSeconds(){return this[i].duration}get startDate(){return new Date(this[i].started_at)}get endDate(){return new Date(this.startDate.getTime()+this[i].duration*1e3)}get choices(){return this[i].choices.map(e=>new Mr(e))}};o([h(!1)],ee.prototype,"_client",void 0);ee=o([u("api","HelixPoll","id")],ee);var Nr=class extends y{static{s(this,"HelixPollApi")}async getPolls(e,t){let r=await this._client.callApi({type:"helix",url:"polls",userId:l(e),scopes:["channel:read:polls","channel:manage:polls"],query:{...w(e),...x(t)}});return v(r,ee,this._client)}getPollsPaginated(e){return new S({url:"polls",userId:l(e),scopes:["channel:read:polls","channel:manage:polls"],query:w(e)},this._client,t=>new ee(t,this._client),20)}async getPollsByIds(e,t){return t.length?(await this._client.callApi({type:"helix",url:"polls",userId:l(e),scopes:["channel:read:polls","channel:manage:polls"],query:de(e,t)})).data.map(a=>new ee(a,this._client)):[]}async getPollById(e,t){let r=await this.getPollsByIds(e,[t]);return r.length?r[0]:null}async createPoll(e,t){let r=await this._client.callApi({type:"helix",url:"polls",method:"POST",userId:l(e),scopes:["channel:manage:polls"],jsonBody:En(e,t)});return new ee(r.data[0],this._client)}async endPoll(e,t,r=!0){let a=await this._client.callApi({type:"helix",url:"polls",method:"PATCH",userId:l(e),scopes:["channel:manage:polls"],jsonBody:Tn(e,t,r)});return new ee(a.data[0],this._client)}};Nr=o([u("api","HelixPollApi")],Nr);function Hn(n,e){return{broadcaster_id:l(n),title:e.title,outcomes:e.outcomes.map(t=>({title:t})),prediction_window:e.autoLockAfter}}s(Hn,"createPredictionBody");function Bn(n,e,t,r){return{broadcaster_id:l(n),id:e,status:t,winning_outcome_id:r}}s(Bn,"createEndPredictionBody");var $t=class extends d{static{s(this,"HelixPredictor")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return await this._client.users.getUserById(this[i].user_id)}get channelPointsUsed(){return this[i].channel_points_used}get channelPointsWon(){return this[i].channel_points_won}};o([h(!1)],$t.prototype,"_client",void 0);$t=o([u("api","HelixPredictor","userId")],$t);var Ze=class extends d{static{s(this,"HelixPredictionOutcome")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get title(){return this[i].title}get users(){return this[i].users}get totalChannelPoints(){return this[i].channel_points}get color(){return this[i].color}get topPredictors(){return this[i].top_predictors?.map(e=>new $t(e,this._client))??[]}};o([h(!1)],Ze.prototype,"_client",void 0);Ze=o([u("api","HelixPredictionOutcome","id")],Ze);var te=class extends d{static{s(this,"HelixPrediction")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get title(){return this[i].title}get status(){return this[i].status}get autoLockAfter(){return this[i].prediction_window}get creationDate(){return new Date(this[i].created_at)}get endDate(){return this[i].ended_at?new Date(this[i].ended_at):null}get lockDate(){return this[i].locked_at?new Date(this[i].locked_at):null}get outcomes(){return this[i].outcomes.map(e=>new Ze(e,this._client))}get winningOutcomeId(){return this[i].winning_outcome_id||null}get winningOutcome(){if(!this[i].winning_outcome_id)return null;let e=this[i].outcomes.find(t=>t.id===this[i].winning_outcome_id);if(!e)throw new M("Winning outcome not found in outcomes array");return new Ze(e,this._client)}};o([h(!1)],te.prototype,"_client",void 0);te=o([u("api","HelixPrediction","id")],te);var Fr=class extends y{static{s(this,"HelixPredictionApi")}async getPredictions(e,t){let r=await this._client.callApi({type:"helix",url:"predictions",userId:l(e),scopes:["channel:read:predictions"],query:{...w(e),...x(t)}});return v(r,te,this._client)}getPredictionsPaginated(e){return new S({url:"predictions",userId:l(e),scopes:["channel:read:predictions"],query:w(e)},this._client,t=>new te(t,this._client),20)}async getPredictionsByIds(e,t){return t.length?(await this._client.callApi({type:"helix",url:"predictions",userId:l(e),scopes:["channel:read:predictions"],query:de(e,t)})).data.map(a=>new te(a,this._client)):[]}async getPredictionById(e,t){let r=await this.getPredictionsByIds(e,[t]);return r.length?r[0]:null}async createPrediction(e,t){let r=await this._client.callApi({type:"helix",url:"predictions",method:"POST",userId:l(e),scopes:["channel:manage:predictions"],jsonBody:Hn(e,t)});return new te(r.data[0],this._client)}async lockPrediction(e,t){return await this._endPrediction(e,t,"LOCKED")}async resolvePrediction(e,t,r){return await this._endPrediction(e,t,"RESOLVED",r)}async cancelPrediction(e,t){return await this._endPrediction(e,t,"CANCELED")}async _endPrediction(e,t,r,a){let c=await this._client.callApi({type:"helix",url:"predictions",method:"PATCH",userId:l(e),scopes:["channel:manage:predictions"],jsonBody:Bn(e,t,r,a)});return new te(c.data[0],this._client)}};Fr=o([u("api","HelixPredictionApi")],Fr);function Un(n,e){return{from_broadcaster_id:l(n),to_broadcaster_id:l(e)}}s(Un,"createRaidStartQuery");var jr=class extends d{static{s(this,"HelixRaid")}get creationDate(){return new Date(this[i].created_at)}get targetIsMature(){return this[i].is_mature}};jr=o([u("api","HelixRaid")],jr);var Lr=class extends y{static{s(this,"HelixRaidApi")}async startRaid(e,t){let r=await this._client.callApi({type:"helix",url:"raids",method:"POST",userId:l(e),scopes:["channel:manage:raids"],query:Un(e,t)});return new jr(r.data[0])}async cancelRaid(e){await this._client.callApi({type:"helix",url:"raids",method:"DELETE",userId:l(e),scopes:["channel:manage:raids"],query:w(e)})}};Lr=o([u("api","HelixRaidApi")],Lr);function Qr(n,e){return{broadcaster_id:l(n),start_time:e?.startDate,utc_offset:e?.utcOffset?.toString()}}s(Qr,"createScheduleQuery");function Rn(n,e){return e.vacation?{broadcaster_id:l(n),is_vacation_enabled:"true",vacation_start_time:e.vacation.startDate,vacation_end_time:e.vacation.endDate,timezone:e.vacation.timezone}:{broadcaster_id:l(n),is_vacation_enabled:"false"}}s(Rn,"createScheduleSettingsUpdateQuery");function Dn(n){return{start_time:n.startDate,timezone:n.timezone,is_recurring:n.isRecurring,duration:n.duration,category_id:n.categoryId,title:n.title}}s(Dn,"createScheduleSegmentBody");function Ri(n,e){return{broadcaster_id:l(n),id:e}}s(Ri,"createScheduleSegmentModifyQuery");function Pn(n){return{start_time:n.startDate,timezone:n.timezone,is_canceled:n.isCanceled,duration:n.duration,category_id:n.categoryId,title:n.title}}s(Pn,"createScheduleSegmentUpdateBody");var G=class extends d{static{s(this,"HelixScheduleSegment")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get startDate(){return new Date(this[i].start_time)}get endDate(){return new Date(this[i].end_time)}get title(){return this[i].title}get cancelEndDate(){return H(this[i].canceled_until,e=>new Date(e))}get categoryId(){return this[i].category?.id??null}get categoryName(){return this[i].category?.name??null}async getCategory(){let e=this[i].category?.id;return e?await this._client.games.getGameById(e):null}get isRecurring(){return this[i].is_recurring}};o([h(!1)],G.prototype,"_client",void 0);G=o([u("api","HelixScheduleSegment","id")],G);var Gr=class extends S{static{s(this,"HelixPaginatedScheduleSegmentRequest")}constructor(e,t,r){super({url:"schedule",query:Qr(e,r)},t,a=>new G(a,t),25)}async _fetchData(e={}){let t=await super._fetchData(e);return{data:t.data.segments??[],pagination:t.pagination}}};Gr=o([u("api","HelixPaginatedScheduleSegmentRequest")],Gr);var zt=class extends d{static{s(this,"HelixSchedule")}_client;constructor(e,t){super(e),this._client=t}get segments(){return this[i].segments?.map(e=>new G(e,this._client))??[]}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get vacationStartDate(){let e=this[i].vacation?.start_time;return e?new Date(e):null}get vacationEndDate(){let e=this[i].vacation?.end_time;return e?new Date(e):null}};o([h(!1)],zt.prototype,"_client",void 0);zt=o([u("api","HelixSchedule","broadcasterId")],zt);var Wr=class extends y{static{s(this,"HelixScheduleApi")}async getSchedule(e,t){let r=await this._client.callApi({type:"helix",url:"schedule",userId:l(e),query:{...Qr(e,t),...x(t)}});return{data:new zt(r.data,this._client),cursor:r.pagination.cursor}}getScheduleSegmentsPaginated(e,t){return new Gr(e,this._client,t)}async getScheduleSegmentsByIds(e,t){return(await this._client.callApi({type:"helix",url:"schedule",userId:l(e),query:de(e,t)})).data.segments?.map(a=>new G(a,this._client))??[]}async getScheduleSegmentById(e,t){let r=await this.getScheduleSegmentsByIds(e,[t]);return r.length?r[0]:null}async getScheduleAsIcal(e){return await this._client.callApi({type:"helix",url:"schedule/icalendar",query:w(e)})}async updateScheduleSettings(e,t){await this._client.callApi({type:"helix",url:"schedule/settings",method:"PATCH",userId:l(e),scopes:["channel:manage:schedule"],query:Rn(e,t)})}async createScheduleSegment(e,t){let r=await this._client.callApi({type:"helix",url:"schedule/segment",method:"POST",userId:l(e),scopes:["channel:manage:schedule"],query:w(e),jsonBody:Dn(t)});return new G(r.data.segments[0],this._client)}async updateScheduleSegment(e,t,r){let a=await this._client.callApi({type:"helix",url:"schedule/segment",method:"PATCH",userId:l(e),scopes:["channel:manage:schedule"],query:Ri(e,t),jsonBody:Pn(r)});return new G(a.data.segments[0],this._client)}async deleteScheduleSegment(e,t){await this._client.callApi({type:"helix",url:"schedule/segment",method:"DELETE",userId:l(e),scopes:["channel:manage:schedule"],query:Ri(e,t)})}};function Di(n,e){return{query:n,live_only:e.liveOnly?.toString()}}s(Di,"createSearchChannelsQuery");var Je=class extends d{static{s(this,"HelixChannelSearchResult")}_client;constructor(e,t){super(e),this._client=t}get language(){return this[i].broadcaster_language}get id(){return this[i].id}get name(){return this[i].broadcaster_login}get displayName(){return this[i].display_name}async getUser(){return p(await this._client.users.getUserById(this[i].id))}get gameId(){return this[i].game_id}get gameName(){return this[i].game_name}async getGame(){return this[i].game_id?p(await this._client.games.getGameById(this[i].game_id)):null}get isLive(){return this[i].is_live}get tags(){return this[i].tags}get thumbnailUrl(){return this[i].thumbnail_url}get startDate(){return this[i].is_live?new Date(this[i].started_at):null}};o([h(!1)],Je.prototype,"_client",void 0);Je=o([u("api","HelixChannelSearchResult","id")],Je);var Vr=class extends y{static{s(this,"HelixSearchApi")}async searchCategories(e,t){let r=await this._client.callApi({type:"helix",url:"search/categories",query:{query:e,...x(t)}});return v(r,N,this._client)}searchCategoriesPaginated(e){return new S({url:"search/categories",query:{query:e}},this._client,t=>new N(t,this._client))}async searchChannels(e,t={}){let r=await this._client.callApi({type:"helix",url:"search/channels",query:{...Di(e,t),...x(t)}});return v(r,Je,this._client)}searchChannelsPaginated(e,t={}){return new S({url:"search/channels",query:Di(e,t)},this._client,r=>new Je(r,this._client))}};Vr=o([u("api","HelixSearchApi")],Vr);var $r=class extends P{static{s(this,"StreamNotLiveError")}constructor(e){super("Your stream needs to be live to do this",e)}};function zr(n){return{game_id:n.game,language:n.language,type:n.type,user_id:n.userId,user_login:n.userName}}s(zr,"createStreamQuery");function kn(n,e){return{user_id:l(n),description:e}}s(kn,"createStreamMarkerBody");function Pi(n){return{video_id:n}}s(Pi,"createVideoQuery");var W=class extends d{static{s(this,"HelixStream")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get gameId(){return this[i].game_id}get gameName(){return this[i].game_name}async getGame(){return this[i].game_id?p(await this._client.games.getGameById(this[i].game_id)):null}get type(){return this[i].type}get title(){return this[i].title}get viewers(){return this[i].viewer_count}get startDate(){return new Date(this[i].started_at)}get language(){return this[i].language}get thumbnailUrl(){return this[i].thumbnail_url}getThumbnailUrl(e,t){return this[i].thumbnail_url.replace("{width}",e.toString()).replace("{height}",t.toString())}get tags(){return this[i].tags}get isMature(){return this[i].is_mature}};o([h(!1)],W.prototype,"_client",void 0);W=o([u("api","HelixStream","id")],W);var Te=class extends d{static{s(this,"HelixStreamMarker")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get creationDate(){return new Date(this[i].created_at)}get description(){return this[i].description}get positionInSeconds(){return this[i].position_seconds}};o([h(!1)],Te.prototype,"_client",void 0);Te=o([u("api","HelixStreamMarker","id")],Te);var Kr=class extends Te{static{s(this,"HelixStreamMarkerWithVideo")}_videoId;constructor(e,t,r){super(e,r),this._videoId=t}get url(){return this[i].URL}get videoId(){return this._videoId}async getVideo(){return p(await this._client.videos.getVideoById(this._videoId))}};Kr=o([u("api","HelixStreamMarkerWithVideo","id")],Kr);var Ye,Xe=Ye=class extends y{static{s(this,"HelixStreamApi")}_getStreamByUserIdBatcher=new U({url:"streams"},"user_id","user_id",this._client,e=>new W(e,this._client));_getStreamByUserNameBatcher=new U({url:"streams"},"user_login","user_login",this._client,e=>new W(e,this._client));async getStreams(e={}){let t=await this._client.callApi({url:"streams",type:"helix",query:{...zr(e),...x(e)}});return v(t,W,this._client)}getStreamsPaginated(e={}){return new S({url:"streams",query:zr(e)},this._client,t=>new W(t,this._client))}async getStreamsByUserNames(e){return(await this.getStreams({userName:e.map(le)})).data}async getStreamByUserName(e){return(await this.getStreamsByUserNames([e]))[0]??null}async getStreamByUserNameBatched(e){return await this._getStreamByUserNameBatcher.request(le(e))}async getStreamsByUserIds(e){return(await this.getStreams({userId:e.map(l)})).data}async getStreamByUserId(e){let t=l(e),r=await this._client.callApi({url:"streams",type:"helix",userId:t,query:zr({userId:t})});return H(r.data[0],a=>new W(a,this._client))}async getStreamByUserIdBatched(e){return await this._getStreamByUserIdBatcher.request(l(e))}async getStreamMarkersForUser(e,t){let r=await this._client.callApi({url:"streams/markers",type:"helix",query:{...wi(e),...x(t)},userId:l(e),scopes:["user:read:broadcast"],canOverrideScopedUserContext:!0});return{data:or(r.data.map(a=>Ye._mapGetStreamMarkersResult(a,this._client))),cursor:r.pagination?.cursor}}getStreamMarkersForUserPaginated(e){return new S({url:"streams/markers",query:wi(e),userId:l(e),scopes:["user:read:broadcast"],canOverrideScopedUserContext:!0},this._client,t=>Ye._mapGetStreamMarkersResult(t,this._client))}async getStreamMarkersForVideo(e,t,r){let a=await this._client.callApi({url:"streams/markers",type:"helix",query:{...Pi(t),...x(r)},userId:l(e),scopes:["user:read:broadcast"],canOverrideScopedUserContext:!0});return{data:or(a.data.map(c=>Ye._mapGetStreamMarkersResult(c,this._client))),cursor:a.pagination?.cursor}}getStreamMarkersForVideoPaginated(e,t){return new S({url:"streams/markers",query:Pi(t),userId:l(e),scopes:["user:read:broadcast"],canOverrideScopedUserContext:!0},this._client,r=>Ye._mapGetStreamMarkersResult(r,this._client))}async createStreamMarker(e,t){try{let r=await this._client.callApi({url:"streams/markers",method:"POST",type:"helix",userId:l(e),scopes:["channel:manage:broadcast"],canOverrideScopedUserContext:!0,jsonBody:kn(e,t)});return new Te(r.data[0],this._client)}catch(r){throw r instanceof O&&r.statusCode===404?new $r({cause:r}):r}}async getStreamKey(e){let t=l(e);return(await this._client.callApi({type:"helix",url:"streams/key",userId:t,scopes:["channel:read:stream_key"],query:w(e)})).data[0].stream_key}async getFollowedStreams(e,t){let r=l(e),a=await this._client.callApi({type:"helix",url:"streams/followed",userId:r,scopes:["user:read:follows"],query:{...I("user_id",r),...x(t)}});return v(a,W,this._client)}getFollowedStreamsPaginated(e){let t=l(e);return new S({url:"streams/followed",userId:t,scopes:["user:read:follows"],query:I("user_id",t)},this._client,r=>new W(r,this._client))}static _mapGetStreamMarkersResult(e,t){return e.videos.reduce((r,a)=>[...r,...a.markers.map(c=>new Kr(c,a.video_id,t))],[])}};o([h(!1)],Xe.prototype,"_getStreamByUserIdBatcher",void 0);o([h(!1)],Xe.prototype,"_getStreamByUserNameBatcher",void 0);Xe=Ye=o([u("api","HelixStreamApi")],Xe);function qn(n,e){return{broadcaster_id:l(n),user_id:l(e)}}s(qn,"createSubscriptionCheckQuery");var He=class extends d{static{s(this,"HelixUserSubscription")}_client;constructor(e,t){super(e),this._client=t}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return await this._client.users.getUserById(this[i].broadcaster_id)}get isGift(){return this[i].is_gift}get tier(){return this[i].tier}};o([h(!1)],He.prototype,"_client",void 0);He=o([u("api","HelixUserSubscription","broadcasterId")],He);var Be=class extends He{static{s(this,"HelixSubscription")}get broadcasterId(){return this[i].broadcaster_id}get broadcasterName(){return this[i].broadcaster_login}get broadcasterDisplayName(){return this[i].broadcaster_name}async getBroadcaster(){return p(await this._client.users.getUserById(this[i].broadcaster_id))}get gifterId(){return this[i].is_gift?this[i].gifter_id:null}get gifterName(){return this[i].is_gift?this[i].gifter_login:null}get gifterDisplayName(){return this[i].is_gift?this[i].gifter_name:null}async getGifter(){return this[i].is_gift?p(await this._client.users.getUserById(this[i].gifter_id)):null}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};Be=o([u("api","HelixSubscription","userId")],Be);var Zr=class extends L{static{s(this,"HelixPaginatedSubscriptionsRequest")}constructor(e,t){super({url:"subscriptions",scopes:["channel:read:subscriptions"],userId:l(e),query:w(e)},t,r=>new Be(r,t))}async getPoints(){return(this._currentData??await this._fetchData({query:{after:void 0}})).points}};Zr=o([u("api","HelixPaginatedSubscriptionsRequest")],Zr);var Jr=class extends y{static{s(this,"HelixSubscriptionApi")}async getSubscriptions(e,t){let r=await this._client.callApi({url:"subscriptions",scopes:["channel:read:subscriptions"],type:"helix",userId:l(e),query:{...w(e),...x(t)}});return{...j(r,Be,this._client),points:r.points}}getSubscriptionsPaginated(e){return new Zr(e,this._client)}async getSubscriptionsForUsers(e,t){return(await this._client.callApi({type:"helix",url:"subscriptions",userId:l(e),scopes:["channel:read:subscriptions"],query:Sr(e,t)})).data.map(a=>new Be(a,this._client))}async getSubscriptionForUser(e,t){let r=await this.getSubscriptionsForUsers(e,[t]);return r.length?r[0]:null}async checkUserSubscription(e,t){try{let r=await this._client.callApi({type:"helix",url:"subscriptions/user",userId:l(e),scopes:["user:read:subscriptions"],query:qn(t,e)});return new He(r.data[0],this._client)}catch(r){if(r instanceof O&&r.statusCode===404)return null;throw r}}};Jr=o([u("api","HelixSubscriptionApi")],Jr);var Ue=class extends d{static{s(this,"HelixTeam")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get name(){return this[i].team_name}get displayName(){return this[i].team_display_name}get backgroundImageUrl(){return this[i].background_image_url}get bannerUrl(){return this[i].banner}get creationDate(){return new Date(this[i].created_at)}get updateDate(){return new Date(this[i].updated_at)}get info(){return this[i].info}get logoThumbnailUrl(){return this[i].thumbnail_url}async getUserRelations(){return(await this._client.teams.getTeamById(this.id)).userRelations}};o([h(!1)],Ue.prototype,"_client",void 0);Ue=o([u("api","HelixTeam","id")],Ue);var Kt=class extends Ue{static{s(this,"HelixTeamWithUsers")}get userRelations(){return this[i].users.map(e=>new Y(e,this._client))}};Kt=o([u("api","HelixTeamWithUsers","id")],Kt);var Yr=class extends y{static{s(this,"HelixTeamApi")}async getTeamsForBroadcaster(e){return(await this._client.callApi({type:"helix",url:"teams/channel",userId:l(e),query:w(e)})).data?.map(r=>new Ue(r,this._client))??[]}async getTeamById(e){try{let t=await this._client.callApi({type:"helix",url:"teams",query:{id:e}});return new Kt(t.data[0],this._client)}catch(t){if(t instanceof O&&t.statusCode===500)return null;throw t}}async getTeamByName(e){try{let t=await this._client.callApi({type:"helix",url:"teams",query:{name:e}});return new Kt(t.data[0],this._client)}catch(t){if(t instanceof O&&t.statusCode===404)return null;throw t}}};Yr=o([u("api","HelixTeamApi")],Yr);function On(n,e){return{target_user_id:l(n),source_context:e.sourceContext,reason:e.reason}}s(On,"createUserBlockCreateQuery");function Mn(n){return{target_user_id:l(n)}}s(Mn,"createUserBlockDeleteQuery");var et=class extends d{static{s(this,"HelixBaseExtension")}get id(){return this[i].id}get version(){return this[i].version}get name(){return this[i].name}};var tt=class extends et{static{s(this,"HelixInstalledExtension")}_slotType;_slotId;constructor(e,t,r){super(r),this._slotType=e,this._slotId=t}get slotType(){return this._slotType}get slotId(){return this._slotId}};tt=o([u("api","HelixInstalledExtension","id")],tt);var Zt=class extends d{static{s(this,"HelixInstalledExtensionList")}getExtensionAtSlot(e,t){let r=this[i][e][t];return r.active?new tt(e,t,r):null}getExtensionsForSlotType(e){return[...Object.entries(this[i][e])].filter(t=>t[1].active).map(([t,r])=>new tt(e,t,r))}getAllExtensions(){return[...Object.entries(this[i])].flatMap(([e,t])=>[...Object.entries(t)].filter(r=>r[1].active).map(([r,a])=>new tt(e,r,a)))}};Zt=o([u("api","HelixInstalledExtensionList")],Zt);var Xr=class extends et{static{s(this,"HelixUserExtension")}get canActivate(){return this[i].can_activate}get types(){return this[i].type}};Xr=o([u("api","HelixUserExtension","id")],Xr);var z=class extends d{static{s(this,"HelixUser")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get name(){return this[i].login}get displayName(){return this[i].display_name}get description(){return this[i].description}get type(){return this[i].type}get broadcasterType(){return this[i].broadcaster_type}get profilePictureUrl(){return this[i].profile_image_url}get offlinePlaceholderUrl(){return this[i].offline_image_url}get creationDate(){return new Date(this[i].created_at)}async getStream(){return await this._client.streams.getStreamByUserId(this)}async getFollowedChannels(){return await this._client.channels.getFollowedChannels(this)}async getFollowedChannel(e){return(await this._client.channels.getFollowedChannels(this,e)).data[0]??null}async follows(e){return await this.getFollowedChannel(e)!==null}async getChannelFollowers(){return await this._client.channels.getChannelFollowers(this)}async getChannelFollower(e){return(await this._client.channels.getChannelFollowers(this,e)).data[0]??null}async isFollowedBy(e){return await this.getChannelFollower(e)!==null}async getSubscriptionTo(e){return await this._client.subscriptions.checkUserSubscription(this,e)}async isSubscribedTo(e){return await this.getSubscriptionTo(e)!==null}async getSubscriber(e){return await this._client.subscriptions.getSubscriptionForUser(this,e)}async hasSubscriber(e){return await this.getSubscriber(e)!==null}};o([h(!1)],z.prototype,"_client",void 0);z=o([u("api","HelixUser","id")],z);var Jt=class extends z{static{s(this,"HelixPrivilegedUser")}get email(){return this[i].email}async setDescription(e){return await this._client.users.updateAuthenticatedUser(this,{description:e})}};Jt=o([u("api","HelixPrivilegedUser","id")],Jt);var rt=class extends d{static{s(this,"HelixUserBlock")}_client;constructor(e,t){super(e),this._client=t}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].display_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}};o([h(!1)],rt.prototype,"_client",void 0);rt=o([u("api","HelixUserBlock","userId")],rt);var it=class extends y{static{s(this,"HelixUserApi")}_getUserByIdBatcher=new U({url:"users"},"id","id",this._client,e=>new z(e,this._client));_getUserByNameBatcher=new U({url:"users"},"login","login",this._client,e=>new z(e,this._client));async getUsersByIds(e){return await this._getUsers("id",e.map(l))}async getUsersByNames(e){return await this._getUsers("login",e.map(le))}async getUserById(e){let t=l(e),r=await this._client.callApi({type:"helix",url:"users",userId:t,query:{id:t}});return H(r.data[0],a=>new z(a,this._client))}async getUserByIdBatched(e){return await this._getUserByIdBatcher.request(l(e))}async getUserByName(e){let t=await this._getUsers("login",[le(e)]);return t.length?t[0]:null}async getUserByNameBatched(e){return await this._getUserByNameBatcher.request(le(e))}async getAuthenticatedUser(e,t=!1){let r=await this._client.callApi({type:"helix",url:"users",forceType:"user",userId:l(e),scopes:t?["user:read:email"]:void 0});if(!r.data?.length)throw new M("Could not get authenticated user");return new Jt(r.data[0],this._client)}async updateAuthenticatedUser(e,t){let r=await this._client.callApi({type:"helix",url:"users",method:"PUT",userId:l(e),scopes:["user:edit"],query:{description:t.description}});return new Jt(r.data[0],this._client)}async getBlocks(e,t){let r=await this._client.callApi({type:"helix",url:"users/blocks",userId:l(e),scopes:["user:read:blocked_users"],query:{...w(e),...x(t)}});return v(r,rt,this._client)}getBlocksPaginated(e){return new S({url:"users/blocks",userId:l(e),scopes:["user:read:blocked_users"],query:w(e)},this._client,t=>new rt(t,this._client))}async createBlock(e,t,r={}){await this._client.callApi({type:"helix",url:"users/blocks",method:"PUT",userId:l(e),scopes:["user:manage:blocked_users"],query:On(t,r)})}async deleteBlock(e,t){await this._client.callApi({type:"helix",url:"users/blocks",method:"DELETE",userId:l(e),scopes:["user:manage:blocked_users"],query:Mn(t)})}async getExtensionsForAuthenticatedUser(e,t=!1){return(await this._client.callApi({type:"helix",url:"users/extensions/list",userId:l(e),scopes:t?["channel:manage:extensions"]:["user:read:broadcast","channel:manage:extensions"]})).data.map(a=>new Xr(a))}async getActiveExtensions(e,t=!1){let r=l(e),a=await this._client.callApi({type:"helix",url:"users/extensions",userId:r,scopes:t?["user:read:broadcast","channel:manage:extensions"]:void 0,query:I("user_id",r)});return new Zt(a.data)}async updateActiveExtensionsForAuthenticatedUser(e,t){let r=await this._client.callApi({type:"helix",url:"users/extensions",method:"PUT",userId:l(e),scopes:["channel:manage:extensions"],jsonBody:{data:t}});return new Zt(r.data)}async _getUsers(e,t){if(t.length===0)return[];let r={[e]:t};return(await this._client.callApi({type:"helix",url:"users",query:r})).data.map(c=>new z(c,this._client))}};o([h(!1)],it.prototype,"_getUserByIdBatcher",void 0);o([h(!1)],it.prototype,"_getUserByNameBatcher",void 0);it=o([u("api","HelixUserApi")],it);var ge=class extends d{static{s(this,"HelixVideo")}_client;constructor(e,t){super(e),this._client=t}get id(){return this[i].id}get userId(){return this[i].user_id}get userName(){return this[i].user_login}get userDisplayName(){return this[i].user_name}async getUser(){return p(await this._client.users.getUserById(this[i].user_id))}get title(){return this[i].title}get description(){return this[i].description}get creationDate(){return new Date(this[i].created_at)}get publishDate(){return new Date(this[i].published_at)}get url(){return this[i].url}get thumbnailUrl(){return this[i].thumbnail_url}getThumbnailUrl(e,t){return this[i].thumbnail_url.replace("%{width}",e.toString()).replace("%{height}",t.toString())}get isPublic(){return this[i].viewable==="public"}get views(){return this[i].view_count}get language(){return this[i].language}get type(){return this[i].type}get duration(){return this[i].duration}get durationInSeconds(){let e=this[i].duration.match(/\d+[hms]/g);if(!e)throw new M(`Could not parse duration string: ${this[i].duration}`);return e.map(t=>{let r=/(\d+)([hms])/.exec(t);if(!r)throw new M(`Could not parse partial duration string: ${t}`);let[,a,c]=r;return parseInt(a,10)*{h:3600,m:60,s:1}[c]}).reduce((t,r)=>t+r)}get streamId(){return this[i].stream_id}get mutedSegmentData(){return this[i].muted_segments?.slice()??[]}isMutedAt(e,t,r=!1){if(this[i].muted_segments===null)return!1;if(t==null)return this[i].muted_segments.some(c=>c.offset<=e&&e<=c.offset+c.duration);let a=e+t;return r?this[i].muted_segments.some(c=>{let m=c.offset+c.duration;return e<m&&c.offset<a}):this[i].muted_segments.some(c=>{let m=c.offset+c.duration;return c.offset<=e&&a<=m})}};o([h(!1)],ge.prototype,"_client",void 0);o([A()],ge.prototype,"durationInSeconds",null);ge=o([J,u("api","HelixVideo","id")],ge);var ei,Yt=ei=class extends y{static{s(this,"HelixVideoApi")}_getVideoByIdBatcher=new U({url:"videos"},"id","id",this._client,e=>new ge(e,this._client));async getVideosByIds(e){return(await this._getVideos("id",e)).data}async getVideoById(e){let t=await this.getVideosByIds([e]);return t.length?t[0]:null}async getVideoByIdBatched(e){return await this._getVideoByIdBatcher.request(e)}async getVideosByUser(e,t={}){let r=l(e);return await this._getVideos("user_id",[r],t)}getVideosByUserPaginated(e,t={}){let r=l(e);return this._getVideosPaginated("user_id",[r],t)}async getVideosByGame(e,t={}){return await this._getVideos("game_id",[e],t)}getVideosByGamePaginated(e,t={}){return this._getVideosPaginated("game_id",[e],t)}async deleteVideosByIds(e,t){await this._client.callApi({type:"helix",url:"videos",method:"DELETE",scopes:["channel:manage:videos"],userId:l(e),query:{id:t}})}async _getVideos(e,t,r={}){if(!t.length)return{data:[]};let a=await this._client.callApi({type:"helix",url:"videos",userId:e==="user_id"?t[0]:void 0,query:{...ei._makeVideosQuery(e,t,r),...x(r)}});return v(a,ge,this._client)}_getVideosPaginated(e,t,r={}){return new S({url:"videos",userId:e==="user_id"?t[0]:void 0,query:ei._makeVideosQuery(e,t,r)},this._client,a=>new ge(a,this._client))}static _makeVideosQuery(e,t,r={}){let{language:a,period:c,orderBy:m,type:_}=r;return{[e]:t,language:a,period:c,sort:m,type:_}}};o([h(!1)],Yt.prototype,"_getVideoByIdBatcher",void 0);Yt=ei=o([u("api","HelixVideoApi")],Yt);function Nn(n,e){return{from_user_id:l(n),to_user_id:l(e)}}s(Nn,"createWhisperQuery");var ti=class extends y{static{s(this,"HelixWhisperApi")}async sendWhisper(e,t,r){await this._client.callApi({type:"helix",url:"whispers",method:"POST",userId:l(e),scopes:["user:manage:whispers"],query:Nn(e,t),jsonBody:{message:r}})}};ti=o([u("api","HelixWhisperApi")],ti);var ri=class{static{s(this,"ApiReportedRequest")}_options;_httpStatus;_resolvedUserId;constructor(e,t,r){this._options=e,this._httpStatus=t,this._resolvedUserId=r}get options(){return this._options}get httpStatus(){return this._httpStatus}get resolvedUserId(){return this._resolvedUserId}};var E=class extends wt{static{s(this,"BaseApiClient")}_config;_logger;_rateLimiter;onRequest=this.registerEvent();constructor(e,t,r){super(),this._config=e,this._logger=t,this._rateLimiter=r}async requestScopesForUser(e,t){await this._config.authProvider.getAccessTokenForUser(e,...t.map(r=>[r]))}async getTokenInfo(){try{let e=await this.callApi({type:"auth",url:"validate"});return new St(e)}catch(e){throw e instanceof O&&e.statusCode===401?new bt({cause:e}):e}}async callApi(e){let{authProvider:t}=this._config;if(!(e.auth??!0))return await xt(e,t.clientId,void 0,void 0,this._config.fetchOptions);let a=!1;if(e.forceType)switch(e.forceType){case"app":{if(!t.getAppAccessToken)throw new Error("Tried to make an API call that requires an app access token but your auth provider does not support that");let _=await t.getAppAccessToken();return await this._callApiUsingInitialToken(e,_)}case"user":{a=!0;break}default:throw new M(`Unknown forced token type: ${e.forceType}`)}if(e.scopes&&(a=!0),a){let _=e.canOverrideScopedUserContext?this._getUserIdFromRequestContext(e.userId):e.userId;if(!_)throw new Error("Tried to make an API call with a user context but no context user ID");let f=await t.getAccessTokenForUser(_,e.scopes);if(!f)throw new Error(`Tried to make an API call with a user context for user ID ${_} but no token was found`);if(ke(f)&&t.refreshAccessTokenForUser){let C=await t.refreshAccessTokenForUser(_);return await this._callApiUsingInitialToken(e,C,!0)}return await this._callApiUsingInitialToken(e,f)}let c=this._getUserIdFromRequestContext(e.userId),m=c===null?await t.getAnyAccessToken():await t.getAnyAccessToken(c??e.userId);if(ke(m)&&m.userId&&t.refreshAccessTokenForUser){let _=await t.refreshAccessTokenForUser(m.userId);return await this._callApiUsingInitialToken(e,_,!0)}return await this._callApiUsingInitialToken(e,m)}get bits(){return new xr(this)}get channels(){return new It(this)}get channelPoints(){return new Ir(this)}get charity(){return new Ar(this)}get chat(){return new Hr(this)}get clips(){return new Pt(this)}get contentClassificationLabels(){return new Ur(this)}get entitlements(){return new kt(this)}get eventSub(){return new Rr(this)}get extensions(){return new Dr(this)}get games(){return new Ae(this)}get hypeTrain(){return new kr(this)}get goals(){return new Pr(this)}get moderation(){return new Or(this)}get polls(){return new Nr(this)}get predictions(){return new Fr(this)}get raids(){return new Lr(this)}get schedule(){return new Wr(this)}get search(){return new Vr(this)}get streams(){return new Xe(this)}get subscriptions(){return new Jr(this)}get teams(){return new Yr(this)}get users(){return new it(this)}get videos(){return new Yt(this)}get whispers(){return new ti(this)}get rateLimiterStats(){return this._rateLimiter instanceof K?this._rateLimiter.stats:null}get _authProvider(){return this._config.authProvider}get _batchDelay(){return this._config.batchDelay??0}_getUserIdFromRequestContext(e){return e}async _callApiUsingInitialToken(e,t,r=!1){let{authProvider:a}=this._config,{authorizationType:c}=a,m=await this._callApiInternal(e,a.clientId,t.accessToken,c);if(m.status===401&&!r){if(t.userId){if(a.refreshAccessTokenForUser){let _=await a.refreshAccessTokenForUser(t.userId);m=await this._callApiInternal(e,a.clientId,_.accessToken,c)}}else if(a.getAppAccessToken){let _=await a.getAppAccessToken(!0);m=await this._callApiInternal(e,a.clientId,_.accessToken,c)}}return this.emit(this.onRequest,new ri(e,m.status,t.userId??null)),await Pe(m,e),await yt(m)}async _callApiInternal(e,t,r,a){let{fetchOptions:c}=this._config,m=e.type??"helix";this._logger.debug(`Calling ${m} API: ${e.method??"GET"} ${e.url}`),this._logger.trace(`Query: ${JSON.stringify(e.query)}`),e.jsonBody&&this._logger.trace(`Request body: ${JSON.stringify(e.jsonBody)}`);let _=Fn.operation({retries:3,minTimeout:500,factor:2}),{promise:f,resolve:C,reject:T}=ie();_.attempt(async()=>{try{let q=m==="helix"?await this._rateLimiter.request({options:e,clientId:t,accessToken:r,authorizationType:a,fetchOptions:c}):await ce(e,t,r,a,c);!q.ok&&q.status>=500&&q.status<600&&await Pe(q,e),C(q)}catch(q){if(_.retry(q))return;T(_.mainError())}});let k=await f;return this._logger.debug(`Called ${m} API: ${e.method??"GET"} ${e.url} - result: ${k.status}`),k}};o([A()],E.prototype,"bits",null);o([A()],E.prototype,"channels",null);o([A()],E.prototype,"channelPoints",null);o([A()],E.prototype,"charity",null);o([A()],E.prototype,"chat",null);o([A()],E.prototype,"clips",null);o([A()],E.prototype,"contentClassificationLabels",null);o([A()],E.prototype,"entitlements",null);o([A()],E.prototype,"eventSub",null);o([A()],E.prototype,"extensions",null);o([A()],E.prototype,"games",null);o([A()],E.prototype,"hypeTrain",null);o([A()],E.prototype,"goals",null);o([A()],E.prototype,"moderation",null);o([A()],E.prototype,"polls",null);o([A()],E.prototype,"predictions",null);o([A()],E.prototype,"raids",null);o([A()],E.prototype,"schedule",null);o([A()],E.prototype,"search",null);o([A()],E.prototype,"streams",null);o([A()],E.prototype,"subscriptions",null);o([A()],E.prototype,"teams",null);o([A()],E.prototype,"users",null);o([A()],E.prototype,"videos",null);o([A()],E.prototype,"whispers",null);E=o([J,u("api","ApiClient")],E);var ii=class extends E{static{s(this,"NoContextApiClient")}_getUserIdFromRequestContext(){return null}};ii=o([u("api","ApiClient")],ii);var Xt=class extends E{static{s(this,"UserContextApiClient")}_userId;constructor(e,t,r,a){super(e,t,r),this._userId=a}_getUserIdFromRequestContext(){return this._userId}};Xt=o([u("api","ApiClient")],Xt);var er=class extends E{static{s(this,"ApiClient")}constructor(e){if(!e.authProvider)throw new hr("No auth provider given. Please supply the `authProvider` option.");let t={name:"twurple:api:rate-limiter",...e.logger};super(e,xe({name:"twurple:api:client",...e.logger}),jn.isNode?new pt({getPartitionKey:s(r=>r.userId??null,"getPartitionKey"),createChild:s(()=>new pr({logger:t}),"createChild")}):new _t({logger:t,bucketSize:800,timeFrame:64e3,doRequest:s(async({options:r,clientId:a,accessToken:c,authorizationType:m,fetchOptions:_})=>await ce(r,a,c,m,_),"doRequest"),getPartitionKey:s(r=>r.userId??null,"getPartitionKey")}))}async asUser(e,t){let r=new Xt(this._config,this._logger,this._rateLimiter,l(e));return await t(r)}async asIntent(e,t){if(!this._authProvider.getAccessTokenForIntent)throw new Error("Trying to use intents with an auth provider that does not support them");for(let r of e){let a=await this._authProvider.getAccessTokenForIntent(r);if(a){let c=new Xt(this._config,this._logger,this._rateLimiter,a.userId);return await t(c)}}throw new Error(`Intents [${e.join(", ")}] not found in auth provider`)}async withoutUser(e){let t=new ii(this._config,this._logger,this._rateLimiter);return await e(t)}};er=o([u("api","ApiClient")],er);var ki=class{static{s(this,"EmoteFetcher")}constructor(e={}){if(e.apiClient)this.apiClient=e.apiClient;else if(e.twitchAppID&&e.twitchAppSecret){let t=new ue(e.twitchAppID,e.twitchAppSecret);this.apiClient=new er({authProvider:t})}this.forceStatic=e.forceStatic||!1,this.twitchThemeMode=e.twitchThemeMode||"dark",this.emotes=new ye,this.channels=new ye,this.ffzModifiersFetched=!1}get globalChannel(){return this.channels.get(null)}_setupChannel(e,t){let r=this.channels.get(e);return r||(r=new rr(this,e),this.channels.set(e,r)),t&&(r.format=t.toLowerCase()),r}_getRawTwitchEmotes(e){if(!this.apiClient)throw new Error("Client id or client secret not provided.");return e?this.apiClient.chat.getChannelEmotes(e):this.apiClient.chat.getGlobalEmotes()}_cacheTwitchEmote(e,t,r){let a=this._setupChannel(e),c=r||new lt(a,t.id,t);return this.emotes.set(c.code,c),a.emotes.set(c.code,c),c}_getRawBTTVEmotes(e){let t=e?B.BTTV.Channel(e):B.BTTV.Global;return fetch(t).then(r=>r.json()).then(r=>Array.isArray(r)?r:r?.channelEmotes&&r?.sharedEmotes?[...r.channelEmotes,...r.sharedEmotes]:r||[])}_cacheBTTVEmote(e,t,r){let a=this._setupChannel(e),c=r||new st(a,t.id,t);return this.emotes.set(c.code,c),a.emotes.set(c.code,c),c}_getRawFFZEmoteSet(e){let t=B.FFZ.Set(e);return fetch(t).then(r=>r.json()).then(r=>r.set.emoticons)}_getRawFFZEmotes(e){let t=B.FFZ.Channel(e);return fetch(t).then(r=>r.json()).then(r=>{let a=[];for(let c of Object.keys(r.sets)){let m=r.sets[c];a.push(...m.emoticons)}return a})}_cacheFFZEmote(e,t,r){let a=this._setupChannel(e),c=r||new at(a,t.id,t);return this.emotes.set(c.code,c),a.emotes.set(c.code,c),c}_getRawSevenTVEmotes(e){let t=e?B.SevenTV.Channel(e):B.SevenTV.Global;return fetch(t).then(r=>r.json())}_cacheSevenTVEmote(e,t,r,a){let c=this._setupChannel(e,r),m=a||new ot(c,t.id,t);return this.emotes.set(m.code,m),c.emotes.set(m.code,m),m}fetchTwitchEmotes(e){return this._getRawTwitchEmotes(e).then(t=>{for(let r of t)this._cacheTwitchEmote(e,{code:r.name,id:r.id,formats:r.formats});return this.channels.get(e).emotes.filter(r=>r.type==="twitch")})}fetchBTTVEmotes(e){return this._getRawBTTVEmotes(e).then(t=>{for(let r of t)this._cacheBTTVEmote(e,r);return this.channels.get(e).emotes.filter(r=>r.type==="bttv")})}async fetchFFZEmotes(e){return this.ffzModifiersFetched||(this.ffzModifiersFetched=!0,await this._getRawFFZEmoteSet(B.FFZ.sets.Modifiers).then(t=>{for(let r of t)this._cacheFFZEmote(null,r)})),e?this._getRawFFZEmotes(e).then(t=>{for(let r of t)this._cacheFFZEmote(e,r);return this.channels.get(e).emotes.filter(r=>r.type==="ffz")}):this._getRawFFZEmoteSet(B.FFZ.sets.Global).then(t=>{for(let r of t)this._cacheFFZEmote(e,r);return this.channels.get(e).emotes.filter(r=>r.type==="ffz")})}fetchSevenTVEmotes(e,t){let{format:r="webp"}=t||{};return this._getRawSevenTVEmotes(e).then(a=>{if(Object.hasOwn(a,"emotes"))for(let c of a.emotes)this._cacheSevenTVEmote(e,c,r);else for(let c of a.emote_set.emotes)this._cacheSevenTVEmote(e,c,r);return this.channels.get(e).emotes.filter(c=>c.type==="7tv")})}fromObject(e){let t=[],r={bttv:{class:st,cache:s((a,c,m)=>this._cacheBTTVEmote(c,null,m),"cache")},ffz:{class:at,cache:s((a,c,m)=>this._cacheFFZEmote(c,null,m),"cache")},"7tv":{class:ot,cache:s((a,c,m)=>this._cacheSevenTVEmote(c,null,a.imageType,m),"cache")},twitch:{class:lt,cache:s((a,c,m)=>this._cacheTwitchEmote(c,null,m),"cache")}};for(let a of e){let{type:c}=a;if(!Object.keys(r).includes(c))throw new TypeError(`Unknown type: ${c}`);let m=r[c].class;this._setupChannel(a.channel_id,c==="7tv"?a.imageType:null);let _=m.fromObject(a,this.channels.get(a.channel_id));r[c].cache(a,a.channel_id,_),t.push(_)}return t}},Ln=ki;var qi=class{static{s(this,"EmoteParser")}constructor(e,t={}){this.fetcher=e,this.options={template:"",type:"html",match:/(\w+)/g,...t},this._validateOptions(this.options)}_validateOptions(e){if(e.template&&typeof e.template!="string")throw new TypeError("Template must be a string");if(!["html","markdown","bbcode","plain"].includes(e.type))throw new TypeError("Parse type must be one of `html`, `markdown`, `bbcode`, or `plain`");if(!(e.match instanceof RegExp)||!e.match.global)throw new TypeError("Match must be a global RegExp.")}parse(e,t){let{size:r,forceStatic:a,themeMode:c}=t||{};return e.replace(this.options.match,(_,f)=>{let C=this.fetcher.emotes.get(f);if(!C)return _;if(C.modifier)return"";let T=this.options.template||B.Templates[this.options.type],k=C.toLink({size:r,forceStatic:a,themeMode:c});return T.replaceAll("{link}",k).replaceAll("{name}",C.code).replaceAll("{size}",r).replaceAll("{creator}",C.ownerName||"global")})}},Qn=qi;var nT={BTTVEmote:st,Channel:rr,Collection:ye,Constants:B,Emote:V,EmoteFetcher:Ln,EmoteParser:Qn,FFZEmote:at,SevenTVEmote:ot,TwitchEmote:lt};export{st as BTTVEmote,rr as Channel,ye as Collection,B as Constants,V as Emote,Ln as EmoteFetcher,Qn as EmoteParser,at as FFZEmote,ot as SevenTVEmote,lt as TwitchEmote,nT as default};
7
+ //# sourceMappingURL=TwitchEmoticons.esm.min.js.map