@streamlayer/sdk-web 1.9.1 → 1.10.1
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.
- package/lib/cjs/index.js +8 -8
- package/lib/es/index.js +890 -850
- package/lib/index.d.ts +1 -0
- package/package.json +13 -13
package/lib/cjs/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const si=require("pino"),S=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),ot=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),V=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),st=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),ne=require("nanostores"),Zt=require("nanoid"),B=require("@connectrpc/connect"),Nn=require("@connectrpc/connect-web"),Fn=require("@nanostores/query"),fr=require("@streamlayer/sl-eslib/sports/events/events_connect"),Ze=require("@streamlayer/sl-eslib/sdkSettings/client/client_connect"),gn=require("@streamlayer/sl-eslib/users/users_connect"),W=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_connect"),pr=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_connect");require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb");const ai=require("@streamlayer/sl-eslib/shortLinks/linksClient_connect"),v=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),hr=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_connect"),Dn=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),ee=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function ui(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var yr={exports:{}},U=yr.exports={},se,ae;function en(){throw new Error("setTimeout has not been defined")}function tn(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?se=setTimeout:se=en}catch{se=en}try{typeof clearTimeout=="function"?ae=clearTimeout:ae=tn}catch{ae=tn}})();function gr(t){if(se===setTimeout)return setTimeout(t,0);if((se===en||!se)&&setTimeout)return se=setTimeout,setTimeout(t,0);try{return se(t,0)}catch{try{return se.call(null,t,0)}catch{return se.call(this,t,0)}}}function ci(t){if(ae===clearTimeout)return clearTimeout(t);if((ae===tn||!ae)&&clearTimeout)return ae=clearTimeout,clearTimeout(t);try{return ae(t)}catch{try{return ae.call(null,t)}catch{return ae.call(this,t)}}}var ge=[],Be=!1,Ee,dt=-1;function di(){!Be||!Ee||(Be=!1,Ee.length?ge=Ee.concat(ge):dt=-1,ge.length&&mr())}function mr(){if(!Be){var t=gr(di);Be=!0;for(var e=ge.length;e;){for(Ee=ge,ge=[];++dt<e;)Ee&&Ee[dt].run();dt=-1,e=ge.length}Ee=null,Be=!1,ci(t)}}U.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];ge.push(new br(t,e)),ge.length===1&&!Be&&gr(mr)};function br(t,e){this.fun=t,this.array=e}br.prototype.run=function(){this.fun.apply(null,this.array)};U.title="browser";U.browser=!0;U.env={};U.argv=[];U.version="";U.versions={};function be(){}U.on=be;U.addListener=be;U.once=be;U.off=be;U.removeListener=be;U.removeAllListeners=be;U.emit=be;U.prependListener=be;U.prependOnceListener=be;U.listeners=function(t){return[]};U.binding=function(t){throw new Error("process.binding is not supported")};U.cwd=function(){return"/"};U.chdir=function(t){throw new Error("process.chdir is not supported")};U.umask=function(){return 0};var li=yr.exports;const I=ui(li),fi=si.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),ce=(t,e)=>fi.child({name:t},e);class pi extends Event{slEventBus;constructor(e,n){super(e),this.slEventBus=n}}const hi=ce("event-bus");class yi{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,n)=>{const r=new pi(this.name,{...n,type:e});hi.debug(r,"Emitting event"),window.dispatchEvent(r)};listen(e){return window.addEventListener(this.name,e),this.listeners.add(e),()=>{this.off(e)}}off(e){window.removeEventListener(this.name,e),this.listeners.delete(e)}destroy=()=>{this.listeners.forEach(e=>{window.removeEventListener(this.name,e),this.listeners.delete(e)}),this.listeners.clear()}}class gi{}var me;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(me||(me={}));window.slStore=Object.create(null);class Ot{store;name;constructor(e,n){this.store=e,this.name=n}getStore(){return this.store}}const mi=t=>{const e=Object.keys(t);return ne.computed(e.map(n=>t[n].getStore()),(...n)=>Object.fromEntries(e.map((r,i)=>[r,n[i]])))};class Ae extends Ot{getValues=()=>this.getStore().get();getValue=e=>this.getStore().get()[e];setValue=(e,n)=>this.getStore().setKey(e,n);subscribe=(...e)=>this.getStore().subscribe(...e);unsubscribe=()=>this.getStore().off()}const H=t=>ne.map(t);var pe;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(pe||(pe={}));const bi={[V.SdkOverlayType.BETTING]:"betting",[V.SdkOverlayType.GAMES]:"games",[V.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[V.SdkOverlayType.TWITTER]:"twitter"};var He;(function(t){t.Ready="ready",t.Suspended="suspended"})(He||(He={}));class vr{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...n},r){this.settingsKey=bi[n.type],this.status=ne.atom(He.Suspended),this.config=new Ae(H(n),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ae(H(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ae(H({}),`feature:settings:${this.settingsKey}`),this.source=r}get featureConfig(){return this.config.getStore()}get featureSettings(){return this.settings.getStore()}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(He.Ready)};disable=()=>{this.status.set(He.Suspended)};setFeatureConfig=({settings:e,...n})=>{let r;for(r in n)this.config.setValue(r,n[r]);if(e?.overlaySettings?.case!==void 0&&e?.overlaySettings.case===this.settingsKey){const i=e.overlaySettings.value;if(i!==void 0){let o;for(o in i)i[o]!==0&&i[o]!==""&&this.settings.setValue(o,i[o])}}};update=(e,n)=>{this.source===pe.STREAM&&n===pe.ORGANIZATION||(this.setFeatureConfig(e),this.source=n)};fireEvent(e){for(const n of this.listeners.values())try{n.onEvent(e)}catch(r){console.error(r)}}}class J extends Ot{getValue=()=>this.getStore().get();getValues(){throw new Error("not implemented")}setValue=e=>this.getStore().set(e);subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>this.getStore().off();listen(e){return this.getStore().listen(e)}get(){return this.getStore().get()}}const j=t=>ne.atom(t);class te extends Ot{atomStore;constructor(e,n,r){super(e,`api:${n}`),this.atomStore=ne.atom(),r&&e.subscribe(i=>{const o=this.atomStore.get(),s=r(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;getValue=async()=>{const e=this.getStore();if(e.value===void 0)throw new Error("no store");return await e.value.promise,e.get().data};getValues=()=>this.getStore().get();setValue=e=>this.getStore().set({loading:!1,data:e?.data});subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>{throw new Error("not implemented")};invalidate=()=>{this.store.invalidate()};listen=e=>this.getStore().listen(e);get(){throw new Error("not implemented")}key=()=>this.getStore().key;off=()=>this.getStore().off()}const M=new yi;async function*vi(t,e){for await(const n of e){t.response.message=n,t.received_at=Date.now(),t.id=Date.now();const r={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(r),yield n}}const Si=()=>t=>async e=>{const n={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:n});try{const r=await t(e);if(n.received_at=Date.now(),n.response.header=Object.fromEntries(r.header.entries()),n.response.trailer=Object.fromEntries(r.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...n,stream:!0}};return window.postMessage(i),{...r,message:vi(n,r.message)}}else{n.response.message=r.message,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};window.postMessage(i)}return r}catch(r){n.received_at=Date.now(),n.response.trailer={"grpc-status":r.code,"grpc-message":r.rawMessage},n.response.message=r.rawMessage,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};throw window.postMessage(i),r}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Sr(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class xe{delimiter=":";prefix;storage;constructor(e="main",n=window.localStorage){this.prefix=`sl-sdk${this.delimiter}${e}`,this.storage=n}clear=()=>{for(const e in window.localStorage)e.startsWith(this.prefix)&&this.storage.removeItem(e)};generateKey=e=>`${this.prefix}${this.delimiter}${e.join(this.delimiter)}`;write=(...e)=>{const n=e.pop()||"",r=this.generateKey(e);try{this.storage.setItem(r,n)}catch(i){Sr(i)&&this.storage===window.sessionStorage&&(window.sessionStorage.removeItem("slstreamlogs"),this.storage.setItem(r,n))}};read=(...e)=>{const n=this.storage.getItem(this.generateKey(e));return n===null?void 0:n};remove=(...e)=>{this.storage.removeItem(this.generateKey(e))}}var Z;(function(t){t.Init="init",t.Ready="ready",t.Connecting="connecting",t.Connected="connected",t.Disconnected="disconnected",t.Failed="failed",t.Reconnect="reconnect",t.Reconnecting="reconnecting"})(Z||(Z={}));const Rn=ce("grpc:stream");class wi{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,n,r,i){const o={status:Z.Init,ts:new Date,log:[]};this.state=new Ae(H(o),`subscription:${i.name}:state`),this.options={...i,reconnectDelay:i.reconnectDelay??1e3,reconnectMaxDelay:i.reconnectMaxDelay??3e4,reconnectMaxAttempts:i.reconnectMaxAttempts??10,withStore:i.withStore??!1},this.headers=e,this.listeners=new Map,this.params=r,this.method=n,i.withStore&&(this.store=new J(j(null),`subscription:${i.name}:store`)),"subscribe"in r&&typeof r.subscribe=="function"&&(this.paramsListener=r.subscribe(s=>{this.state.getValue("status")===Z.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(Z.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const n=this.state.getStore().get().log,r=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(n.push(r),this.state.setValue("log",n),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?Rn.trace({name:this.options.name,attempt:this.attempt},"received data"):Rn.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
-
`+r)}catch(i){Sr(i)&&window.sessionStorage.removeItem("slstreamlogs"),window.sessionStorage.setItem("slstreamlogs",r)}}};addListener=(e,n)=>this.listeners.has(e)?(this.addStateLog(`listener '${e}' not added, already exists`),()=>{}):(this.listeners.set(e,n),this.addStateLog(`listener '${e}' added`),()=>this.removeListener(e));removeListener=e=>{this.listeners.delete(e),this.addStateLog(`listener '${e}' removed`)};connect=()=>{this.updateState(Z.Connecting),this.streamCancel&&(this.addStateLog("disconnect prev connection"),this.streamCancel.abort(),this.streamCancel=void 0);const e="get"in this.params&&typeof this.params.get=="function"?this.params.get():this.params;(async()=>{this.streamCancel=new AbortController;try{const r={headers:this.headers.getValues(),signal:this.streamCancel.signal},i=this.method(e,r);for await(const o of i)this.attempt=0,this.onData(o)}catch(r){r instanceof B.ConnectError&&r.code!=B.Code.Canceled&&this.onStreamError(r)}})(),this.updateState(Z.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(Z.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(Z.Reconnect);const e=Math.min(this.options.reconnectMaxDelay,Math.pow(2,this.attempt)*this.options.reconnectDelay),n=Math.round(e*(1+Math.random())/2);this.reconnectTimeout=setTimeout(()=>{this.attempt++,this.updateState(Z.Reconnecting),this.addStateLog(`reconnect attempt ${this.attempt} after ${n}ms`),this.connect(),this.reconnectTimeout=void 0},n)}else this.addStateLog("max reconnect attempts reached"),this.disconnect()};getStore=()=>this.store?.getStore();onData=e=>{try{this.addStateLog(`received data => ${JSON.stringify(e)}`),this.store&&this.store.setValue(e);for(const[,n]of this.listeners)n(e);this.addStateLog(`data routed to ${this.listeners.size} listeners`)}catch(n){this.addStateLog(`error process data => ${n}`)}};onStreamError=e=>{if(this.addStateLog(`error => ${e?JSON.stringify(e):"undefined"}}`),e!==void 0){if(e instanceof B.ConnectError&&e.code!==B.Code.Canceled){this.updateState(Z.Failed),this.state.setValue("error",e),e.code===B.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const Ti=new Set([B.Code.Unknown,B.Code.Internal,B.Code.DeadlineExceeded,B.Code.ResourceExhausted,B.Code.FailedPrecondition,B.Code.Unavailable,B.Code.DataLoss]),Vn=ce("grpc:retry"),Ei=t=>async e=>{const n=e.contextValues.get(nn.retryAttempts),r=300,i=e.contextValues.get(nn.retryDelay);if(e.stream||n===0)return t(e);Vn.trace({url:e.url,attempts:n,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Vn.trace({attempt:o,error:s},"retry attempt");const a=B.ConnectError.from(s);if(o>=n||!(a instanceof B.ConnectError)||!Ti.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*r),l=Math.round(u*(1+Math.random())/2);await new Promise(c=>setTimeout(c,l))}},nn={retryAttempts:B.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:B.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},Ai=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Zt.nanoid();return localStorage.setItem("sl-device-id",e),e},Ii=()=>navigator.userAgentData?.platform||navigator.platform;class $n{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,n){this.host=e,this.opts=n,this.$headers=new Ae(H({"sl-device-id":Ai(),"sl-device-os":Ii()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[r,i,o]=Fn.nanoquery({dedupeTime:n?.dedupeTime,refetchInterval:n?.refetchInterval});this.nanoquery={createFetcherStore:r,createMutatorStore:i,utils:o},this.transport=Nn.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Nn.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,n,r)=>{const i=this.subscriptions.get(n);if(i)return i;const o=new wi(this.$headers,e,n,r);return this.subscriptions.set(n,o),o};removeSubscription=e=>{e.disconnect(),this.subscriptions.delete(e.params)};disconnect=()=>{for(const[i,o]of this.subscriptions)o.disconnect(),this.subscriptions.delete(i);this.clients.clear(),this.streamClients.clear(),this.subscriptions.clear();const[e,n,r]=Fn.nanoquery({dedupeTime:this.opts?.dedupeTime,refetchInterval:this.opts?.refetchInterval});this.nanoquery={createFetcherStore:e,createMutatorStore:n,utils:r}};registerInterceptor=e=>{this.interceptors.push(e)};removeInterceptor=e=>{this.interceptors=this.interceptors.filter(n=>n!==e)};getClient=e=>{const n=e.typeName;if(this.clients.has(n))return this.clients.get(n);const r=B.createClient(e,this.transport);return this.clients.set(n,r),r};getStreamClient=e=>{const n=`stream-${e.typeName}`;if(this.clients.has(n))return this.clients.get(n);const r=B.createClient(e,this.streamTransport);return this.clients.set(n,r),r};createPromiseClient=(e,{params:n=[],method:r})=>{const i=this.getClient(e),o=e.methods[r].name,s=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1),...Array.isArray(n)?n:[n]],a=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1)];return{client:i,createRequestOptions:l=>{const c=B.createContextValues();for(const f in l){const p=nn[f];c.set(p,l[f])}return c},queryKey:s,queryKeyStr:a.join("")}};createStreamClient=e=>({client:this.getStreamClient(e)});setSdkKey=e=>{this.$headers.setValue("sdk",e)};setAuth=(e,n)=>{this.$headers.setValue("authorization",e),this.$headers.setValue("sl-user-id",n)};setHeader=(e,n)=>this.$headers.setValue(e,n);getHeader=e=>this.$headers.getValue(e);getHeaders=()=>this.$headers.getValues();initInterceptors=()=>{if(this.interceptors.length!==0)return;const e=n=>r=>{const i=this.$headers.getValues();for(const o in i)r.header.set(o,i[o]);return n(r)};this.interceptors.push(e),this.interceptors.push(Si()),this.opts?.retryable&&this.interceptors.push(Ei)}}const Oi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(fr.Events,{method:"retrieveEventId",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s||typeof s!="string")return"";try{return(await n.retrieveEventId({id:s})).data?.id||""}catch{return""}}})},_i=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getStream",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.getStream({id:s})).data?.attributes:void 0})},ki=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(fr.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.summary({id:s})).data?.attributes:void 0})},Ci=(t,e)=>{const{queryKey:n,client:r}=e.createPromiseClient(gn.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>{const{data:i}=await r.me({});return{data:i}}})},Pi=t=>{const{client:e,createRequestOptions:n}=t.createPromiseClient(gn.Users,{method:"bypassAuth"}),r=n({retryAttempts:0});return({userKey:i,schema:o,init:s,inviterKey:a})=>e.bypassAuth({userKey:i,schema:o,init:s,inviterKey:a},{contextValues:r})},Li=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.get({})).data?.attributes})},Ni=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganization",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{const i=await n.getOrganization({});return i.data?{...i.data.attributes,id:i.data.id}:void 0}})},Fi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ze.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.getOrganizationAdvertising({})).data?.attributes})},Di=(t,e,n)=>{t.transport=new $n(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new $n(e.analyticsHost),t.sdk.host=t.transport.host,t.transport.setSdkKey(e.sdkKey),t.transport.setHeader("sl-sdk-version",e.version||"-"),t.transport.$headers.subscribe(r=>{t.analyticsTransport.$headers.getStore().set(r)}),t.sdk.onMount({name:"transport"},()=>()=>{t.transport.disconnect(),t.analyticsTransport.disconnect()}),n()};var fe;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(fe||(fe={}));class $e extends xe{constructor(){super("user")}setSchema=e=>{this.write(fe.SCHEMA,e)};getSchema=()=>this.read(fe.SCHEMA);setToken=e=>{this.write(fe.TOKEN,e)};getToken=()=>this.read(fe.TOKEN);setExternalToken=e=>{this.write(fe.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(fe.EXTERNAL_TOKEN);removeToken=()=>{this.remove(fe.TOKEN)}}var he;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(he||(he={}));const Ri=t=>{const e=new $e,n=new J(j(e.getExternalToken()),"userKey"),r=new J(j(e.getToken()),"userToken"),i=new te(Ci(r.getStore(),t),"user",({data:s,error:a,loading:u},l)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:l}),o=new te(Li(r.getStore(),t),"userSettings");return{userKey:n,userToken:r,user:i,userSettings:o}},Vi=t=>{const e=new J(j(void 0),"providerStreamId"),n=new te(Oi(e.getStore(),t),"slStreamId",o=>o?.data),r=new te(_i(n.getAtomStore(),t),"streamSettings"),i=new te(ki(n.getAtomStore(),t),"streamSettings");return n.getAtomStore().listen(o=>{(o===""||o===void 0)&&(r.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:n,streamSettings:r,streamSummary:i}},$i=t=>{const e=new J(j(void 0),"enabled"),n=new J(j(he.DISABLED),"status"),r=new te(Ni(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new te(Fi(r.getAtomStore(),t),"organizationAdvertising"),o=Ri(t),s=Vi(t);return{enabled:e,status:n,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:r,organizationAdvertising:i}};class qi extends Ot{stores;constructor(e){const n=$i(e),r=mi(n);super(r,"core"),this.stores=n}getValue(){throw new Error("Not implemented")}getValues(){return this.stores}setValue(){throw new Error("Not implemented")}subscribe=e=>{let n;for(n in this.stores){const r=e[n];n in e&&r!==void 0&&this.stores[n].subscribe(e[n])}};unsubscribe=()=>this.getStore().off()}const Bi=(t,e,n)=>{t.store=new qi(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},n()},Mi=t=>{const{client:e}=t.createPromiseClient(pr.Leaderboard,{method:"list"});return n=>e.list(n)},wr=t=>{const{client:e}=t.createPromiseClient(pr.Leaderboard,{method:"summary"});return n=>e.summary(n)},Ui=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(gn.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return[];try{return(await n.getFriends({})).data}catch{return[]}}})},ji=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.get({eventId:s})).data?.attributes,refetchInterval:0,dedupeTime:1e3*60*60})},Qi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"syncQuestion",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return;const a=await n.syncQuestion({filter:{eventId:s}});if(a.data?.attributes?.question?.type!==S.QuestionType.PROMOTION)return a.data?.attributes},dedupeTime:1e3*60*10,refetchInterval:0})},xi=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"item",params:[t]});return(await n.item({id:t})).data},Gi=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed),r=ne.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{r.set({eventId:o,feedId:""})}),e.addSubscription(n.subscription,r,{name:"feedSubscription"})},Ki=(t,e)=>{const{client:n}=e.createStreamClient(W.Feed);return e.addSubscription(n.questionSubscription,{questionId:t},{name:"questionSubscription"})},rn=async(t,e)=>{const{client:n}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return(await n.questionByUser({questionId:t})).data?.attributes?.question},Je=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.questionByUser({questionId:s})).data?.attributes?.question,dedupeTime:1e3*60*5})},Tr=async(t,e)=>{if(!t)return;const{client:n}=e.createPromiseClient(W.Feed,{method:"getQuestion",params:[t]}),r=await n.getQuestion({id:t});if(!r.data?.attributes)return;const{options:i,notification:o,...s}=r.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},zi=(t,e,n)=>{const{client:r,queryKey:i}=n.createPromiseClient(W.Feed,{method:"list",params:[t,e]});return n.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>a?(await r.list({eventId:a,filter:{types:u===Ie.ALLOWED?[]:[S.QuestionType.FACTOID,S.QuestionType.PROMOTION,S.QuestionType.TWEET],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED]}})).data:[],dedupeTime:0,refetchInterval:0})},Hi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(W.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await n.list({eventId:s,filter:{types:[S.QuestionType.PROMOTION],statuses:[S.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return Tr(u.id,e)},dedupeTime:0,refetchInterval:0})},Wi=(t,e,n,r,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(W.Feed,{method:"betPack",params:[t,e,n]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,l,c,f)=>{if(!l||!c||!f)return null;const p=await o.betPack({eventId:l,types:[S.QuestionType.PREDICTION],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?null:p.data?.reduce((w,E)=>{const g=E?.attributes?.question;if(!g?.id)return w;const m={eventId:l,userId:c,organizationId:f};return r.isBetPackQuestionReceived(m,g.id)||(M.emit("poll",{action:"received",payload:{questionId:g.id,questionType:g.type}}),r.saveBetPackQuestionReceived(m,g.id)),{...w,[g.id]:g}},{})},dedupeTime:0,refetchInterval:0})},Yi=(t,e,n)=>{const r=ne.batched([e,n],()=>{const a=e.get();if(!a)return;const u=n.get().data?.find(c=>c.id===a?.questionId),l=a?.question?.openedFrom;return u?(u.openedFrom=l,u):a.question}),i=ne.batched(r,a=>a&&a.type==="question"?a.id:void 0),o=Je(i,t);return{$store:r,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,l=(c,f)=>{if(!c||!f)return c||f||[];const p=[];for(let w=0;w<c.length;w++)p.push({...c[w],...f[w],correct:c[w].correct,youVoted:c[w].youVoted,pointsEarned:c[w].pointsEarned});return p};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:l(u?.answers,a?.answers)})}}};var mt;(function(t){t.SHOWED="showed"})(mt||(mt={}));class Ji extends xe{constructor(){super("advertisement")}setShowed=e=>{this.write(mt.SHOWED,e,"true")};isViewed=e=>this.read(mt.SHOWED,e)}const Xi=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:r,notification:i,...o}=e,s=r?.options.case==="promotion"?r.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},at=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,Zi=({gamOptions:t,gamBaseUrl:e})=>{const n=`${e}?`,r=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")r.push(`${o}=${at(s)}`);else if(Array.isArray(s))r.push(`${o}=${s.map(at).join(",")}`);else{const a=Object.entries(s).map(([u,l])=>Array.isArray(l)?`${u}=${l.map(at).join(",")}`:typeof l=="string"?`${u}=${at(l)}`:`${u}=${l}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");r.push(`${o}=${a}`)}}return n+r.join("&")},Fe=t=>(t?.promotion?.type===S.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===S.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,eo=(t,e,n)=>{let r=!1;const i=n.transport,o=ce("advertisement"),s=new Ji,a=H({}),u=Hi(t,i),l=g=>{const m=a.get(),T=m.data?.question.id,D=m.data?.promotion?.type;T&&(M.emit("advertisement",{action:"opened",payload:{id:T,type:D,hasBanner:Fe(m.data),openedFrom:g?.fromNotification?"notification":"auto"}}),g?.fromNotification&&(a.setKey("hasNotification",!1),M.emit("advertisement",{action:"notification-opened",payload:{id:T,type:D,hasBanner:Fe(m.data)}})))},c=()=>{const g=a.get(),m=g.data?.question.id,T=g.data?.promotion?.type,D=a.get()?.isOpened;m&&!D&&(o.debug({id:m},"markAsViewed: %o"),s.setShowed(m),a.setKey("isOpened",!0),M.emit("advertisement",{action:"viewed",payload:{id:m,type:T,hasBanner:Fe(g.data)}}))},f=(g,m)=>{m?a.set({loading:!1,error:void 0,data:m,hasNotification:m?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(m.question.id),togglePause:T=>w(m.question.id,T),isViewed:!!s.isViewed(m.question.id)}):(a.setKey("loading",!0),Tr(g,i).then(T=>a.set({loading:!1,error:void 0,data:T,hasNotification:T?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(T?.question.id),togglePause:D=>w(T?.question.id,D),isViewed:T&&!!s.isViewed(T.question.id)})).catch(T=>a.set({loading:!1,error:T,data:void 0})))};a.subscribe((g,m)=>{if(!(g.data?.id===m?.data?.id&&g.isPaused!==m?.isPaused)){if(g.data?.promotion?.type===S.PromotionType.EXTERNAL_AD&&!g?.externalAd&&g.data.promotion.adCampaigns?.gamOptions&&g.data.promotion.adCampaigns?.gamBaseUrl){const T=Zi(g.data.promotion.adCampaigns);a.setKey("externalAd",{type:"gam",url:T})}g.data?.promotion&&!g.isOpened&&(M.emit("advertisement",{action:"received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!!g.hasNotification,hasBanner:Fe(g.data),isViewed:!!s.isViewed(g.data.question.id)},skipAnalytics:g.data.question.id===m?.data?.question.id}),g.data.question.id!==m?.data?.question.id&&!s.isViewed(g.data.question.id)&&M.emit("advertisement",{action:"notification-received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!0,hasBanner:Fe(g.data),isViewed:!1}})),!g?.data&&m?.data&&M.emit("advertisement",{action:"closed",payload:{id:m.data.question.id,type:m.data.promotion?.type,hasNotification:!!m.hasNotification,hasBanner:Fe(m.data),isViewed:!!s.isViewed(m.data.question.id)}})}});const p=g=>{(!g||a.get()?.data?.question.id===g)&&a.set({})},w=(g,m)=>{a.get()?.data?.question.id===g&&a.setKey("isPaused",m)};return{connect:()=>{r||(r=!0,u.subscribe((g,m)=>{g.data&&(!m?.data||g.data.id!==m.data.id)&&f(g.data.question.id,g.data)}),e.addListener("promotion",g=>{const m=Xi(g);if(m){if(m.question.status===S.QuestionStatus.RESOLVED){p(m.question.id),o.debug({promotion:m},"resolved: %o");return}if(m.question.status===S.QuestionStatus.ACTIVE){o.debug({promotion:m},"active: %o"),f(m.question.id,m);return}o.debug({promotion:m},"skip: %o")}}))},hide:p,show:f,open:l,markAsViewed:c,$store:a}};var oe;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.BET_PACK_ITEM_RECEIVED="bp-item-received",t.QUESTION_OPENED="q-opened"})(oe||(oe={}));class to extends xe{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,n)=>{this.write(...e,n)};readValue=e=>this.read(...e)}class no extends xe{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new to}saveBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i)};isBetPackQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.BET_PACK_ITEM_RECEIVED,r,e,n,i);saveQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.QUESTION_OPENED,r,e,n,i)};isQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(oe.QUESTION_OPENED,r,e,n,i);saveOnboardingStatus=({userId:e,eventId:n,organizationId:r},i)=>{this.write(oe.ONBOARDING,r,e,n,i)};getOnboardingStatus=({userId:e,eventId:n,organizationId:r})=>this.read(oe.ONBOARDING,r,e,n);setOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>{this.sessionStorage.writeValue([oe.ONBOARDING_IO,r,e,n],"1")};getOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>this.sessionStorage.readValue([oe.ONBOARDING_IO,r,e,n])}var Ie;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Ie||(Ie={}));class ro{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ce("gamification-background"),this.storage=new no,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new J(j(void 0),"moderationId").getStore(),this.interactiveAllowed=new J(j(Ie.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new J(j(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new te(ji(this.slStreamId,e.transport),"gamification:moderation"),this.feedList=new te(zi(this.slStreamId,this.interactiveAllowed,e.transport),"gamification:feedList"),this.betPack=new te(Wi(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=Qi(this.slStreamId,e.transport),this.openedQuestion=Yi(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(n=>{this.log.debug({item:n},"received question"),n?.questionId?(this.questionSubscription=Ki(n.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",async r=>{const i=r.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(i),i?.type===S.QuestionType.PREDICTION){const o=this.betPack.getValues().data||{};if(o?.[i.id]||Object.keys(o).length<5){const a=Je(i.id,this.transport),u=a.subscribe(()=>{});await a.get().promise;const l=await rn(i.id,this.transport);u(),window.requestAnimationFrame(()=>{a.invalidate()}),this.betPack.getStore().mutate({...o,[i.id]:l})}}}),this.questionSubscription.connect()):(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0))})),this.feedSubscription=Gi(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async n=>{const r=n.data?.attributes?.question;if(r?.type===S.QuestionType.PREDICTION){const i=this.betPack.getValues().data||{};if(i?.[r.id]||Object.keys(i).length<5){const s=Je(r.id,this.transport),a=s.subscribe(()=>{});await s.get().promise;let u=s.get().data;u||(u=await rn(r.id,this.transport)),a(),window.requestAnimationFrame(()=>{s.invalidate()}),this.betPack.getStore().mutate({...i,[r.id]:u})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",n=>{const r=this.activeQuestionId.get().data?.question?.id,i=n.data?.attributes?.question;if(!(!i||i.type===S.QuestionType.PROMOTION)){if(i.status===S.QuestionStatus.RESOLVED){r===i.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(n.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",n=>{window.requestAnimationFrame(()=>{n.data?.attributes?.question===void 0&&n.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((n,r)=>{n.data?.feedItem&&n.data?.feedItem?.id!==r?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:n.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:n.data.feedItem.id})),hasNotification:!0,type:n.data.feedItem.type}),!n.data?.feedItem&&r?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:r.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:r.data.feedItem.id})),hasNotification:!0,type:r.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const n of this.cancels)n(),this.cancels.delete(n)}),this.advertisement=eo(this.slStreamId,this.feedSubscription,e)}getCurrentSessionId=e=>{const n=e.eventId||this.slStreamId.get()||"",r=e.userId||this.userId.get()||"",i=e.organizationId||this.organizationId.get()||"",o=e.entity||"",s=e.prefix||"";return[i,n,r,s,o].join(":")};disconnect=()=>{this.feedSubscription?.disconnect(),this.questionSubscription!==void 0&&(this.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0)};openQuestion=(e,n)=>{this.openedQuestionId.set({questionId:e,question:n}),this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))};closeQuestion=e=>{this.openedQuestionId.set(void 0),e&&this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))}}class io{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ce("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=j(new Map)}addToQueue=e=>{if(this.store.has(e.id)){this.logger.debug({notification:e},"skip existed notification: %o");return}const n=e.close,r=e.action;if(this.store.set(e.id,{...e,close:(...i)=>{n&&n(...i),this.closeNotification(e.id)},action:(...i)=>{r&&r(...i),this.closeNotification(e.id,{animateHiding:!1})}}),this.waitingQueue.add(e.id),this.activeQueue.size===this.options.concurrency){const[i]=this.activeQueue;if(this.store.get(i)?.persistent!==!0)this.closeNotification(i);else{const[s]=this.waitingQueue;this.waitingQueue.size>1&&this.closeNotification(s),this.tickWaitingQueue()}}else this.tickWaitingQueue()};tickWaitingQueue=()=>{if(this.activeQueue.size<this.options.concurrency){const[e]=this.waitingQueue;if(!e)return;this.activeQueue.add(e),this.waitingQueue.delete(e),this.logger.debug({job:e},"waiting queue tick"),this.tickActiveQueue(e)}else this.logger.debug({queueSize:this.activeQueue.size,concurrency:this.options.concurrency},"waiting queue tick skipped")};tickActiveQueue=e=>{if(!e)return;const n=this.store.get(e);if(!n){this.logger.debug({notificationId:e},"active queue tick skipped, notification not exist");return}M.emit("notification",{action:"received",payload:{type:n.type,questionId:n.data.questionId,questionType:n.data.questionType}});const r=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(n.id,n),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:n.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},n.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},n.delay||0);this.timeouts.set(e,r),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:n=!0}={})=>{const r=new Map(this.notificationsList.get()),i=r.get(e);if(i){i.hiding=!(this.waitingQueue.size>=this.options.concurrency)&&n,this.notificationsList.set(r);const o=setTimeout(()=>{const s=new Map(this.notificationsList.get());s.delete(e),this.notificationsList.set(s);const a=this.timeouts.get(e);a!==void 0&&(clearTimeout(a),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&M.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})},this.options.animationDelay||0);this.timeouts.set(e,o)}return this.store.delete(e),this.activeQueue.delete(e),this.waitingQueue.delete(e),this.tickWaitingQueue(),this.logger.debug({notificationId:e},"notification hiding"),i};drain=()=>{this.store.clear(),this.timeouts.clear(),this.waitingQueue.clear(),this.activeQueue.clear(),this.notificationsList.off(),this.notificationsList.set(new Map)}}var bt;(function(t){t.OPENED="opened"})(bt||(bt={}));class oo extends xe{constructor(){super("notification")}setOpened=e=>{this.write(bt.OPENED,e,"true")};isOpened=e=>this.read(bt.OPENED,e);clearNotification=()=>{this.clear()}}class so{queue;storage;constructor(e={}){this.storage=new oo,this.queue=new io({concurrency:1,animationDelay:1600,...e})}isViewed=e=>this.storage.isOpened(e);add=e=>{if(!this.isViewed(e.id)){if(e.data&&e.emitEvent){const r=e.action;e.action=(...i)=>{r&&r(...i),M.emit("notification",{action:"opened",payload:{questionId:e.data.questionId,questionType:e.data.questionType}})}}this.queue.addToQueue(e)}};close=(e,{markAsViewed:n=!0,animateHiding:r}={})=>{this.queue.closeNotification(e,{animateHiding:r}),n&&this.markAsViewed(e)};getActiveNotification=()=>{const e=this.queue.notificationsList.get();if(!e?.size)return null;for(const r of e.values())if(r.type===me.ONBOARDING)return r;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const ao=(t,e,n)=>{t.notifications=new so(void 0),t.addNotification=t.notifications.add,t.sdk.getNotificationsStore=()=>t.notifications.getQueueStore(),t.sdk.getActiveNotification=()=>t.notifications.getActiveNotification(),t.sdk.onMount({name:"notifications"},()=>()=>{t.notifications.queue.drain()}),n()};var Xe;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(Xe||(Xe={}));const uo=async(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitAnswer"}),i=r({retryAttempts:0});try{return await n.submitAnswer({data:e},{contextValues:i})}catch(o){throw B.ConnectError.from(o)?.code===B.Code.AlreadyExists?new Error(Xe.ALREADY_VOTED):new Error(Xe.UNKNOWN)}},Er=(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(W.Feed,{method:"submitInplay"}),i=r({retryAttempts:0});return n.submitInplay({data:{eventId:+e}},{contextValues:i})},co={pageSize:10},lo=(t,e,n,r,i)=>{let o=0;const s=j({pageSize:co.pageSize,page:0}),a=H({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Mi(t),l=async()=>{const p=e.get(),w=r?.getStore().get().data?.map(E=>E.slId)||[];if(p&&w?.length){const E=n.get();E&&w.push(E),a.setKey("loading",!0),a.setKey("data",[]);const m=await u({eventId:p,usersIds:w});a.set({data:m.data.map((T,D)=>({...T.attributes,friendsRank:D+1})),hasMore:!1,key:Date.now(),loading:!1}),m.meta&&(o=Math.round(m.meta.count/m.meta.pageSize))}},c=()=>{l()},f=p=>{const w=s.get(),E=p||w.page+1;E<=o&&s.set({...w,page:E})};return ne.onMount(a,()=>{const p=e.listen(l),w=r?.listen(l);return()=>{p(),w?.()}}),{$store:a,fetchMore:f,invalidate:c}};class fo extends xe{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const qn="sldl",_t="sldl_uid",Ar="sldl_eid",Ir="sldl_e_eid",po=new Set([_t,Ar,Ir]),Bn=t=>{const e={},n={};for(const[r,i]of t)po.has(r)?e[r]=i:n[r]=i;return{result:e,remain:n}},ho=({hash:t,search:e})=>{if(t&&t.includes(qn)){const n=new URLSearchParams(t.substr(1));return{hash:Bn(n)}}if(e&&e.includes(qn)){const n=new URLSearchParams(e);return{search:Bn(n)}}return null},Mn=ce("deep_link"),ue={debug:(...t)=>{Mn.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Mn.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},yo=(t,e)=>{const{hash:n,search:r}=window.location;if(ue.debug({hash:n,search:r},"get deep link data from"),n||r){const i=ho({hash:n,search:r});if(ue.debug(i,"parse deep link result"),i){const{hash:o,search:s}=i,{result:a,remain:u}=o||s;if(Object.keys(a).length!==0){t.setValue("data",a);const l=Object.keys(u).length!==0;if(o){let c="";l&&(c=`#${new URLSearchParams(u).toString()}`,ue.debug({updatedHash:c},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+c)}if(s){let c="";l&&(c=`?${new URLSearchParams(u).toString()}`,ue.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},go=(t,e,n)=>{const r=new fo,i=r.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ue.debug(a)}t.deepLink={$store:new Ae(H(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ue.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[_t]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),r.del("sl-deep-link-store")},t.deepLink.$store.subscribe(a=>r.set("sl-deep-link-store",JSON.stringify(a))),t.sdk.addDeepLinkHandler=a=>{localStorage.getItem("SL_DEBUG")&&ue.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ue.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ue.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ue.trace("called handler"),u(a)}catch(l){console.error(l)}};yo(t.deepLink.$store,s),n()},mo=ce("bypass");class bo extends gi{$coreStore;deepLink;transport;bypassLogin;constructor(e,n,r){super(),this.$coreStore=e,this.deepLink=r,this.transport=n,this.bypassLogin=Pi(this.transport),this.connect()}me=async()=>(this.$coreStore.getValues().user.invalidate(),(await this.$coreStore.getValues().user.getValue())?.data);login=async(e,n)=>{this.$coreStore.getValues().userKey.setValue(n);const{used:r,data:i}=this.deepLink.getDeepLinkData(),o=r?"":i?.[_t];mo.debug({inviterKey:o},"login with inviterKey");const s=await this.bypassLogin({schema:e,userKey:n,inviterKey:o,init:!1}),a=s.meta?.jwt,u=s.data?.id;if(!a||!u)throw new Error("internal: token missing");return s.meta?.inviterKey&&this.deepLink.deepLinkUsed(s.meta.inviterKey),this.$coreStore.getValues().user.getStore().mutate({data:s.data}),this.saveUser(a,u),a};isAuthenticated=()=>this.me();logout=()=>{this.$coreStore.getValues().user.setValue(),this.$coreStore.getValues().userKey.setValue(),this.$coreStore.getValues().userToken.setValue(),this.transport.setAuth("",""),new $e().clear()};softLogout=()=>{const e=new $e;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const n=new $e,r=n.getToken(),i=n.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),r)return this.saveUser(r,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(r,s)}return o});if(i&&!r&&!e){const o=n.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,n)=>{this.transport.setAuth(e,n),this.$coreStore.getValues().userToken.setValue(e),new $e().setToken(e)};connect=()=>{this.transport.registerInterceptor(e=>async n=>{try{return await e(n)}catch(r){throw r.code&&(r.code===7||r.code===16)&&this.transport.getHeader("authorization")&&this.softLogout(),r}})}}const ze=new $e,vo=(t,e,n)=>{t.auth=new bo(t.store,t.transport,t.deepLink),t.stores.status.listen(r=>{r===he.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(r,i)=>{if(!(ze.getSchema()===r&&ze.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(r,i),ze.setSchema(r),ze.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),ze.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),n()},Un=ce("video_player"),ut={debug:(...t)=>{Un.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Un.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},So=(t,e,n)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=r=>{ut.trace("adding video player controller"),t.videoPlayer.controllers.add(r)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=r=>{ut.trace("removing video player controller"),t.videoPlayer.controllers.delete(r)},t.sdk.controlVideoPlayer=r=>{ut.trace("controlling video player");for(const i of t.videoPlayer.controllers){ut.trace("calling video player controller");try{i(r)}catch(o){console.error(o)}}},n()},wo={[S.QuestionType.FACTOID]:"insight",[S.QuestionType.POLL]:"poll",[S.QuestionType.TRIVIA]:"trivia",[S.QuestionType.PREDICTION]:"prediction",[S.QuestionType.TWEET]:"tweet"},To=(t,e,n)=>{t.sdk.uiState=H({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appNotification:!1,app:!1})}},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const r=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.onContentActivate){const s=o.type||i&&wo[i]||"question";t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===me.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:l,hasBanner:c,id:f,isViewed:p,type:w}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:w===S.PromotionType.EXTERNAL_AD,promotionBanner:c,promotionNotification:!1,promotionOverlay:!0,promotionSidebar:!0});break;case"received":if(t.sdk.closeFeature(),r({stage:"activate",id:f,hasNotification:l,hasBanner:c,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:c,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break}l?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:c,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),r({stage:"deactivate",id:f,hasNotification:l,hasBanner:c,isViewed:p});break}}},o=M.listen(i),s=t.activeFeature.subscribe(a=>{a?(t.ui.enableApp(),t.sdk.uiState.set({app:!0})):t.ui.disableApp()});return()=>{o(),s()}}),n()},Eo=(t,e,n)=>{const r={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=H(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const l=o.get(s);l&&l(),i.delete(s),o.delete(s)}i.set(s,{cb:u,clear:a}),t?.stores?.enabled?.get()==="on"&&o.set(s,u())},t.ready=()=>{t.stores.enabled.subscribe(s=>{s==="on"&&r.onMountedFired===!1&&(i.forEach(({cb:a},u)=>o.set(u,a())),r.onMountedFired=!0),s!=="on"&&r.onMountedFired===!0&&(o.forEach(a=>a()),o.clear(),i.forEach(({clear:a},u)=>a&&i.delete(u)),r.onMountedFired=!1)})},t.sdk.initializeApp=async s=>{if(t.contextConfig=s,t.stores.enabled.get()==="on")return{enabled:!0};t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(he.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(he.READY),{enabled:!!a}):(t.stores.status.setValue(he.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(he.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(he.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=s=>{t.stores.providerStreamId.setValue(s)},n()},Ao=(t,e)=>{const{client:n,queryKey:r}=t.createPromiseClient(Ze.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s,a)=>{if(!s)return{};try{return(await n.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes}catch{return}},dedupeTime:1e3*60*60*24,refetchInterval:0})},Io=(t,{web:e,mobile:n})=>{const{client:r}=t.createPromiseClient(ai.LinksClient,{method:"generate"});return r.generate({web:e,mobile:n})},jn=(t,e)=>{const n=new URLSearchParams(t);for(const[r,i]of Object.entries(e))n.append(r,i);return n.toString()},Oo=(t,e,n,r)=>{const i=H({});return ne.onMount(i,()=>Ao(t,[e,n]).subscribe(async({data:a,loading:u})=>{const l=a===void 0&&u===!1?"https://streamlayer.io":a?.url,c=r.get()||"",f=e.get()||"",p=n.get()||"",w={[_t]:c,[Ar]:f,[Ir]:p};if(!u&&l){i.setKey("loading",!0);let E=window.location.search,g=window.location.hash;E&&g||g?E=`?${jn(E,w)}`:g=`#${jn("",w)}`;const m=window.location.origin+window.location.pathname+E+g;try{const T=await Io(t,{web:m,mobile:l});i.set({data:T.data?.link,loading:!1})}catch{i.set({loading:!1,error:"Failed to generate short link",data:void 0})}}else i.setKey("loading",!0)})),{$store:i,fetch}};var q;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(q||(q={}));const _o=(t,e,n,r)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&n.add({type:me.ONBOARDING,id:o,action:t.openFeature,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:S.QuestionType.UNSET,onboarding:{...i,instantOpen:!r.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ct=(t,e,n,r,i,o,s,a)=>{try{const u=e.userId.get(),l=e.organizationId.get(),c=e.slStreamId.get();if(!u||!l||!c)return;const f=i.getOnboardingStatus({userId:u,organizationId:l,eventId:c});if(f===q.Completed||a?.skipOnboarding){t.set(q.Completed);for(const m of o)m();a?.skipOnboarding&&f!==q.Completed&&(i.saveOnboardingStatus({organizationId:l,userId:u,eventId:c},q.Completed),Er(s,e.slStreamId.get()||""));return}const p=e.moderation.getStore().value?.data,w=n.featureSettings.get().inplayGame;if(p===void 0||w===void 0)return;const E=p?.options?.onboardingEnabled,g=w?.titleCard?.optIn;E?g?t.set(q.Required):t.set(q.Optional):(g?t.set(q.Unavailable):t.set(q.Disabled),r.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},ko=(t,e,n,r,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=j(q.Unset);a.subscribe(c=>{c!==q.Unset&&(c===q.Optional||c===q.Required?o===!1&&(_o(t,e,r,s),o=!0):t.onboardingProcessed.set(!0),c===q.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==q.Completed&&(u.push(e.userId.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)})),u.push(e.moderation.listen(c=>{c.data&&ct(a,e,t,r,s,u,n,i)})),u.push(t.featureSettings.listen(c=>{c&&ct(a,e,t,r,s,u,n,i)}))),ct(a,e,t,r,s,u,n,i),{$store:a,submitInplay:async()=>{const c=e.slStreamId.get();if(c){await Er(n,c),a.set(q.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:c},q.Completed),M.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const f=e.getCurrentSessionId({prefix:"onboarding"});r.close(f)}}}},Co=(t,e,n,r)=>{const i=H(void 0),o=wr(r),s=async()=>{const u=t.get(),l=e.get(),c=n?n.getStore().get().data?.map(w=>w.slId):[];if(!c)return;const f={eventId:u,userId:l,usersIds:[...c,l]},p=await o(f);i.set(p.data?.attributes)},a=()=>{s()};return ne.onMount(i,()=>{a();const u=t.listen(s),l=n?.listen(s),c=e.listen(s);return()=>{u(),l?.(),c()}}),{$store:i,invalidate:a}},Po=async(t,e,n,r,i)=>{const o=wr(i),s=t.get(),a=e.get(),u=n?.getStore().get().data?.map(p=>p.slId)||[],l={eventId:s,userId:r,usersIds:[...u,a]};return(await o(l)).data?.attributes?.summary},Lo=new Set([S.QuestionType.POLL,S.QuestionType.PREDICTION,S.QuestionType.TRIVIA]);class No extends vr{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,n,r){if(super(e,n),this.background=new ro(r),this.advertisement=this.background.advertisement,this.onQuestionActivate=r.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=j(!r.sdk.withAuth),this.leaderboardId=new J(j(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.onboardingStatus=ko(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding}),this.notifications=r.notifications,this.transport=r.transport,this.closeFeature=(i=!0)=>r.sdk.closeFeature(i),this.openFeature=()=>r.sdk.openFeature(V.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=Oo(this.transport,this.background.slStreamId,r.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=Co(this.background.slStreamId,this.background.userId,this.friends,this.transport),!r.sdk.options.get().hideFriends){this.friends=new te(Ui(this.background.userId,r.transport),"gamification:friends"),this.openedUser=j(void 0);const i=this.leaderboardList=lo(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==q.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=j(!1),this.cancels.add(r.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{r.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),r.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Ie.ALLOWED}checkInteractiveFlag=()=>{const e=this.onboardingStatus.$store.get(),n=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,r=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===q.Completed,o=!n||i||r!==!0;this.background.interactiveAllowed.set(o?Ie.ALLOWED:Ie.DISALLOWED)};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const n=e.data?.attributes?.question,r=e.data?.attributes?.feedItem;if(!n||!r?.attributes)return;const{status:i,type:o,id:s,answers:a}=n;if(i===S.QuestionStatus.RESOLVED&&o===S.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),l=[...this.feedList.getValues().data||[]],c=l.findIndex(K=>K.id===s),f=l[c];let p=f?.attributes?.attributes?.value?.answerId;const w=Je(s,this.transport),E=w.subscribe(()=>{});await w.get().promise;let g=w.get().data;g||(g=await rn(s,this.transport)),E(),window.requestAnimationFrame(()=>{w.invalidate()}),p||(p=g?.answers.find(({youVoted:K})=>K)?.id);const m=a.find(({correct:K})=>K),T=p?a.find(({id:K})=>K===p):void 0,D=!!T?.correct;if(f&&l[c]?.attributes?.attributes.case==="question"){try{l[c].attributes.attributes.value.answerId=p,l[c].attributes.attributes.value.openForVoting=!1,p&&(l[c].attributes.attributes.value.status=D?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(l)}if(!T||!m)return;this.openedQuestionId.get()?.questionId!==n.id&&this.notifications.add({type:me.QUESTION_RESOLVED,action:()=>this.openQuestion(n.id,r),close:()=>this.closeQuestion(s),autoHideDuration:D?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:S.QuestionType.PREDICTION,question:{title:D?`Congratulations! You answered correctly! You won ${m.points} pts!`:`Better luck next time! Correct: ${m?.text}!`,votedAnswer:{title:T?.text,points:T?.points},correctAnswerTitle:m?.text,correct:!!D,predictionResult:i===S.QuestionStatus.RESOLVED,questionTitle:n?.subject}}}),this.userSummary.invalidate()}})),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-questions-list",e=>{const n=[...this.feedList.getStore().value?.data||[]],r=e.data?.attributes?.feedItem,i=n.findIndex(o=>o.id===r?.id);if(r?.attributes&&r.attributes.attributes.case!=="promotion"&&!(r.attributes.status!==S.QuestionStatus.ACTIVE&&r.attributes.status!==S.QuestionStatus.RESOLVED)){if(i!==-1)if(r.attributes.attributes.case==="question"&&n[i].attributes?.attributes.case==="question"){const o=n[i];o.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value,answerId:o.attributes.attributes.value.answerId,status:o.attributes.attributes.value.status,openForVoting:o.attributes.attributes.value.openForVoting}}}})}else{const o=n[i];o.attributes&&r.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value}}}})}i===-1&&(n.unshift(r),M.emit("poll",{action:"received",payload:{questionId:r.id,questionType:r.attributes?.type}})),this.feedList.getStore().mutate(n)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,n)=>{await this.submitAnswer(e,n);const i={...this.betPack.getValues().data}?.[e];i&&M.emit("poll",{action:"voted",payload:{questionId:e,questionType:i.type}})};submitAnswer=async(e,n)=>{const r=Je(e,this.transport),i=r.subscribe(()=>{}),o={...r.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(f=>f.id===e),l=a[u],c=l?.attributes?.attributes.case==="question"&&l.attributes.attributes.value;if(c){M.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=r.get().data;if(i(),f){const p=f.answers.find(m=>m.correct===!0),w=f.answers.findIndex(m=>m.id===n),E=f.answers[w],g=f.answers.every(({percentageDecimal:m},T)=>m===o?.answers[T].percentageDecimal);a[u].attributes.attributes.value.answerId=n,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=E?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===n?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[w].correct=p?.id===n,f.answers[w].youVoted=!0,g&&f.answers.forEach(m=>{m.percentageDecimal=0}),p?.id===n&&(f.answers[w].pointsEarned=f.status===S.QuestionStatus.RESOLVED?0:p.points),r.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await uo(this.transport,{questionId:e,answerId:n}),s()}catch(a){if(a.message===Xe.ALREADY_VOTED){this.userSummary.invalidate();const u=r.subscribe(()=>{});r.invalidate(),u()}throw a}};openQuestion=(e,n)=>{if(!e)return()=>{};this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let r=n?.attributes?.type;r||(r=(this.feedList.getStore().value?.data||[]).find(s=>s.id===e)?.attributes?.type);const i={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return this.storage.isQuestionOpened(i,e)||(M.emit("poll",{action:"opened",payload:{questionId:e,questionType:r,questionOpenedFrom:n?.openedFrom}}),this.storage.saveQuestionOpened(i,e)),this.openFeature(),this.background.openQuestion(e,n)};getFeedItem=e=>xi(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const n=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!n){this.openedUser?.set(n);return}if(n.summaryLoaded){this.openedUser?.set(n);return}const r={...n};try{const i=await Po(this.background.slStreamId,this.background.userId,this.friends,e,this.transport);i?.inTop!==void 0&&(this.leaderboardList?.$store.setKey("data",this.leaderboardList.$store.get().data?.map(o=>(o.userId===e&&(o.inTop=i.inTop),o))),r.inTop=i.inTop)}catch(i){console.error(i)}this.openedUser.set(r)};closeUser=()=>{this.openedUser?.set(void 0)};showInApp=e=>{const n=this.onboardingStatus.$store.get();if(e&&e.data&&n&&n!==q.Unset&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==S.SilenceSetting.ON&&e.data.question.status===S.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Lo.has(e.data.question.type))this.isInteractiveAllowed&&e.data.question.notification!==void 0&&this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*60,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),emitEvent:!0,data:{questionId:e.data.question.id,questionType:e.data.question.type,question:{title:e.data.question.notification.title},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}});else if(e.data.question.type===S.QuestionType.FACTOID){const r=e.data.question.options?.options.value,i=e.data.question.notification?.title||e.data.question.subject||"",o=e.data.question.notification?.body||r.body,s={heading:i,body:o,imageMode:r?.imageMode,image:r?.image,video:{id:r?.video?.id||"",url:r?.video?.url||"",thumbnailUrl:r?.video?.thumbnailUrl||""},webLink:{label:"",url:""}};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e?.data?.question?.id,e?.data?.feedItem),close:()=>this.closeQuestion(e?.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,insight:s,inApp:{useMediaFromContent:r.useAsNotification===S.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}else if(e.data.question.type===S.QuestionType.TWEET&&e.data.question.notification!==void 0){const r=e.data.question.options?.options.value,i={image:"",video:""};if(r.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const s=r.tweetMeta.tweet.meta.extendedEntities.media;if(s){const a=s.find(({type:u})=>u==="photo")||s[0];i.image=a.mediaUrlHttps,a.type==="video"&&(i.video=a.url)}}const o={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:r?.tweetMeta?.account||"",accountVerified:!!r?.tweetMeta?.accountVerified,tweet:r?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:i};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,tweet:o,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const Fo={[V.SdkOverlayType.GAMES]:!0};class Do extends vr{constructor(e,n){super(e,n)}}const Ro=(t,e,n)=>t.type===V.SdkOverlayType.GAMES?new No(t,e,n):new Do(t,e),Vo=(t,e,n)=>{t.features=new Map,t.sdk.featuresList=new J(j(new Set),"features-list"),t.activeFeature=new J(j(V.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=r=>t.features.get(r),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=r=>{t.activeFeature.setValue(r)},t.sdk.closeFeature=(r=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(V.SdkOverlayType.UNSET),r&&i){t.features.delete(i);const o=t.sdk.featuresList.getValue();o&&o.delete(i),t.sdk.featuresList.setValue(o)}},t.initFeature=(r,i=pe.ORGANIZATION)=>{if(r.type in Fo&&!t.features.has(r.type)){const o=Ro(r,i,t);t.features.set(r.type,o);let s=t.sdk.featuresList.getValue();s?s.add(r.type):s=new Set([r.type]),t.sdk.featuresList.setValue(new Set(s))}},t.updateFeature=(r,i)=>{t.features.get(r.type)?.update(r,i)},t.destroyFeature=r=>{t.features.delete(r.type);const i=t.sdk.featuresList.getValue();i&&i.delete(r.type),t.sdk.featuresList.setValue(new Set(i))},t.reinitializeFeatures=async()=>{const r=await t.stores.organizationSettings.getValue();t.features.clear(),t.sdk.featuresList.setValue(new Set);for(const i of r?.overlays||[])t.initFeature(i,pe.ORGANIZATION)},t.stores.providerStreamId.listen(r=>{r||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const r=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===pe.ORGANIZATION))for(const a of s.overlays)a.sdkEnable===!0&&(t.features.has(a.type)?t.updateFeature(a,o):t.initFeature(a,o))},i={organizationSettings:o=>{if(o.data)try{r(pe.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{r(pe.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},n()};class $o{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="invitation")switch(r.slEventBus.action){case"sent":this.sent(r.slEventBus.payload);break}};return M.listen(n)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:st.InvitationCategory.GAMES,from:st.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:st.InvitationCategory.GAMES,from:e||st.InvitationFrom.UNSET})}}class qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="interactions")switch(r.slEventBus.action){case"tap":this.tap();break;case"scroll":this.scroll();break}};return M.listen(n)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Dn.InteractionActionType.SCROLL})}}const Bo={[S.PromotionType.UNSET]:v.TopicSubType.UNSET,[S.PromotionType.INGAME_IAB21]:v.TopicSubType.PROMOTION_INGAME_IAB21,[S.PromotionType.INGAME_IAB11_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[S.PromotionType.INGAME_IAB11]:v.TopicSubType.PROMOTION_INGAME_IAB11,[S.PromotionType.INGAME_IAB21_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[S.PromotionType.INGAME_IAB61]:v.TopicSubType.PROMOTION_INGAME_IAB61,[S.PromotionType.EXTERNAL_AD]:v.TopicSubType.PROMOTION_GAM,[S.PromotionType.VIDEO_SIDE_BY_SIDE]:v.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[S.PromotionType.PICTURE_IN_PICTURE]:v.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[S.PromotionType.SHOP_LBAR]:v.TopicSubType.PROMOTION_SHOP_LBAR,[S.PromotionType.SHOP_OVERLAY]:v.TopicSubType.PROMOTION_SHOP_OVERLAY,[S.PromotionType.SHOP_SIDEBAR]:v.TopicSubType.PROMOTION_SHOP_SIDEBAR},on=t=>t?Bo[t]:v.TopicSubType.UNSET;class Mo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(!r.slEventBus?.skipAnalytics&&r.slEventBus?.type==="advertisement"){const i=on(r.slEventBus.payload.type);switch(r.slEventBus.action){case"videoPlay":this.videoPlay(r.slEventBus.payload,{topicSubType:i});break;case"buttonSelect":this.buttonSelect(r.slEventBus.payload,{topicSubType:i});break;case"bannerSelect":this.bannerSelect(r.slEventBus.payload,{topicSubType:i});break;case"received":this.received(r.slEventBus.payload,{topicSubType:i});break;case"opened":this.opened(r.slEventBus.payload,{topicSubType:i});break;case"viewed":this.viewed(r.slEventBus.payload,{topicSubType:i});break}}};return M.listen(n)})}received=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:n},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:n==="notification"?v.PollOpenedFrom.IN_APP:v.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_VIDEO_PLAYED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BUTTON_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BANNER_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const We={[S.QuestionType.UNSET]:v.TopicType.UNSET,[S.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[S.QuestionType.POLL]:v.TopicType.POLLS_POLL,[S.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[S.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[S.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[S.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};S.QuestionType.UNSET+"",ee.NotificationKind.UNSET,S.QuestionType.FACTOID+"",ee.NotificationKind.POLLS,S.QuestionType.POLL+"",ee.NotificationKind.POLLS,S.QuestionType.PREDICTION+"",ee.NotificationKind.POLLS,S.QuestionType.PROMOTION+"",ee.NotificationKind.POLLS,S.QuestionType.TRIVIA+"",ee.NotificationKind.POLLS,S.QuestionType.TWEET+"",ee.NotificationKind.POLLS;const Uo={[V.SdkOverlayType.UNSET]:v.Category.UNSET,[V.SdkOverlayType.INPLAY]:v.Category.INPLAY,[V.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[V.SdkOverlayType.STATISTICS]:v.Category.STATS,[V.SdkOverlayType.BETTING]:v.Category.BETTING,[V.SdkOverlayType.TWITTER]:v.Category.TWITTER,[V.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[V.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[V.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[V.SdkOverlayType.TICKETS]:v.Category.TICKETS,[V.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[V.SdkOverlayType.PROFILE]:v.Category.PROFILE,[V.SdkOverlayType.GAMES]:v.Category.POLLS,[V.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[V.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[V.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class jo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="notification")switch(r.slEventBus.action){case"rendered":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}if(r.slEventBus?.type==="advertisement")switch(r.slEventBus.action){case"notification-received":this.received({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:r.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:on(r.slEventBus.payload.type)});break}};return M.listen(n)})}received=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:n?We[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})};opened=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:n?We[n]:v.TopicType.UNSET,topicSubType:r},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})}}class Qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="poll")switch(r.slEventBus.action){case"voted":this.voted(r.slEventBus.payload);break;case"navigated":this.navigated();break;case"onboardingPassed":this.onboardingPassed();break;case"received":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}};return M.listen(n)})}received=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:n?We[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({questionId:e,questionType:n,questionOpenedFrom:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:n?We[n]:v.TopicType.UNSET},pollOpenedFrom:r==="list"?v.PollOpenedFrom.PICK_HISTORY:v.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_VOTE,topicId:e,topicType:n?We[n]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.GAMES_JOINED},pollOpenedFrom:v.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_NAVIGATED},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const xo=({transport:t,$commonStore:e})=>{let n;const r=j(!1),i=5e3,{client:o,queryKey:s}=t.createPromiseClient(hr.AnalyticsService,{method:"send",params:[r]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(w){ye.error(w,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{ye.debug("mounted heartbeat"),n=a.subscribe(()=>{})},l=()=>{ye.debug("enabled heartbeat"),r.set(!0),a.lc===0&&u()},c=()=>{ye.debug("disabled heartbeat"),r.set(!1)};return{enable:l,disable:c,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),n?.(),n=void 0,c()}}},ye=ce("analytics");class Go{commonStore;notifications;polls;invitation;interactions;advertisement;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ae(H({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=xo({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new jo(this),this.polls=new Qo(this),this.invitation=new $o(this),this.interactions=new qo(this),this.advertisement=new Mo(this);const{client:n}=e.analyticsTransport.createPromiseClient(hr.AnalyticsService,{method:"send"});this.analyticsClient=n}connect=()=>{this.writeCommon("sessionId",Zt.nanoid()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,n)=>{n&&this.analyticsClient.unary({message:{case:e,value:n}}).then(()=>{ye.trace("send analytics success",e,n)}).catch(r=>{ye.error(r,"send analytics failed")})};writeCommon=(e,n)=>{this.commonStore.setValue(e,n)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(n=>{this.writeCommon("eventId",n)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(n=>{n&&this.writeCommon("category",Uo[n]),n!==V.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Zt.nanoid()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const n=window.matchMedia("(orientation: portrait)"),r=i=>{this.writeCommon("screenOrientation",i.matches?v.ScreenOrientation.PORTRAIT:v.ScreenOrientation.LANDSCAPE)};return n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}}),this.onConnect(()=>e.deepLink.$store.subscribe(n=>{n?.handled&&this.invitation.accepted()}))}}const Ko=(t,e,n)=>{t.analytics=new Go(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),n()};var mn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var bn={exports:{}},vn={exports:{}};function Ho(t){var e=new t,n=e;function r(){var o=e;return o.next?e=o.next:(e=new t,n=e),o.next=null,o}function i(o){n.next=o,n=o}return{get:r,release:i}}var Wo=Ho,Yo=Wo;function Or(t,e,n){if(typeof t=="function"&&(n=e,e=t,t=null),!(n>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var r=Yo(Jo),i=null,o=null,s=0,a=null,u={push:g,drain:Y,saturated:Y,pause:c,paused:!1,get concurrency(){return n},set concurrency(N){if(!(N>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(n=N,!u.paused)for(;i&&s<n;)s++,T()},running:l,resume:w,idle:E,length:f,getQueue:p,unshift:m,empty:Y,kill:D,killAndDrain:K,error:X};return u;function l(){return s}function c(){u.paused=!0}function f(){for(var N=i,$=0;N;)N=N.next,$++;return $}function p(){for(var N=i,$=[];N;)$.push(N.value),N=N.next;return $}function w(){if(u.paused){if(u.paused=!1,i===null){s++,T();return}for(;i&&s<n;)s++,T()}}function E(){return s===0&&u.length()===0}function g(N,$){var k=r.get();k.context=t,k.release=T,k.value=N,k.callback=$||Y,k.errorHandler=a,s>=n||u.paused?o?(o.next=k,o=k):(i=k,o=k,u.saturated()):(s++,e.call(t,k.value,k.worked))}function m(N,$){var k=r.get();k.context=t,k.release=T,k.value=N,k.callback=$||Y,k.errorHandler=a,s>=n||u.paused?i?(k.next=i,i=k):(i=k,o=k,u.saturated()):(s++,e.call(t,k.value,k.worked))}function T(N){N&&r.release(N);var $=i;$&&s<=n?u.paused?s--:(o===i&&(o=null),i=$.next,$.next=null,e.call(t,$.value,$.worked),o===null&&u.empty()):--s===0&&u.drain()}function D(){i=null,o=null,u.drain=Y}function K(){i=null,o=null,u.drain(),u.drain=Y}function X(N){a=N}}function Y(){}function Jo(){this.value=null,this.callback=Y,this.next=null,this.release=Y,this.context=null,this.errorHandler=null;var t=this;this.worked=function(n,r){var i=t.callback,o=t.errorHandler,s=t.value;t.value=null,t.callback=Y,t.errorHandler&&o(n,s),i.call(t.context,n,r),t.release(t)}}function Xo(t,e,n){typeof t=="function"&&(n=e,e=t,t=null);function r(c,f){e.call(this,c).then(function(p){f(null,p)},f)}var i=Or(t,r,n),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=l,i;function a(c){var f=new Promise(function(p,w){o(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function u(c){var f=new Promise(function(p,w){s(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function l(){if(i.idle())return new Promise(function(p){p()});var c=i.drain,f=new Promise(function(p){i.drain=function(){c(),p()}});return f}}vn.exports=Or;vn.exports.promise=Xo;var _r=vn.exports,Sn={exports:{}},Me=typeof Reflect=="object"?Reflect:null,Qn=Me&&typeof Me.apply=="function"?Me.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},lt;Me&&typeof Me.ownKeys=="function"?lt=Me.ownKeys:Object.getOwnPropertySymbols?lt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:lt=function(e){return Object.getOwnPropertyNames(e)};function Zo(t){console&&console.warn&&console.warn(t)}var kr=Number.isNaN||function(e){return e!==e};function F(){F.init.call(this)}Sn.exports=F;Sn.exports.once=rs;F.EventEmitter=F;F.prototype._events=void 0;F.prototype._eventsCount=0;F.prototype._maxListeners=void 0;var xn=10;function kt(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(F,"defaultMaxListeners",{enumerable:!0,get:function(){return xn},set:function(t){if(typeof t!="number"||t<0||kr(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");xn=t}});F.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};F.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||kr(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Cr(t){return t._maxListeners===void 0?F.defaultMaxListeners:t._maxListeners}F.prototype.getMaxListeners=function(){return Cr(this)};F.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(n.length>0&&(s=n[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(u===void 0)return!1;if(typeof u=="function")Qn(u,this,n);else for(var l=u.length,c=Dr(u,l),r=0;r<l;++r)Qn(c[r],this,n);return!0};function Pr(t,e,n,r){var i,o,s;if(kt(n),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),o=t._events),s=o[e]),s===void 0)s=o[e]=n,++t._eventsCount;else if(typeof s=="function"?s=o[e]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=Cr(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,Zo(a)}return t}F.prototype.addListener=function(e,n){return Pr(this,e,n,!1)};F.prototype.on=F.prototype.addListener;F.prototype.prependListener=function(e,n){return Pr(this,e,n,!0)};function es(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Lr(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=es.bind(r);return i.listener=n,r.wrapFn=i,i}F.prototype.once=function(e,n){return kt(n),this.on(e,Lr(this,e,n)),this};F.prototype.prependOnceListener=function(e,n){return kt(n),this.prependListener(e,Lr(this,e,n)),this};F.prototype.removeListener=function(e,n){var r,i,o,s,a;if(kt(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(o=-1,s=r.length-1;s>=0;s--)if(r[s]===n||r[s].listener===n){a=r[s].listener,o=s;break}if(o<0)return this;o===0?r.shift():ts(r,o),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this};F.prototype.off=F.prototype.removeListener;F.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var o=Object.keys(r),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Nr(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?ns(i):Dr(i,i.length)}F.prototype.listeners=function(e){return Nr(this,e,!0)};F.prototype.rawListeners=function(e){return Nr(this,e,!1)};F.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Fr.call(t,e)};F.prototype.listenerCount=Fr;function Fr(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}F.prototype.eventNames=function(){return this._eventsCount>0?lt(this._events):[]};function Dr(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function ts(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ns(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function rs(t,e){return new Promise(function(n,r){function i(s){t.removeListener(e,o),r(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}Rr(t,e,o,{once:!0}),e!=="error"&&is(t,i,{once:!0})})}function is(t,e,n){typeof t.on=="function"&&Rr(t,"error",e,n)}function Rr(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){r.once&&t.removeEventListener(e,i),n(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Vr=Sn.exports,Ct={},$r={},qr=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},n=Symbol("test"),r=Object(n);if(typeof n=="string"||Object.prototype.toString.call(n)!=="[object Symbol]"||Object.prototype.toString.call(r)!=="[object Symbol]")return!1;var i=42;e[n]=i;for(n in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==n||!Object.prototype.propertyIsEnumerable.call(e,n))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,n);if(s.value!==i||s.enumerable!==!0)return!1}return!0},os=qr,Pt=function(){return os()&&!!Symbol.toStringTag},ss=Error,as=EvalError,us=RangeError,cs=ReferenceError,Br=SyntaxError,Lt=TypeError,ds=URIError,Gn=typeof Symbol<"u"&&Symbol,ls=qr,fs=function(){return typeof Gn!="function"||typeof Symbol!="function"||typeof Gn("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ls()},Vt={__proto__:null,foo:{}},ps=Object,hs=function(){return{__proto__:Vt}.foo===Vt.foo&&!(Vt instanceof ps)},ys="Function.prototype.bind called on incompatible ",gs=Object.prototype.toString,ms=Math.max,bs="[object Function]",Kn=function(e,n){for(var r=[],i=0;i<e.length;i+=1)r[i]=e[i];for(var o=0;o<n.length;o+=1)r[o+e.length]=n[o];return r},vs=function(e,n){for(var r=[],i=n,o=0;i<e.length;i+=1,o+=1)r[o]=e[i];return r},Ss=function(t,e){for(var n="",r=0;r<t.length;r+=1)n+=t[r],r+1<t.length&&(n+=e);return n},ws=function(e){var n=this;if(typeof n!="function"||gs.apply(n)!==bs)throw new TypeError(ys+n);for(var r=vs(arguments,1),i,o=function(){if(this instanceof i){var c=n.apply(this,Kn(r,arguments));return Object(c)===c?c:this}return n.apply(e,Kn(r,arguments))},s=ms(0,n.length-r.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Ss(a,",")+"){ return binder.apply(this,arguments); }")(o),n.prototype){var l=function(){};l.prototype=n.prototype,i.prototype=new l,l.prototype=null}return i},Ts=ws,wn=Function.prototype.bind||Ts,Es=Function.prototype.call,As=Object.prototype.hasOwnProperty,Is=wn,Os=Is.call(Es,As),_,_s=ss,ks=as,Cs=us,Ps=cs,je=Br,Ue=Lt,Ls=ds,Mr=Function,$t=function(t){try{return Mr('"use strict"; return ('+t+").constructor;")()}catch{}},Oe=Object.getOwnPropertyDescriptor;if(Oe)try{Oe({},"")}catch{Oe=null}var qt=function(){throw new Ue},Ns=Oe?function(){try{return arguments.callee,qt}catch{try{return Oe(arguments,"callee").get}catch{return qt}}}():qt,De=fs(),Fs=hs(),Q=Object.getPrototypeOf||(Fs?function(t){return t.__proto__}:null),Ve={},Ds=typeof Uint8Array>"u"||!Q?_:Q(Uint8Array),_e={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?_:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?_:ArrayBuffer,"%ArrayIteratorPrototype%":De&&Q?Q([][Symbol.iterator]()):_,"%AsyncFromSyncIteratorPrototype%":_,"%AsyncFunction%":Ve,"%AsyncGenerator%":Ve,"%AsyncGeneratorFunction%":Ve,"%AsyncIteratorPrototype%":Ve,"%Atomics%":typeof Atomics>"u"?_:Atomics,"%BigInt%":typeof BigInt>"u"?_:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?_:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?_:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?_:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":_s,"%eval%":eval,"%EvalError%":ks,"%Float32Array%":typeof Float32Array>"u"?_:Float32Array,"%Float64Array%":typeof Float64Array>"u"?_:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?_:FinalizationRegistry,"%Function%":Mr,"%GeneratorFunction%":Ve,"%Int8Array%":typeof Int8Array>"u"?_:Int8Array,"%Int16Array%":typeof Int16Array>"u"?_:Int16Array,"%Int32Array%":typeof Int32Array>"u"?_:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":De&&Q?Q(Q([][Symbol.iterator]())):_,"%JSON%":typeof JSON=="object"?JSON:_,"%Map%":typeof Map>"u"?_:Map,"%MapIteratorPrototype%":typeof Map>"u"||!De||!Q?_:Q(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?_:Promise,"%Proxy%":typeof Proxy>"u"?_:Proxy,"%RangeError%":Cs,"%ReferenceError%":Ps,"%Reflect%":typeof Reflect>"u"?_:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?_:Set,"%SetIteratorPrototype%":typeof Set>"u"||!De||!Q?_:Q(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?_:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":De&&Q?Q(""[Symbol.iterator]()):_,"%Symbol%":De?Symbol:_,"%SyntaxError%":je,"%ThrowTypeError%":Ns,"%TypedArray%":Ds,"%TypeError%":Ue,"%Uint8Array%":typeof Uint8Array>"u"?_:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?_:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?_:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?_:Uint32Array,"%URIError%":Ls,"%WeakMap%":typeof WeakMap>"u"?_:WeakMap,"%WeakRef%":typeof WeakRef>"u"?_:WeakRef,"%WeakSet%":typeof WeakSet>"u"?_:WeakSet};if(Q)try{null.error}catch(t){var Rs=Q(Q(t));_e["%Error.prototype%"]=Rs}var Vs=function t(e){var n;if(e==="%AsyncFunction%")n=$t("async function () {}");else if(e==="%GeneratorFunction%")n=$t("function* () {}");else if(e==="%AsyncGeneratorFunction%")n=$t("async function* () {}");else if(e==="%AsyncGenerator%"){var r=t("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Q&&(n=Q(i.prototype))}return _e[e]=n,n},zn={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},et=wn,vt=Os,$s=et.call(Function.call,Array.prototype.concat),qs=et.call(Function.apply,Array.prototype.splice),Hn=et.call(Function.call,String.prototype.replace),St=et.call(Function.call,String.prototype.slice),Bs=et.call(Function.call,RegExp.prototype.exec),Ms=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Us=/\\(\\)?/g,js=function(e){var n=St(e,0,1),r=St(e,-1);if(n==="%"&&r!=="%")throw new je("invalid intrinsic syntax, expected closing `%`");if(r==="%"&&n!=="%")throw new je("invalid intrinsic syntax, expected opening `%`");var i=[];return Hn(e,Ms,function(o,s,a,u){i[i.length]=a?Hn(u,Us,"$1"):s||o}),i},Qs=function(e,n){var r=e,i;if(vt(zn,r)&&(i=zn[r],r="%"+i[0]+"%"),vt(_e,r)){var o=_e[r];if(o===Ve&&(o=Vs(r)),typeof o>"u"&&!n)throw new Ue("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:o}}throw new je("intrinsic "+e+" does not exist!")},tt=function(e,n){if(typeof e!="string"||e.length===0)throw new Ue("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof n!="boolean")throw new Ue('"allowMissing" argument must be a boolean');if(Bs(/^%?[^%]*%?$/,e)===null)throw new je("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=js(e),i=r.length>0?r[0]:"",o=Qs("%"+i+"%",n),s=o.name,a=o.value,u=!1,l=o.alias;l&&(i=l[0],qs(r,$s([0,1],l)));for(var c=1,f=!0;c<r.length;c+=1){var p=r[c],w=St(p,0,1),E=St(p,-1);if((w==='"'||w==="'"||w==="`"||E==='"'||E==="'"||E==="`")&&w!==E)throw new je("property names with quotes must have matching quotes");if((p==="constructor"||!f)&&(u=!0),i+="."+p,s="%"+i+"%",vt(_e,s))a=_e[s];else if(a!=null){if(!(p in a)){if(!n)throw new Ue("base intrinsic for "+e+" exists, but the property is not available.");return}if(Oe&&c+1>=r.length){var g=Oe(a,p);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?a=g.get:a=a[p]}else f=vt(a,p),a=a[p];f&&!u&&(_e[s]=a)}}return a},Ur={exports:{}},Bt,Wn;function Tn(){if(Wn)return Bt;Wn=1;var t=tt,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Bt=e,Bt}var xs=tt,ft=xs("%Object.getOwnPropertyDescriptor%",!0);if(ft)try{ft([],"length")}catch{ft=null}var Nt=ft,Yn=Tn(),Gs=Br,Re=Lt,Jn=Nt,Ks=function(e,n,r){if(!e||typeof e!="object"&&typeof e!="function")throw new Re("`obj` must be an object or a function`");if(typeof n!="string"&&typeof n!="symbol")throw new Re("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Re("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Re("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Re("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Re("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!Jn&&Jn(e,n);if(Yn)Yn(e,n,{configurable:s===null&&u?u.configurable:!s,enumerable:i===null&&u?u.enumerable:!i,value:r,writable:o===null&&u?u.writable:!o});else if(a||!i&&!o&&!s)e[n]=r;else throw new Gs("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},sn=Tn(),jr=function(){return!!sn};jr.hasArrayLengthDefineBug=function(){if(!sn)return null;try{return sn([],"length",{value:1}).length!==1}catch{return!0}};var zs=jr,Hs=tt,Xn=Ks,Ws=zs(),Zn=Nt,er=Lt,Ys=Hs("%Math.floor%"),Js=function(e,n){if(typeof e!="function")throw new er("`fn` is not a function");if(typeof n!="number"||n<0||n>4294967295||Ys(n)!==n)throw new er("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&Zn){var s=Zn(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!r)&&(Ws?Xn(e,"length",n,!0,!0):Xn(e,"length",n)),e};(function(t){var e=wn,n=tt,r=Js,i=Lt,o=n("%Function.prototype.apply%"),s=n("%Function.prototype.call%"),a=n("%Reflect.apply%",!0)||e.call(s,o),u=Tn(),l=n("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var w=a(e,s,arguments);return r(w,1+l(0,p.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(Ur);var En=Ur.exports,Qr=tt,xr=En,Xs=xr(Qr("String.prototype.indexOf")),An=function(e,n){var r=Qr(e,!!n);return typeof r=="function"&&Xs(e,".prototype.")>-1?xr(r):r},Zs=Pt(),ea=An,an=ea("Object.prototype.toString"),Ft=function(e){return Zs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:an(e)==="[object Arguments]"},Gr=function(e){return Ft(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&an(e)!=="[object Array]"&&an(e.callee)==="[object Function]"},ta=function(){return Ft(arguments)}();Ft.isLegacyArguments=Gr;var na=ta?Ft:Gr,ra=Object.prototype.toString,ia=Function.prototype.toString,oa=/^\s*(?:function)?\*/,Kr=Pt(),Mt=Object.getPrototypeOf,sa=function(){if(!Kr)return!1;try{return Function("return function*() {}")()}catch{}},Ut,aa=function(e){if(typeof e!="function")return!1;if(oa.test(ia.call(e)))return!0;if(!Kr){var n=ra.call(e);return n==="[object GeneratorFunction]"}if(!Mt)return!1;if(typeof Ut>"u"){var r=sa();Ut=r?Mt(r):!1}return Mt(e)===Ut},zr=Function.prototype.toString,qe=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,un,pt;if(typeof qe=="function"&&typeof Object.defineProperty=="function")try{un=Object.defineProperty({},"length",{get:function(){throw pt}}),pt={},qe(function(){throw 42},null,un)}catch(t){t!==pt&&(qe=null)}else qe=null;var ua=/^\s*class\b/,cn=function(e){try{var n=zr.call(e);return ua.test(n)}catch{return!1}},jt=function(e){try{return cn(e)?!1:(zr.call(e),!0)}catch{return!1}},ht=Object.prototype.toString,ca="[object Object]",da="[object Function]",la="[object GeneratorFunction]",fa="[object HTMLAllCollection]",pa="[object HTML document.all class]",ha="[object HTMLCollection]",ya=typeof Symbol=="function"&&!!Symbol.toStringTag,ga=!(0 in[,]),dn=function(){return!1};if(typeof document=="object"){var ma=document.all;ht.call(ma)===ht.call(document.all)&&(dn=function(e){if((ga||!e)&&(typeof e>"u"||typeof e=="object"))try{var n=ht.call(e);return(n===fa||n===pa||n===ha||n===ca)&&e("")==null}catch{}return!1})}var ba=qe?function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{qe(e,null,un)}catch(n){if(n!==pt)return!1}return!cn(e)&&jt(e)}:function(e){if(dn(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(ya)return jt(e);if(cn(e))return!1;var n=ht.call(e);return n!==da&&n!==la&&!/^\[object HTML/.test(n)?!1:jt(e)},va=ba,Sa=Object.prototype.toString,Hr=Object.prototype.hasOwnProperty,wa=function(e,n,r){for(var i=0,o=e.length;i<o;i++)Hr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Ta=function(e,n,r){for(var i=0,o=e.length;i<o;i++)r==null?n(e.charAt(i),i,e):n.call(r,e.charAt(i),i,e)},Ea=function(e,n,r){for(var i in e)Hr.call(e,i)&&(r==null?n(e[i],i,e):n.call(r,e[i],i,e))},Aa=function(e,n,r){if(!va(n))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=r),Sa.call(e)==="[object Array]"?wa(e,n,i):typeof e=="string"?Ta(e,n,i):Ea(e,n,i)},Wr=Aa,Ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],Qt=Ia,Oa=typeof globalThis>"u"?mn:globalThis,Yr=function(){for(var e=[],n=0;n<Qt.length;n++)typeof Oa[Qt[n]]=="function"&&(e[e.length]=Qt[n]);return e},wt=Wr,_a=Yr,tr=En,In=An,yt=Nt,ka=In("Object.prototype.toString"),Jr=Pt(),nr=typeof globalThis>"u"?mn:globalThis,ln=_a(),On=In("String.prototype.slice"),xt=Object.getPrototypeOf,Ca=In("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},Tt={__proto__:null};Jr&&yt&&xt?wt(ln,function(t){var e=new nr[t];if(Symbol.toStringTag in e){var n=xt(e),r=yt(n,Symbol.toStringTag);if(!r){var i=xt(n);r=yt(i,Symbol.toStringTag)}Tt["$"+t]=tr(r.get)}}):wt(ln,function(t){var e=new nr[t],n=e.slice||e.set;n&&(Tt["$"+t]=tr(n))});var Pa=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{"$"+r(e)===i&&(n=On(i,1))}catch{}}),n},La=function(e){var n=!1;return wt(Tt,function(r,i){if(!n)try{r(e),n=On(i,1)}catch{}}),n},Na=function(e){if(!e||typeof e!="object")return!1;if(!Jr){var n=On(ka(e),8,-1);return Ca(ln,n)>-1?n:n!=="Object"?!1:La(e)}return yt?Pa(e):null},Et=Wr,Fa=Yr,rr=En,_n=An,gt=Nt,Da=_n("Object.prototype.toString"),Xr=Pt(),ir=typeof globalThis>"u"?mn:globalThis,fn=Fa(),kn=_n("String.prototype.slice"),Gt=Object.getPrototypeOf,Ra=_n("Array.prototype.indexOf",!0)||function(e,n){for(var r=0;r<e.length;r+=1)if(e[r]===n)return r;return-1},At={__proto__:null};Xr&>&&Gt?Et(fn,function(t){var e=new ir[t];if(Symbol.toStringTag in e){var n=Gt(e),r=gt(n,Symbol.toStringTag);if(!r){var i=Gt(n);r=gt(i,Symbol.toStringTag)}At["$"+t]=rr(r.get)}}):Et(fn,function(t){var e=new ir[t],n=e.slice||e.set;n&&(At["$"+t]=rr(n))});var Va=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{"$"+r(e)===i&&(n=kn(i,1))}catch{}}),n},$a=function(e){var n=!1;return Et(At,function(r,i){if(!n)try{r(e),n=kn(i,1)}catch{}}),n},qa=function(e){if(!e||typeof e!="object")return!1;if(!Xr){var n=kn(Da(e),8,-1);return Ra(fn,n)>-1?n:n!=="Object"?!1:$a(e)}return gt?Va(e):null},Ba=qa,Ma=function(e){return!!Ba(e)};(function(t){var e=na,n=aa,r=Na,i=Ma;function o(y){return y.call.bind(y)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),l=o(Number.prototype.valueOf),c=o(String.prototype.valueOf),f=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var w=o(Symbol.prototype.valueOf);function E(y,oi){if(typeof y!="object")return!1;try{return oi(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=n,t.isTypedArray=i;function g(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=g;function m(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||h(y)}t.isArrayBufferView=m;function T(y){return r(y)==="Uint8Array"}t.isUint8Array=T;function D(y){return r(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=D;function K(y){return r(y)==="Uint16Array"}t.isUint16Array=K;function X(y){return r(y)==="Uint32Array"}t.isUint32Array=X;function N(y){return r(y)==="Int8Array"}t.isInt8Array=N;function $(y){return r(y)==="Int16Array"}t.isInt16Array=$;function k(y){return r(y)==="Int32Array"}t.isInt32Array=k;function re(y){return r(y)==="Float32Array"}t.isFloat32Array=re;function ie(y){return r(y)==="Float64Array"}t.isFloat64Array=ie;function ke(y){return r(y)==="BigInt64Array"}t.isBigInt64Array=ke;function Se(y){return r(y)==="BigUint64Array"}t.isBigUint64Array=Se;function de(y){return u(y)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Dt(y){return typeof Map>"u"?!1:de.working?de(y):y instanceof Map}t.isMap=Dt;function ve(y){return u(y)==="[object Set]"}ve.working=typeof Set<"u"&&ve(new Set);function Ke(y){return typeof Set>"u"?!1:ve.working?ve(y):y instanceof Set}t.isSet=Ke;function Ce(y){return u(y)==="[object WeakMap]"}Ce.working=typeof WeakMap<"u"&&Ce(new WeakMap);function Rt(y){return typeof WeakMap>"u"?!1:Ce.working?Ce(y):y instanceof WeakMap}t.isWeakMap=Rt;function Pe(y){return u(y)==="[object WeakSet]"}Pe.working=typeof WeakSet<"u"&&Pe(new WeakSet);function le(y){return Pe(y)}t.isWeakSet=le;function Le(y){return u(y)==="[object ArrayBuffer]"}Le.working=typeof ArrayBuffer<"u"&&Le(new ArrayBuffer);function nt(y){return typeof ArrayBuffer>"u"?!1:Le.working?Le(y):y instanceof ArrayBuffer}t.isArrayBuffer=nt;function d(y){return u(y)==="[object DataView]"}d.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&d(new DataView(new ArrayBuffer(1),0,1));function h(y){return typeof DataView>"u"?!1:d.working?d(y):y instanceof DataView}t.isDataView=h;var b=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function A(y){return u(y)==="[object SharedArrayBuffer]"}function P(y){return typeof b>"u"?!1:(typeof A.working>"u"&&(A.working=A(new b)),A.working?A(y):y instanceof b)}t.isSharedArrayBuffer=P;function L(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=L;function O(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=O;function C(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=C;function R(y){return u(y)==="[object Generator]"}t.isGeneratorObject=R;function z(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=z;function we(y){return E(y,l)}t.isNumberObject=we;function rt(y){return E(y,c)}t.isStringObject=rt;function Ne(y){return E(y,f)}t.isBooleanObject=Ne;function it(y){return s&&E(y,p)}t.isBigIntObject=it;function Ln(y){return a&&E(y,w)}t.isSymbolObject=Ln;function ri(y){return we(y)||rt(y)||Ne(y)||it(y)||Ln(y)}t.isBoxedPrimitive=ri;function ii(y){return typeof Uint8Array<"u"&&(nt(y)||P(y))}t.isAnyArrayBuffer=ii,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})($r);var Ua=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},pn={exports:{}};typeof Object.create=="function"?pn.exports=function(e,n){n&&(e.super_=n,e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:pn.exports=function(e,n){if(n){e.super_=n;var r=function(){};r.prototype=n.prototype,e.prototype=new r,e.prototype.constructor=e}};var ja=pn.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(h){for(var b=Object.keys(h),A={},P=0;P<b.length;P++)A[b[P]]=Object.getOwnPropertyDescriptor(h,b[P]);return A},n=/%[sdj%]/g;t.format=function(d){if(!N(d)){for(var h=[],b=0;b<arguments.length;b++)h.push(s(arguments[b]));return h.join(" ")}for(var b=1,A=arguments,P=A.length,L=String(d).replace(n,function(C){if(C==="%%")return"%";if(b>=P)return C;switch(C){case"%s":return String(A[b++]);case"%d":return Number(A[b++]);case"%j":try{return JSON.stringify(A[b++])}catch{return"[Circular]"}default:return C}}),O=A[b];b<P;O=A[++b])D(O)||!ie(O)?L+=" "+O:L+=" "+s(O);return L},t.deprecate=function(d,h){if(typeof I<"u"&&I.noDeprecation===!0)return d;if(typeof I>"u")return function(){return t.deprecate(d,h).apply(this,arguments)};var b=!1;function A(){if(!b){if(I.throwDeprecation)throw new Error(h);I.traceDeprecation?console.trace(h):console.error(h),b=!0}return d.apply(this,arguments)}return A};var r={},i=/^$/;if(I.env.NODE_DEBUG){var o=I.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(d){if(d=d.toUpperCase(),!r[d])if(i.test(d)){var h=I.pid;r[d]=function(){var b=t.format.apply(t,arguments);console.error("%s %d: %s",d,h,b)}}else r[d]=function(){};return r[d]};function s(d,h){var b={seen:[],stylize:u};return arguments.length>=3&&(b.depth=arguments[2]),arguments.length>=4&&(b.colors=arguments[3]),T(h)?b.showHidden=h:h&&t._extend(b,h),k(b.showHidden)&&(b.showHidden=!1),k(b.depth)&&(b.depth=2),k(b.colors)&&(b.colors=!1),k(b.customInspect)&&(b.customInspect=!0),b.colors&&(b.stylize=a),c(b,d,b.depth)}t.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(d,h){var b=s.styles[h];return b?"\x1B["+s.colors[b][0]+"m"+d+"\x1B["+s.colors[b][1]+"m":d}function u(d,h){return d}function l(d){var h={};return d.forEach(function(b,A){h[b]=!0}),h}function c(d,h,b){if(d.customInspect&&h&&de(h.inspect)&&h.inspect!==t.inspect&&!(h.constructor&&h.constructor.prototype===h)){var A=h.inspect(b,d);return N(A)||(A=c(d,A,b)),A}var P=f(d,h);if(P)return P;var L=Object.keys(h),O=l(L);if(d.showHidden&&(L=Object.getOwnPropertyNames(h)),Se(h)&&(L.indexOf("message")>=0||L.indexOf("description")>=0))return p(h);if(L.length===0){if(de(h)){var C=h.name?": "+h.name:"";return d.stylize("[Function"+C+"]","special")}if(re(h))return d.stylize(RegExp.prototype.toString.call(h),"regexp");if(ke(h))return d.stylize(Date.prototype.toString.call(h),"date");if(Se(h))return p(h)}var R="",z=!1,we=["{","}"];if(m(h)&&(z=!0,we=["[","]"]),de(h)){var rt=h.name?": "+h.name:"";R=" [Function"+rt+"]"}if(re(h)&&(R=" "+RegExp.prototype.toString.call(h)),ke(h)&&(R=" "+Date.prototype.toUTCString.call(h)),Se(h)&&(R=" "+p(h)),L.length===0&&(!z||h.length==0))return we[0]+R+we[1];if(b<0)return re(h)?d.stylize(RegExp.prototype.toString.call(h),"regexp"):d.stylize("[Object]","special");d.seen.push(h);var Ne;return z?Ne=w(d,h,b,O,L):Ne=L.map(function(it){return E(d,h,b,O,it,z)}),d.seen.pop(),g(Ne,R,we)}function f(d,h){if(k(h))return d.stylize("undefined","undefined");if(N(h)){var b="'"+JSON.stringify(h).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return d.stylize(b,"string")}if(X(h))return d.stylize(""+h,"number");if(T(h))return d.stylize(""+h,"boolean");if(D(h))return d.stylize("null","null")}function p(d){return"["+Error.prototype.toString.call(d)+"]"}function w(d,h,b,A,P){for(var L=[],O=0,C=h.length;O<C;++O)Pe(h,String(O))?L.push(E(d,h,b,A,String(O),!0)):L.push("");return P.forEach(function(R){R.match(/^\d+$/)||L.push(E(d,h,b,A,R,!0))}),L}function E(d,h,b,A,P,L){var O,C,R;if(R=Object.getOwnPropertyDescriptor(h,P)||{value:h[P]},R.get?R.set?C=d.stylize("[Getter/Setter]","special"):C=d.stylize("[Getter]","special"):R.set&&(C=d.stylize("[Setter]","special")),Pe(A,P)||(O="["+P+"]"),C||(d.seen.indexOf(R.value)<0?(D(b)?C=c(d,R.value,null):C=c(d,R.value,b-1),C.indexOf(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ui=require("pino"),S=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),ot=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),V=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),st=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),re=require("nanostores"),Zt=require("uuid"),M=require("@connectrpc/connect"),Lr=require("@connectrpc/connect-web"),Nr=require("@nanostores/query"),hn=require("@streamlayer/sl-eslib/sports/events/events_connect"),Ze=require("@streamlayer/sl-eslib/sdkSettings/client/client_connect"),yr=require("@streamlayer/sl-eslib/users/users_connect"),W=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_connect"),yn=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_connect");require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb");const ci=require("@streamlayer/sl-eslib/shortLinks/linksClient_connect"),v=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),gn=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_connect"),Fr=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),ee=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function di(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var mn={exports:{}},U=mn.exports={},se,ae;function er(){throw new Error("setTimeout has not been defined")}function tr(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?se=setTimeout:se=er}catch{se=er}try{typeof clearTimeout=="function"?ae=clearTimeout:ae=tr}catch{ae=tr}})();function bn(t){if(se===setTimeout)return setTimeout(t,0);if((se===er||!se)&&setTimeout)return se=setTimeout,setTimeout(t,0);try{return se(t,0)}catch{try{return se.call(null,t,0)}catch{return se.call(this,t,0)}}}function li(t){if(ae===clearTimeout)return clearTimeout(t);if((ae===tr||!ae)&&clearTimeout)return ae=clearTimeout,clearTimeout(t);try{return ae(t)}catch{try{return ae.call(null,t)}catch{return ae.call(this,t)}}}var ge=[],Me=!1,Ae,dt=-1;function fi(){!Me||!Ae||(Me=!1,Ae.length?ge=Ae.concat(ge):dt=-1,ge.length&&vn())}function vn(){if(!Me){var t=bn(fi);Me=!0;for(var e=ge.length;e;){for(Ae=ge,ge=[];++dt<e;)Ae&&Ae[dt].run();dt=-1,e=ge.length}Ae=null,Me=!1,li(t)}}U.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];ge.push(new Sn(t,e)),ge.length===1&&!Me&&bn(vn)};function Sn(t,e){this.fun=t,this.array=e}Sn.prototype.run=function(){this.fun.apply(null,this.array)};U.title="browser";U.browser=!0;U.env={};U.argv=[];U.version="";U.versions={};function be(){}U.on=be;U.addListener=be;U.once=be;U.off=be;U.removeListener=be;U.removeAllListeners=be;U.emit=be;U.prependListener=be;U.prependOnceListener=be;U.listeners=function(t){return[]};U.binding=function(t){throw new Error("process.binding is not supported")};U.cwd=function(){return"/"};U.chdir=function(t){throw new Error("process.chdir is not supported")};U.umask=function(){return 0};var pi=mn.exports;const I=di(pi),hi=ui.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),ce=(t,e)=>hi.child({name:t},e);class yi extends Event{slEventBus;constructor(e,r){super(e),this.slEventBus=r}}const gi=ce("event-bus");class mi{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,r)=>{const n=new yi(this.name,{...r,type:e});gi.debug(n,"Emitting event"),window.dispatchEvent(n)};listen(e){return window.addEventListener(this.name,e),this.listeners.add(e),()=>{this.off(e)}}off(e){window.removeEventListener(this.name,e),this.listeners.delete(e)}destroy=()=>{this.listeners.forEach(e=>{window.removeEventListener(this.name,e),this.listeners.delete(e)}),this.listeners.clear()}}class bi{}var me;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(me||(me={}));window.slStore=Object.create(null);class Ot{store;name;constructor(e,r){this.store=e,this.name=r}getStore(){return this.store}}const vi=t=>{const e=Object.keys(t);return re.computed(e.map(r=>t[r].getStore()),(...r)=>Object.fromEntries(e.map((n,i)=>[n,r[i]])))};class Ie extends Ot{getValues=()=>this.getStore().get();getValue=e=>this.getStore().get()[e];setValue=(e,r)=>this.getStore().setKey(e,r);subscribe=(...e)=>this.getStore().subscribe(...e);unsubscribe=()=>this.getStore().off()}const H=t=>re.map(t);var pe;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(pe||(pe={}));const Si={[V.SdkOverlayType.BETTING]:"betting",[V.SdkOverlayType.GAMES]:"games",[V.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[V.SdkOverlayType.TWITTER]:"twitter"};var Ye;(function(t){t.Ready="ready",t.Suspended="suspended"})(Ye||(Ye={}));class wn{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...r},n){this.settingsKey=Si[r.type],this.status=re.atom(Ye.Suspended),this.config=new Ie(H(r),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ie(H(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ie(H({}),`feature:settings:${this.settingsKey}`),this.source=n}get featureConfig(){return this.config.getStore()}get featureSettings(){return this.settings.getStore()}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(Ye.Ready)};disable=()=>{this.status.set(Ye.Suspended)};setFeatureConfig=({settings:e,...r})=>{let n;for(n in r)this.config.setValue(n,r[n]);if(e?.overlaySettings?.case!==void 0&&e?.overlaySettings.case===this.settingsKey){const i=e.overlaySettings.value;if(i!==void 0){let o;for(o in i)i[o]!==0&&i[o]!==""&&this.settings.setValue(o,i[o])}}};update=(e,r)=>{this.source===pe.STREAM&&r===pe.ORGANIZATION||(this.setFeatureConfig(e),this.source=r)};fireEvent(e){for(const r of this.listeners.values())try{r.onEvent(e)}catch(n){console.error(n)}}}class J extends Ot{getValue=()=>this.getStore().get();getValues(){throw new Error("not implemented")}setValue=e=>this.getStore().set(e);subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>this.getStore().off();listen(e){return this.getStore().listen(e)}get(){return this.getStore().get()}}const Q=t=>re.atom(t);class te extends Ot{atomStore;constructor(e,r,n){super(e,`api:${r}`),this.atomStore=re.atom(),n&&e.subscribe(i=>{const o=this.atomStore.get(),s=n(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;getValue=async()=>{const e=this.getStore();if(e.value===void 0)throw new Error("no store");return await e.value.promise,e.get().data};getValues=()=>this.getStore().get();setValue=e=>this.getStore().set({loading:!1,data:e?.data});subscribe=e=>this.getStore().subscribe(e);unsubscribe=()=>{throw new Error("not implemented")};invalidate=()=>{this.store.invalidate()};listen=e=>this.getStore().listen(e);get(){throw new Error("not implemented")}key=()=>this.getStore().key;off=()=>this.getStore().off()}const q=new mi;async function*wi(t,e){for await(const r of e){t.response.message=r,t.received_at=Date.now(),t.id=Date.now();const n={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(n),yield r}}const Ti=()=>t=>async e=>{const r={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:r});try{const n=await t(e);if(r.received_at=Date.now(),r.response.header=Object.fromEntries(n.header.entries()),r.response.trailer=Object.fromEntries(n.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...r,stream:!0}};return window.postMessage(i),{...n,message:wi(r,n.message)}}else{r.response.message=n.message,r.latency=r.received_at-r.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:r};window.postMessage(i)}return n}catch(n){r.received_at=Date.now(),r.response.trailer={"grpc-status":n.code,"grpc-message":n.rawMessage},r.response.message=n.rawMessage,r.latency=r.received_at-r.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:r};throw window.postMessage(i),n}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Tn(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class Ke{delimiter=":";prefix;storage;constructor(e="main",r=window.localStorage){this.prefix=`sl-sdk${this.delimiter}${e}`,this.storage=r}clear=()=>{for(const e in window.localStorage)e.startsWith(this.prefix)&&this.storage.removeItem(e)};generateKey=e=>`${this.prefix}${this.delimiter}${e.join(this.delimiter)}`;write=(...e)=>{const r=e.pop()||"",n=this.generateKey(e);try{this.storage.setItem(n,r)}catch(i){Tn(i)&&this.storage===window.sessionStorage&&(window.sessionStorage.removeItem("slstreamlogs"),this.storage.setItem(n,r))}};read=(...e)=>{const r=this.storage.getItem(this.generateKey(e));return r===null?void 0:r};remove=(...e)=>{this.storage.removeItem(this.generateKey(e))}}var Z;(function(t){t.Init="init",t.Ready="ready",t.Connecting="connecting",t.Connected="connected",t.Disconnected="disconnected",t.Failed="failed",t.Reconnect="reconnect",t.Reconnecting="reconnecting"})(Z||(Z={}));const Dr=ce("grpc:stream");class Ei{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,r,n,i){const o={status:Z.Init,ts:new Date,log:[]};this.state=new Ie(H(o),`subscription:${i.name}:state`),this.options={...i,reconnectDelay:i.reconnectDelay??1e3,reconnectMaxDelay:i.reconnectMaxDelay??3e4,reconnectMaxAttempts:i.reconnectMaxAttempts??10,withStore:i.withStore??!1},this.headers=e,this.listeners=new Map,this.params=n,this.method=r,i.withStore&&(this.store=new J(Q(null),`subscription:${i.name}:store`)),"subscribe"in n&&typeof n.subscribe=="function"&&(this.paramsListener=n.subscribe(s=>{this.state.getValue("status")===Z.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(Z.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const r=this.state.getStore().get().log,n=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(r.push(n),this.state.setValue("log",r),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?Dr.trace({name:this.options.name,attempt:this.attempt},"received data"):Dr.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
+
`+n)}catch(i){Tn(i)&&window.sessionStorage.removeItem("slstreamlogs"),window.sessionStorage.setItem("slstreamlogs",n)}}};addListener=(e,r)=>this.listeners.has(e)?(this.addStateLog(`listener '${e}' not added, already exists`),()=>{}):(this.listeners.set(e,r),this.addStateLog(`listener '${e}' added`),()=>this.removeListener(e));removeListener=e=>{this.listeners.delete(e),this.addStateLog(`listener '${e}' removed`)};connect=()=>{this.updateState(Z.Connecting),this.streamCancel&&(this.addStateLog("disconnect prev connection"),this.streamCancel.abort(),this.streamCancel=void 0);const e="get"in this.params&&typeof this.params.get=="function"?this.params.get():this.params;(async()=>{this.streamCancel=new AbortController;try{const n={headers:this.headers.getValues(),signal:this.streamCancel.signal},i=this.method(e,n);for await(const o of i)this.attempt=0,this.onData(o)}catch(n){n instanceof M.ConnectError&&n.code!=M.Code.Canceled&&this.onStreamError(n)}})(),this.updateState(Z.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(Z.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(Z.Reconnect);const e=Math.min(this.options.reconnectMaxDelay,Math.pow(2,this.attempt)*this.options.reconnectDelay),r=Math.round(e*(1+Math.random())/2);this.reconnectTimeout=setTimeout(()=>{this.attempt++,this.updateState(Z.Reconnecting),this.addStateLog(`reconnect attempt ${this.attempt} after ${r}ms`),this.connect(),this.reconnectTimeout=void 0},r)}else this.addStateLog("max reconnect attempts reached"),this.disconnect()};getStore=()=>this.store?.getStore();onData=e=>{try{this.addStateLog(`received data => ${JSON.stringify(e)}`),this.store&&this.store.setValue(e);for(const[,r]of this.listeners)r(e);this.addStateLog(`data routed to ${this.listeners.size} listeners`)}catch(r){this.addStateLog(`error process data => ${r}`)}};onStreamError=e=>{if(this.addStateLog(`error => ${e?JSON.stringify(e):"undefined"}}`),e!==void 0){if(e instanceof M.ConnectError&&e.code!==M.Code.Canceled){this.updateState(Z.Failed),this.state.setValue("error",e),e.code===M.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const Ai=new Set([M.Code.Unknown,M.Code.Internal,M.Code.DeadlineExceeded,M.Code.ResourceExhausted,M.Code.FailedPrecondition,M.Code.Unavailable,M.Code.DataLoss]),Rr=ce("grpc:retry"),Ii=t=>async e=>{const r=e.contextValues.get(rr.retryAttempts),n=300,i=e.contextValues.get(rr.retryDelay);if(e.stream||r===0)return t(e);Rr.trace({url:e.url,attempts:r,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Rr.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=M.ConnectError.from(s);if(o>=r||!(a instanceof M.ConnectError)||!Ai.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*n),d=Math.round(u*(1+Math.random())/2);await new Promise(c=>setTimeout(c,d))}},rr={retryAttempts:M.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:M.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},Oi=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Zt.v4();return localStorage.setItem("sl-device-id",e),e},ki=()=>navigator.userAgentData?.platform||navigator.platform;class Vr{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,r){this.host=e,this.opts=r,this.$headers=new Ie(H({"sl-device-id":Oi(),"sl-device-os":ki()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[n,i,o]=Nr.nanoquery({dedupeTime:r?.dedupeTime,refetchInterval:r?.refetchInterval});this.nanoquery={createFetcherStore:n,createMutatorStore:i,utils:o},this.transport=Lr.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Lr.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,r,n)=>{const i=this.subscriptions.get(r);if(i)return i;const o=new Ei(this.$headers,e,r,n);return this.subscriptions.set(r,o),o};removeSubscription=e=>{e.disconnect(),this.subscriptions.delete(e.params)};disconnect=()=>{for(const[i,o]of this.subscriptions)o.disconnect(),this.subscriptions.delete(i);this.clients.clear(),this.streamClients.clear(),this.subscriptions.clear();const[e,r,n]=Nr.nanoquery({dedupeTime:this.opts?.dedupeTime,refetchInterval:this.opts?.refetchInterval});this.nanoquery={createFetcherStore:e,createMutatorStore:r,utils:n}};registerInterceptor=e=>{this.interceptors.push(e)};removeInterceptor=e=>{this.interceptors=this.interceptors.filter(r=>r!==e)};getClient=e=>{const r=e.typeName;if(this.clients.has(r))return this.clients.get(r);const n=M.createClient(e,this.transport);return this.clients.set(r,n),n};getStreamClient=e=>{const r=`stream-${e.typeName}`;if(this.clients.has(r))return this.clients.get(r);const n=M.createClient(e,this.streamTransport);return this.clients.set(r,n),n};createPromiseClient=(e,{params:r=[],method:n})=>{const i=this.getClient(e),o=e.methods[n].name,s=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1),...Array.isArray(r)?r:[r]],a=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1)];return{client:i,createRequestOptions:d=>{const c=M.createContextValues();for(const f in d){const p=rr[f];c.set(p,d[f])}return c},queryKey:s,queryKeyStr:a.join("")}};createStreamClient=e=>({client:this.getStreamClient(e)});setSdkKey=e=>{this.$headers.setValue("sdk",e)};setAuth=(e,r)=>{this.$headers.setValue("authorization",e),this.$headers.setValue("sl-user-id",r)};setHeader=(e,r)=>this.$headers.setValue(e,r);getHeader=e=>this.$headers.getValue(e);getHeaders=()=>this.$headers.getValues();initInterceptors=()=>{if(this.interceptors.length!==0)return;const e=r=>n=>{const i=this.$headers.getValues();for(const o in i)n.header.set(o,i[o]);return r(n)};this.interceptors.push(e),this.interceptors.push(Ti()),this.opts?.retryable&&this.interceptors.push(Ii)}}const _i=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(hn.Events,{method:"retrieveEventId",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>{if(!s||typeof s!="string")return"";try{return(await r.retrieveEventId({id:s})).data?.id||""}catch{return""}}})},Ci=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ze.Client,{method:"getStream",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.getStream({id:s})).data?.attributes:void 0})},Pi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(hn.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.summary({id:s})).data?.attributes:void 0})},Li=(t,e)=>{const{queryKey:r,client:n}=e.createPromiseClient(yr.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{const{data:i}=await n.me({});return{data:i}}})},Ni=t=>{const{client:e,createRequestOptions:r}=t.createPromiseClient(yr.Users,{method:"bypassAuth"}),n=r({retryAttempts:0});return({userKey:i,schema:o,init:s,inviterKey:a})=>e.bypassAuth({userKey:i,schema:o,init:s,inviterKey:a},{contextValues:n})},Fi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ze.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.get({})).data?.attributes})},Di=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ze.Client,{method:"getOrganization",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>{const i=await r.getOrganization({});return i.data?{...i.data.attributes,id:i.data.id}:void 0}})},Ri=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ze.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.getOrganizationAdvertising({})).data?.attributes})},Vi=(t,e,r)=>{t.transport=new Vr(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new Vr(e.analyticsHost),t.sdk.host=t.transport.host,t.transport.setSdkKey(e.sdkKey),t.transport.setHeader("sl-sdk-version",e.version||"-"),t.transport.$headers.subscribe(n=>{t.analyticsTransport.$headers.getStore().set(n)}),t.sdk.onMount({name:"transport"},()=>()=>{t.transport.disconnect(),t.analyticsTransport.disconnect()}),r()};var fe;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(fe||(fe={}));class $e extends Ke{constructor(){super("user")}setSchema=e=>{this.write(fe.SCHEMA,e)};getSchema=()=>this.read(fe.SCHEMA);setToken=e=>{this.write(fe.TOKEN,e)};getToken=()=>this.read(fe.TOKEN);setExternalToken=e=>{this.write(fe.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(fe.EXTERNAL_TOKEN);removeToken=()=>{this.remove(fe.TOKEN)}}var he;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(he||(he={}));const $i=t=>{const e=new $e,r=new J(Q(e.getExternalToken()),"userKey"),n=new J(Q(e.getToken()),"userToken"),i=new te(Li(n.getStore(),t),"user",({data:s,error:a,loading:u},d)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:d}),o=new te(Fi(n.getStore(),t),"userSettings");return{userKey:r,userToken:n,user:i,userSettings:o}},Bi=t=>{const e=new J(Q(void 0),"providerStreamId"),r=new te(_i(e.getStore(),t),"slStreamId",o=>o?.data),n=new te(Ci(r.getAtomStore(),t),"streamSettings"),i=new te(Pi(r.getAtomStore(),t),"streamSettings");return r.getAtomStore().listen(o=>{(o===""||o===void 0)&&(n.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:r,streamSettings:n,streamSummary:i}},Mi=t=>{const e=new J(Q(void 0),"enabled"),r=new J(Q(he.DISABLED),"status"),n=new te(Di(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new te(Ri(n.getAtomStore(),t),"organizationAdvertising"),o=$i(t),s=Bi(t);return{enabled:e,status:r,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:n,organizationAdvertising:i}};class qi extends Ot{stores;constructor(e){const r=Mi(e),n=vi(r);super(n,"core"),this.stores=r}getValue(){throw new Error("Not implemented")}getValues(){return this.stores}setValue(){throw new Error("Not implemented")}subscribe=e=>{let r;for(r in this.stores){const n=e[r];r in e&&n!==void 0&&this.stores[r].subscribe(e[r])}};unsubscribe=()=>this.getStore().off()}const Ui=(t,e,r)=>{t.store=new qi(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([n,i])=>[n,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},r()},Qi=t=>{const{client:e}=t.createPromiseClient(yn.Leaderboard,{method:"list"});return r=>e.list(r)},En=t=>{const{client:e}=t.createPromiseClient(yn.Leaderboard,{method:"summary"});return r=>e.summary(r)},ji=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(yr.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>{if(!s)return[];try{return(await r.getFriends({})).data}catch{return[]}}})},xi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(W.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>(await r.get({eventId:s})).data?.attributes,refetchInterval:0,dedupeTime:1e3*60*60})},Gi=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(W.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const d=await n.syncQuestion({filter:{eventId:a}});if(d.data?.attributes?.question?.type!==S.QuestionType.PROMOTION)return d.data?.attributes},dedupeTime:1e3*60*10,refetchInterval:0})},Ki=async(t,e)=>{const{client:r}=e.createPromiseClient(W.Feed,{method:"item",params:[t]});return(await r.item({id:t})).data},zi=(t,e)=>{const{client:r}=e.createStreamClient(W.Feed),n=re.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{n.set({eventId:o,feedId:""})}),e.addSubscription(r.subscription,n,{name:"feedSubscription"})},Hi=(t,e)=>{const{client:r}=e.createStreamClient(W.Feed);return e.addSubscription(r.questionSubscription,{questionId:t},{name:"questionSubscription"})},nr=async(t,e)=>{const{client:r}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return(await r.questionByUser({questionId:t})).data?.attributes?.question},qe=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(W.Feed,{method:"questionByUser",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>(await r.questionByUser({questionId:s})).data?.attributes?.question,dedupeTime:1e3*60*5})},An=async(t,e)=>{if(!t)return;const{client:r}=e.createPromiseClient(W.Feed,{method:"getQuestion",params:[t]}),n=await r.getQuestion({id:t});if(!n.data?.attributes)return;const{options:i,notification:o,...s}=n.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},Wi=(t,e,r,n)=>{const{client:i,queryKey:o}=n.createPromiseClient(W.Feed,{method:"list",params:[t,e,r?"true":""]});return n.nanoquery.createFetcherStore(o,{fetcher:async(s,a,u,d,c)=>!u||c?[]:(await i.list({eventId:u,filter:{types:d===Se.ALLOWED?[]:[S.QuestionType.FACTOID,S.QuestionType.PROMOTION,S.QuestionType.TWEET],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED]}})).data,dedupeTime:0,refetchInterval:0})},Yi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(W.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await r.list({eventId:s,filter:{types:[S.QuestionType.PROMOTION],statuses:[S.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return An(u.id,e)},dedupeTime:0,refetchInterval:0})},Ji=(t,e,r,n,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(W.Feed,{method:"betPack",params:[t,e,r]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,d,c,f)=>{if(!d||!c||!f)return null;const p=await o.betPack({eventId:d,types:[S.QuestionType.PREDICTION],statuses:[S.QuestionStatus.ACTIVE,S.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?null:p.data?.reduce((w,E)=>{const g=E?.attributes?.question;if(!g?.id)return w;const m={eventId:d,userId:c,organizationId:f};return n.isBetPackQuestionReceived(m,g.id)||(q.emit("poll",{action:"received",payload:{questionId:g.id,questionType:g.type}}),n.saveBetPackQuestionReceived(m,g.id)),{...w,[g.id]:g}},{})},dedupeTime:0,refetchInterval:0})},Xi=(t,e,r)=>{const n=re.batched([e,r],()=>{const a=e.get();if(!a)return;const u=r.get().data?.find(c=>c.id===a?.questionId),d=a?.question?.openedFrom;return u?(u.openedFrom=d,u):a.question}),i=re.batched(n,a=>a&&a.type==="question"?a.id:void 0),o=qe(i,t);return{$store:n,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,d=(c,f)=>{if(!c||!f)return c||f||[];const p=[];for(let w=0;w<c.length;w++)p.push({...c[w],...f[w],correct:c[w].correct,youVoted:c[w].youVoted,pointsEarned:c[w].pointsEarned});return p};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:d(u?.answers,a?.answers)})}}};var mt;(function(t){t.SHOWED="showed"})(mt||(mt={}));class Zi extends Ke{constructor(){super("advertisement")}setShowed=e=>{this.write(mt.SHOWED,e,"true")};isViewed=e=>this.read(mt.SHOWED,e)}const eo=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:n,notification:i,...o}=e,s=n?.options.case==="promotion"?n.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},at=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,to=({gamOptions:t,gamBaseUrl:e})=>{const r=`${e}?`,n=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")n.push(`${o}=${at(s)}`);else if(Array.isArray(s))n.push(`${o}=${s.map(at).join(",")}`);else{const a=Object.entries(s).map(([u,d])=>Array.isArray(d)?`${u}=${d.map(at).join(",")}`:typeof d=="string"?`${u}=${at(d)}`:`${u}=${d}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");n.push(`${o}=${a}`)}}return r+n.join("&")},Fe=t=>(t?.promotion?.type===S.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===S.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,ro=(t,e,r)=>{let n=!1;const i=r.transport,o=ce("advertisement"),s=new Zi,a=H({}),u=Yi(t,i),d=g=>{const m=a.get(),T=m.data?.question.id,D=m.data?.promotion?.type;T&&(q.emit("advertisement",{action:"opened",payload:{id:T,type:D,hasBanner:Fe(m.data),openedFrom:g?.fromNotification?"notification":"auto"}}),g?.fromNotification&&(a.setKey("hasNotification",!1),q.emit("advertisement",{action:"notification-opened",payload:{id:T,type:D,hasBanner:Fe(m.data)}})))},c=()=>{const g=a.get(),m=g.data?.question.id,T=g.data?.promotion?.type,D=a.get()?.isOpened;m&&!D&&(o.debug({id:m},"markAsViewed: %o"),s.setShowed(m),a.setKey("isOpened",!0),q.emit("advertisement",{action:"viewed",payload:{id:m,type:T,hasBanner:Fe(g.data)}}))},f=(g,m)=>{m?a.set({loading:!1,error:void 0,data:m,hasNotification:m?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(m.question.id),togglePause:T=>w(m.question.id,T),isViewed:!!s.isViewed(m.question.id)}):(a.setKey("loading",!0),An(g,i).then(T=>a.set({loading:!1,error:void 0,data:T,hasNotification:T?.notification?.enabled===S.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>p(T?.question.id),togglePause:D=>w(T?.question.id,D),isViewed:T&&!!s.isViewed(T.question.id)})).catch(T=>a.set({loading:!1,error:T,data:void 0})))};a.subscribe((g,m)=>{if(!(g.data?.id===m?.data?.id&&g.isPaused!==m?.isPaused)){if(g.data?.promotion?.type===S.PromotionType.EXTERNAL_AD&&!g?.externalAd&&g.data.promotion.adCampaigns?.gamOptions&&g.data.promotion.adCampaigns?.gamBaseUrl){const T=to(g.data.promotion.adCampaigns);a.setKey("externalAd",{type:"gam",url:T})}g.data?.promotion&&!g.isOpened&&(q.emit("advertisement",{action:"received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!!g.hasNotification,hasBanner:Fe(g.data),isViewed:!!s.isViewed(g.data.question.id)},skipAnalytics:g.data.question.id===m?.data?.question.id}),g.data.question.id!==m?.data?.question.id&&!s.isViewed(g.data.question.id)&&q.emit("advertisement",{action:"notification-received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!0,hasBanner:Fe(g.data),isViewed:!1}})),!g?.data&&m?.data&&q.emit("advertisement",{action:"closed",payload:{id:m.data.question.id,type:m.data.promotion?.type,hasNotification:!!m.hasNotification,hasBanner:Fe(m.data),isViewed:!!s.isViewed(m.data.question.id)}})}});const p=g=>{(!g||a.get()?.data?.question.id===g)&&a.set({})},w=(g,m)=>{a.get()?.data?.question.id===g&&a.setKey("isPaused",m)};return{connect:()=>{n||(n=!0,u.subscribe((g,m)=>{g.data&&(!m?.data||g.data.id!==m.data.id)&&f(g.data.question.id,g.data)}),e.addListener("promotion",g=>{const m=eo(g);if(m){if(m.question.status===S.QuestionStatus.RESOLVED){p(m.question.id),o.debug({promotion:m},"resolved: %o");return}if(m.question.status===S.QuestionStatus.ACTIVE){o.debug({promotion:m},"active: %o"),f(m.question.id,m);return}o.debug({promotion:m},"skip: %o")}}))},hide:p,show:f,open:d,markAsViewed:c,$store:a}};var oe;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.BET_PACK_ITEM_RECEIVED="bp-item-received",t.QUESTION_OPENED="q-opened"})(oe||(oe={}));class no extends Ke{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,r)=>{this.write(...e,r)};readValue=e=>this.read(...e)}class io extends Ke{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new no}saveBetPackQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>{this.write(oe.BET_PACK_ITEM_RECEIVED,n,e,r,i)};isBetPackQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(oe.BET_PACK_ITEM_RECEIVED,n,e,r,i);saveQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>{this.write(oe.QUESTION_OPENED,n,e,r,i)};isQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(oe.QUESTION_OPENED,n,e,r,i);saveOnboardingStatus=({userId:e,eventId:r,organizationId:n},i)=>{this.write(oe.ONBOARDING,n,e,r,i)};getOnboardingStatus=({userId:e,eventId:r,organizationId:n})=>this.read(oe.ONBOARDING,n,e,r);setOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{this.sessionStorage.writeValue([oe.ONBOARDING_IO,n,e,r],"1")};getOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>this.sessionStorage.readValue([oe.ONBOARDING_IO,n,e,r])}var Se;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Se||(Se={}));class oo{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ce("gamification-background"),this.storage=new io,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new J(Q(void 0),"moderationId").getStore(),this.interactiveAllowed=new J(Q(Se.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new J(Q(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new te(xi(this.slStreamId,e.transport),"gamification:moderation");const r=!!e.sdk.options.get().betPack;this.feedList=new te(Wi(this.slStreamId,this.interactiveAllowed,r,e.transport),"gamification:feedList"),this.betPack=new te(Ji(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=Gi(this.slStreamId,r,e.transport),this.openedQuestion=Xi(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(n=>{this.log.debug({item:n},"received question"),n?.questionId?(this.questionSubscription=Hi(n.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",async i=>{const o=i.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(o),o?.type===S.QuestionType.PREDICTION&&(o.status===S.QuestionStatus.ACTIVE||o.status===S.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data||{};if(s?.[o.id]||Object.keys(s).length<5){const u=qe(o.id,this.transport),d=u.subscribe(()=>{});await u.get().promise;let c=u.get().data;c||(c=await nr(o.id,this.transport)),d(),window.requestAnimationFrame(()=>{u.invalidate()}),this.betPack.getStore().mutate({...s,[o.id]:c})}}}),this.questionSubscription.connect()):(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0))})),this.feedSubscription=zi(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async n=>{const i=n.data?.attributes?.question;if(i?.type===S.QuestionType.PREDICTION&&(i.status===S.QuestionStatus.ACTIVE||i.status===S.QuestionStatus.RESOLVED)){const o=this.betPack.getValues().data||{};if(o?.[i.id]||Object.keys(o).length<5){const a=qe(i.id,this.transport),u=a.subscribe(()=>{});await a.get().promise;let d=a.get().data;d||(d=await nr(i.id,this.transport)),u(),window.requestAnimationFrame(()=>{a.invalidate()}),this.betPack.getStore().mutate({...o,[i.id]:d})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",n=>{const i=this.activeQuestionId.get().data?.question?.id,o=n.data?.attributes?.question;if(!(!o||o.type===S.QuestionType.PROMOTION)){if(o.status===S.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(n.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",n=>{window.requestAnimationFrame(()=>{n.data?.attributes?.question===void 0&&n.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((n,i)=>{n.data?.feedItem&&n.data?.feedItem?.id!==i?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:n.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:n.data.feedItem.id})),hasNotification:!0,type:n.data.feedItem.type}),!n.data?.feedItem&&i?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:i.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:i.data.feedItem.id})),hasNotification:!0,type:i.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const n of this.cancels)n(),this.cancels.delete(n)}),r||(this.advertisement=ro(this.slStreamId,this.feedSubscription,e))}getCurrentSessionId=e=>{const r=e.eventId||this.slStreamId.get()||"",n=e.userId||this.userId.get()||"",i=e.organizationId||this.organizationId.get()||"",o=e.entity||"",s=e.prefix||"";return[i,r,n,s,o].join(":")};disconnect=()=>{this.feedSubscription?.disconnect(),this.questionSubscription!==void 0&&(this.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0)};openQuestion=(e,r)=>{this.openedQuestionId.set({questionId:e,question:r}),this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))};closeQuestion=e=>{this.openedQuestionId.set(void 0),e&&this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))}}class so{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ce("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=Q(new Map)}addToQueue=e=>{if(this.store.has(e.id)){this.logger.debug({notification:e},"skip existed notification: %o");return}const r=e.close,n=e.action;if(this.store.set(e.id,{...e,close:(...i)=>{r&&r(...i),this.closeNotification(e.id)},action:(...i)=>{n&&n(...i),this.closeNotification(e.id,{animateHiding:!1})}}),this.waitingQueue.add(e.id),this.activeQueue.size===this.options.concurrency){const[i]=this.activeQueue;if(this.store.get(i)?.persistent!==!0)this.closeNotification(i);else{const[s]=this.waitingQueue;this.waitingQueue.size>1&&this.closeNotification(s),this.tickWaitingQueue()}}else this.tickWaitingQueue()};tickWaitingQueue=()=>{if(this.activeQueue.size<this.options.concurrency){const[e]=this.waitingQueue;if(!e)return;this.activeQueue.add(e),this.waitingQueue.delete(e),this.logger.debug({job:e},"waiting queue tick"),this.tickActiveQueue(e)}else this.logger.debug({queueSize:this.activeQueue.size,concurrency:this.options.concurrency},"waiting queue tick skipped")};tickActiveQueue=e=>{if(!e)return;const r=this.store.get(e);if(!r){this.logger.debug({notificationId:e},"active queue tick skipped, notification not exist");return}q.emit("notification",{action:"received",payload:{type:r.type,questionId:r.data.questionId,questionType:r.data.questionType}});const n=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(r.id,r),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:r.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},r.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},r.delay||0);this.timeouts.set(e,n),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:r=!0}={})=>{const n=new Map(this.notificationsList.get()),i=n.get(e);if(i){i.hiding=!(this.waitingQueue.size>=this.options.concurrency)&&r,this.notificationsList.set(n);const o=setTimeout(()=>{const s=new Map(this.notificationsList.get());s.delete(e),this.notificationsList.set(s);const a=this.timeouts.get(e);a!==void 0&&(clearTimeout(a),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&q.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})},this.options.animationDelay||0);this.timeouts.set(e,o)}return this.store.delete(e),this.activeQueue.delete(e),this.waitingQueue.delete(e),this.tickWaitingQueue(),this.logger.debug({notificationId:e},"notification hiding"),i};drain=()=>{this.store.clear(),this.timeouts.clear(),this.waitingQueue.clear(),this.activeQueue.clear(),this.notificationsList.off(),this.notificationsList.set(new Map)}}var bt;(function(t){t.OPENED="opened"})(bt||(bt={}));class ao extends Ke{constructor(){super("notification")}setOpened=e=>{this.write(bt.OPENED,e,"true")};isOpened=e=>this.read(bt.OPENED,e);clearNotification=()=>{this.clear()}}class uo{queue;storage;constructor(e={}){this.storage=new ao,this.queue=new so({concurrency:1,animationDelay:1600,...e})}isViewed=e=>this.storage.isOpened(e);add=e=>{if(!this.isViewed(e.id)){if(e.data&&e.emitEvent){const n=e.action;e.action=(...i)=>{n&&n(...i),q.emit("notification",{action:"opened",payload:{questionId:e.data.questionId,questionType:e.data.questionType}})}}this.queue.addToQueue(e)}};close=(e,{markAsViewed:r=!0,animateHiding:n}={})=>{this.queue.closeNotification(e,{animateHiding:n}),r&&this.markAsViewed(e)};getActiveNotification=()=>{const e=this.queue.notificationsList.get();if(!e?.size)return null;for(const n of e.values())if(n.type===me.ONBOARDING)return n;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const co=(t,e,r)=>{t.notifications=new uo(void 0),t.addNotification=t.notifications.add,t.sdk.getNotificationsStore=()=>t.notifications.getQueueStore(),t.sdk.getActiveNotification=()=>t.notifications.getActiveNotification(),t.sdk.onMount({name:"notifications"},()=>()=>{t.notifications.queue.drain()}),r()};var je;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(je||(je={}));const $r=async(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(W.Feed,{method:"submitAnswer"}),i=n({retryAttempts:0});try{return await r.submitAnswer({data:e},{contextValues:i})}catch(o){throw M.ConnectError.from(o)?.code===M.Code.AlreadyExists?new Error(je.ALREADY_VOTED):new Error(je.UNKNOWN)}},In=(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(W.Feed,{method:"submitInplay"}),i=n({retryAttempts:0});return r.submitInplay({data:{eventId:+e}},{contextValues:i})},lo={pageSize:10},fo=(t,e,r,n,i)=>{let o=0;const s=Q({pageSize:lo.pageSize,page:0}),a=H({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Qi(t),d=async()=>{const p=e.get(),w=n?.getStore().get().data?.map(E=>E.slId)||[];if(p&&w?.length){const E=r.get();E&&w.push(E),a.setKey("loading",!0),a.setKey("data",[]);const m=await u({eventId:p,usersIds:w});a.set({data:m.data.map((T,D)=>({...T.attributes,friendsRank:D+1})),hasMore:!1,key:Date.now(),loading:!1}),m.meta&&(o=Math.round(m.meta.count/m.meta.pageSize))}},c=()=>{d()},f=p=>{const w=s.get(),E=p||w.page+1;E<=o&&s.set({...w,page:E})};return re.onMount(a,()=>{const p=e.listen(d),w=n?.listen(d);return()=>{p(),w?.()}}),{$store:a,fetchMore:f,invalidate:c}};class po extends Ke{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Br="sldl",kt="sldl_uid",On="sldl_eid",kn="sldl_e_eid",ho=new Set([kt,On,kn]),Mr=t=>{const e={},r={};for(const[n,i]of t)ho.has(n)?e[n]=i:r[n]=i;return{result:e,remain:r}},yo=({hash:t,search:e})=>{if(t&&t.includes(Br)){const r=new URLSearchParams(t.substr(1));return{hash:Mr(r)}}if(e&&e.includes(Br)){const r=new URLSearchParams(e);return{search:Mr(r)}}return null},qr=ce("deep_link"),ue={debug:(...t)=>{qr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{qr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},go=(t,e)=>{const{hash:r,search:n}=window.location;if(ue.debug({hash:r,search:n},"get deep link data from"),r||n){const i=yo({hash:r,search:n});if(ue.debug(i,"parse deep link result"),i){const{hash:o,search:s}=i,{result:a,remain:u}=o||s;if(Object.keys(a).length!==0){t.setValue("data",a);const d=Object.keys(u).length!==0;if(o){let c="";d&&(c=`#${new URLSearchParams(u).toString()}`,ue.debug({updatedHash:c},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+c)}if(s){let c="";d&&(c=`?${new URLSearchParams(u).toString()}`,ue.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},mo=(t,e,r)=>{const n=new po,i=n.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ue.debug(a)}t.deepLink={$store:new Ie(H(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ue.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[kt]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),n.del("sl-deep-link-store")},t.deepLink.$store.subscribe(a=>n.set("sl-deep-link-store",JSON.stringify(a))),t.sdk.addDeepLinkHandler=a=>{localStorage.getItem("SL_DEBUG")&&ue.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ue.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ue.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ue.trace("called handler"),u(a)}catch(d){console.error(d)}};go(t.deepLink.$store,s),r()},bo=ce("bypass");class vo extends bi{$coreStore;deepLink;transport;bypassLogin;constructor(e,r,n){super(),this.$coreStore=e,this.deepLink=n,this.transport=r,this.bypassLogin=Ni(this.transport),this.connect()}me=async()=>(this.$coreStore.getValues().user.invalidate(),(await this.$coreStore.getValues().user.getValue())?.data);login=async(e,r)=>{this.$coreStore.getValues().userKey.setValue(r);const{used:n,data:i}=this.deepLink.getDeepLinkData(),o=n?"":i?.[kt];bo.debug({inviterKey:o},"login with inviterKey");const s=await this.bypassLogin({schema:e,userKey:r,inviterKey:o,init:!1}),a=s.meta?.jwt,u=s.data?.id;if(!a||!u)throw new Error("internal: token missing");return s.meta?.inviterKey&&this.deepLink.deepLinkUsed(s.meta.inviterKey),this.$coreStore.getValues().user.getStore().mutate({data:s.data}),this.saveUser(a,u),a};isAuthenticated=()=>this.me();logout=()=>{this.$coreStore.getValues().user.setValue(),this.$coreStore.getValues().userKey.setValue(),this.$coreStore.getValues().userToken.setValue(),this.transport.setAuth("",""),new $e().clear()};softLogout=()=>{const e=new $e;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const r=new $e,n=r.getToken(),i=r.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),n)return this.saveUser(n,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(n,s)}return o});if(i&&!n&&!e){const o=r.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,r)=>{this.transport.setAuth(e,r),this.$coreStore.getValues().userToken.setValue(e),new $e().setToken(e)};connect=()=>{this.transport.registerInterceptor(e=>async r=>{try{return await e(r)}catch(n){throw n.code&&(n.code===7||n.code===16)&&this.transport.getHeader("authorization")&&this.softLogout(),n}})}}const We=new $e,So=(t,e,r)=>{t.auth=new vo(t.store,t.transport,t.deepLink),t.stores.status.listen(n=>{n===he.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(n,i)=>{if(!(We.getSchema()===n&&We.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(n,i),We.setSchema(n),We.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),We.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),r()},Ur=ce("video_player"),ut={debug:(...t)=>{Ur.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Ur.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},wo=(t,e,r)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=n=>{ut.trace("adding video player controller"),t.videoPlayer.controllers.add(n)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=n=>{ut.trace("removing video player controller"),t.videoPlayer.controllers.delete(n)},t.sdk.controlVideoPlayer=n=>{ut.trace("controlling video player");for(const i of t.videoPlayer.controllers){ut.trace("calling video player controller");try{i(n)}catch(o){console.error(o)}}},r()},To={[S.QuestionType.FACTOID]:"insight",[S.QuestionType.POLL]:"poll",[S.QuestionType.TRIVIA]:"trivia",[S.QuestionType.PREDICTION]:"prediction",[S.QuestionType.TWEET]:"tweet"},Eo=(t,e,r)=>{t.sdk.uiState=H({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appNotification:!1,app:!1})}},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const n=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.onContentActivate){const s=o.type||i&&To[i]||"question";t.ui.enableAppNotification(),t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="app")switch(a.slEventBus.action){case"open":t.ui.enableApp();break;case"close":t.ui.disableApp();break}if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===me.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:d,hasBanner:c,id:f,isViewed:p,type:w}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:w===S.PromotionType.EXTERNAL_AD,promotionBanner:c,promotionNotification:!1,promotionOverlay:!0,promotionSidebar:!0});break;case"received":if(t.sdk.closeFeature(),n({stage:"activate",id:f,hasNotification:d,hasBanner:c,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:c,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break}d?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:c,promotionOverlay:!0,promotionSidebar:!0,promotionExternalAd:w===S.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),n({stage:"deactivate",id:f,hasNotification:d,hasBanner:c,isViewed:p});break}}},o=q.listen(i),s=t.activeFeature.subscribe(a=>{a?(t.ui.enableApp(),t.sdk.uiState.set({app:!0})):t.ui.disableApp()});return()=>{o(),s()}}),r()},Ao=(t,e,r)=>{const n={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=H(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const d=o.get(s);d&&d(),i.delete(s),o.delete(s)}i.set(s,{cb:u,clear:a}),t?.stores?.enabled?.get()==="on"&&o.set(s,u())},t.ready=()=>{t.stores.enabled.subscribe(s=>{s==="on"&&n.onMountedFired===!1&&(i.forEach(({cb:a},u)=>o.set(u,a())),n.onMountedFired=!0),s!=="on"&&n.onMountedFired===!0&&(o.forEach(a=>a()),o.clear(),i.forEach(({clear:a},u)=>a&&i.delete(u)),n.onMountedFired=!1)})},t.sdk.initializeApp=async s=>{if(t.contextConfig=s,t.stores.enabled.get()==="on")return{enabled:!0};t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(he.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(he.READY),{enabled:!!a}):(t.stores.status.setValue(he.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(he.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(he.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=s=>{t.stores.providerStreamId.setValue(s)},r()},Io=(t,e)=>{const{client:r,queryKey:n}=t.createPromiseClient(Ze.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s,a)=>{if(!s)return{};try{return(await r.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes}catch{return}},dedupeTime:1e3*60*60*24,refetchInterval:0})},Oo=(t,{web:e,mobile:r})=>{const{client:n}=t.createPromiseClient(ci.LinksClient,{method:"generate"});return n.generate({web:e,mobile:r})},Qr=(t,e)=>{const r=new URLSearchParams(t);for(const[n,i]of Object.entries(e))r.append(n,i);return r.toString()},ko=(t,e,r,n)=>{const i=H({});return re.onMount(i,()=>Io(t,[e,r]).subscribe(async({data:a,loading:u})=>{const d=a===void 0&&u===!1?"https://streamlayer.io":a?.url,c=n.get()||"",f=e.get()||"",p=r.get()||"",w={[kt]:c,[On]:f,[kn]:p};if(!u&&d){i.setKey("loading",!0);let E=window.location.search,g=window.location.hash;E&&g||g?E=`?${Qr(E,w)}`:g=`#${Qr("",w)}`;const m=window.location.origin+window.location.pathname+E+g;try{const T=await Oo(t,{web:m,mobile:d});i.set({data:T.data?.link,loading:!1})}catch{i.set({loading:!1,error:"Failed to generate short link",data:void 0})}}else i.setKey("loading",!0)})),{$store:i,fetch}};var B;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(B||(B={}));const _o=(t,e,r,n)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&r.add({type:me.ONBOARDING,id:o,action:t.openFeature,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:S.QuestionType.UNSET,onboarding:{...i,instantOpen:!n.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ct=(t,e,r,n,i,o,s,a)=>{try{const u=e.userId.get(),d=e.organizationId.get(),c=e.slStreamId.get();if(!u||!d||!c)return;const f=i.getOnboardingStatus({userId:u,organizationId:d,eventId:c});if(f===B.Completed||a?.skipOnboarding){t.set(B.Completed);for(const m of o)m();a?.skipOnboarding&&f!==B.Completed&&(i.saveOnboardingStatus({organizationId:d,userId:u,eventId:c},B.Completed),In(s,c));return}const p=e.moderation.getStore().value?.data,w=r.featureSettings.get().inplayGame;if(p===void 0||w===void 0)return;const E=p?.options?.onboardingEnabled,g=w?.titleCard?.optIn;E?g?t.set(B.Required):t.set(B.Optional):(g?t.set(B.Unavailable):t.set(B.Disabled),n.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},jr=(t,e,r,n,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=Q(B.Unset);a.subscribe(c=>{c!==B.Unset&&(c===B.Optional||c===B.Required?o===!1&&(_o(t,e,n,s),o=!0):t.onboardingProcessed.set(!0),c===B.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==B.Completed&&(u.push(e.userId.listen(c=>{c&&ct(a,e,t,n,s,u,r,i)})),u.push(e.moderation.listen(c=>{c.data&&ct(a,e,t,n,s,u,r,i)})),u.push(t.featureSettings.listen(c=>{c&&ct(a,e,t,n,s,u,r,i)}))),ct(a,e,t,n,s,u,r,i),{$store:a,submitInplay:async()=>{const c=e.slStreamId.get();if(c){await In(r,c),a.set(B.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:c},B.Completed),q.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const f=e.getCurrentSessionId({prefix:"onboarding"});n.close(f)}}}},Co=(t,e,r,n)=>{const i=H(void 0),o=En(n),s=async()=>{const u=t.get(),d=e.get(),c=r?r.getStore().get().data?.map(w=>w.slId):[];if(!c||!u||!d)return;const f={eventId:u,userId:d,usersIds:[...c,d]},p=await o(f);i.set(p.data?.attributes)},a=()=>{s()};return re.onMount(i,()=>{a();const u=t.listen(s),d=r?.listen(s),c=e.listen(s);return()=>{u(),d?.(),c()}}),{$store:i,invalidate:a}},Po=async(t,e,r,n,i)=>{const o=En(i),s=t.get(),a=e.get(),u=r?.getStore().get().data?.map(p=>p.slId)||[],d={eventId:s,userId:n,usersIds:[...u,a]};return(await o(d)).data?.attributes?.summary},Lo=new Set([S.QuestionType.POLL,S.QuestionType.PREDICTION,S.QuestionType.TRIVIA]);class No extends wn{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,r,n){if(super(e,r),this.background=new oo(n),this.advertisement=this.background.advertisement,this.onQuestionActivate=n.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=Q(!n.sdk.withAuth),this.leaderboardId=new J(Q(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=n.notifications,this.transport=n.transport,this.closeFeature=(i=!0)=>n.sdk.closeFeature(i),this.openFeature=()=>n.sdk.openFeature(V.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=ko(this.transport,this.background.slStreamId,n.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=Co(this.background.slStreamId,this.background.userId,this.friends,this.transport),!n.sdk.options.get().hideFriends){this.friends=new te(ji(this.background.userId,n.transport),"gamification:friends"),this.openedUser=Q(void 0);const i=this.leaderboardList=fo(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.skipOnboarding=!!n.sdk.options.get().skipOnboarding,this.onboardingStatus=jr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding}),n.sdk.options.get().skipOnboarding||(this.onboardingStatus=jr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding})),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==B.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=Q(!1),this.cancels.add(n.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{n.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),n.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Se.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Se.ALLOWED);else{const e=this.onboardingStatus.$store.get(),r=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,n=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===B.Completed,o=!r||i||n!==!0;this.background.interactiveAllowed.set(o?Se.ALLOWED:Se.DISALLOWED)}};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const r=e.data?.attributes?.question,n=e.data?.attributes?.feedItem;if(!r||!n?.attributes)return;const{status:i,type:o,id:s,answers:a}=r;if(i===S.QuestionStatus.RESOLVED&&o===S.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),d=[...this.feedList.getValues().data||[]],c=d.findIndex(K=>K.id===s),f=d[c];let p=f?.attributes?.attributes?.value?.answerId;const w=qe(s,this.transport),E=w.subscribe(()=>{});await w.get().promise;let g=w.get().data;g||(g=await nr(s,this.transport)),E(),window.requestAnimationFrame(()=>{w.invalidate()}),p||(p=g?.answers.find(({youVoted:K})=>K)?.id);const m=a.find(({correct:K})=>K),T=p?a.find(({id:K})=>K===p):void 0,D=!!T?.correct;if(f&&d[c]?.attributes?.attributes.case==="question"){try{d[c].attributes.attributes.value.answerId=p,d[c].attributes.attributes.value.openForVoting=!1,p&&(d[c].attributes.attributes.value.status=D?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(d)}if(!T||!m)return;this.openedQuestionId.get()?.questionId!==r.id&&this.notifications.add({type:me.QUESTION_RESOLVED,action:()=>this.openQuestion(r.id,n),close:()=>this.closeQuestion(s),autoHideDuration:D?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:S.QuestionType.PREDICTION,question:{title:D?`Congratulations! You answered correctly! You won ${m.points} pts!`:`Better luck next time! Correct: ${m?.text}!`,votedAnswer:{title:T?.text,points:T?.points},correctAnswerTitle:m?.text,correct:!!D,predictionResult:i===S.QuestionStatus.RESOLVED,questionTitle:r?.subject}}}),this.userSummary.invalidate()}})),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-questions-list",e=>{const r=[...this.feedList.getStore().value?.data||[]],n=e.data?.attributes?.feedItem,i=r.findIndex(o=>o.id===n?.id);if(n?.attributes&&n.attributes.attributes.case!=="promotion"&&!(n.attributes.status!==S.QuestionStatus.ACTIVE&&n.attributes.status!==S.QuestionStatus.RESOLVED)){if(i!==-1)if(n.attributes.attributes.case==="question"&&r[i].attributes?.attributes.case==="question"){const o=r[i];o.attributes&&(r[i]={...r[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...n.attributes.attributes.value,answerId:o.attributes.attributes.value.answerId,status:o.attributes.attributes.value.status,openForVoting:o.attributes.attributes.value.openForVoting}}}})}else{const o=r[i];o.attributes&&n.attributes&&(r[i]={...r[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...n.attributes.attributes.value}}}})}i===-1&&(r.unshift(n),q.emit("poll",{action:"received",payload:{questionId:n.id,questionType:n.attributes?.type}})),this.feedList.getStore().mutate(r)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,r)=>{try{await $r(this.transport,{questionId:e,answerId:r})}catch(o){if(o.message===je.ALREADY_VOTED){const s=qe(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const n={...this.betPack.getValues().data},i=n?.[e];i&&(q.emit("poll",{action:"voted",payload:{questionId:e,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===r?{...o,youVoted:!0}:o),this.betPack.getStore().mutate(n))};submitAnswer=async(e,r)=>{const n=qe(e,this.transport),i=n.subscribe(()=>{}),o={...n.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(f=>f.id===e),d=a[u],c=d?.attributes?.attributes.case==="question"&&d.attributes.attributes.value;if(c){q.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=n.get().data;if(i(),f){const p=f.answers.find(m=>m.correct===!0),w=f.answers.findIndex(m=>m.id===r),E=f.answers[w],g=f.answers.every(({percentageDecimal:m},T)=>m===o?.answers[T].percentageDecimal);a[u].attributes.attributes.value.answerId=r,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=E?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===r?ot.PickHistoryStatus.WON:ot.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[w].correct=p?.id===r,f.answers[w].youVoted=!0,g&&f.answers.forEach(m=>{m.percentageDecimal=0}),p?.id===r&&(f.answers[w].pointsEarned=f.status===S.QuestionStatus.RESOLVED?0:p.points),n.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await $r(this.transport,{questionId:e,answerId:r}),s()}catch(a){if(a.message===je.ALREADY_VOTED){this.userSummary.invalidate();const u=n.subscribe(()=>{});n.invalidate(),u()}throw a}};openQuestion=(e,r)=>{if(!e)return()=>{};const n=r?.openedFrom==="bet-pack";n&&this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=r?.attributes?.type;!i&&!n&&(i=(this.feedList.getStore().value?.data||[]).find(a=>a.id===e)?.attributes?.type);const o={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return this.storage.isQuestionOpened(o,e)||(q.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,questionOpenedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}}),this.storage.saveQuestionOpened(o,e)),n||this.openFeature(),this.background.openQuestion(e,r?{...r,openedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}:void 0)};getFeedItem=e=>Ki(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const r=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!r){this.openedUser?.set(r);return}if(r.summaryLoaded){this.openedUser?.set(r);return}const n={...r};try{const i=await Po(this.background.slStreamId,this.background.userId,this.friends,e,this.transport);i?.inTop!==void 0&&(this.leaderboardList?.$store.setKey("data",this.leaderboardList.$store.get().data?.map(o=>(o.userId===e&&(o.inTop=i.inTop),o))),n.inTop=i.inTop)}catch(i){console.error(i)}this.openedUser.set(n)};closeUser=()=>{this.openedUser?.set(void 0)};showInApp=e=>{const r=this.onboardingStatus.$store.get();if(e&&e.data&&r&&r!==B.Unset&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==S.SilenceSetting.ON&&e.data.question.status===S.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Lo.has(e.data.question.type))this.isInteractiveAllowed&&e.data.question.notification!==void 0&&this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*60,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),emitEvent:!0,data:{questionId:e.data.question.id,questionType:e.data.question.type,question:{title:e.data.question.notification.title},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}});else if(e.data.question.type===S.QuestionType.FACTOID){const n=e.data.question.options?.options.value,i=e.data.question.notification?.title||e.data.question.subject||"",o=e.data.question.notification?.body||n.body,s={heading:i,body:o,imageMode:n?.imageMode,image:n?.image,video:{id:n?.video?.id||"",url:n?.video?.url||"",thumbnailUrl:n?.video?.thumbnailUrl||""},webLink:{label:"",url:""}};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e?.data?.question?.id,e?.data?.feedItem),close:()=>this.closeQuestion(e?.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,insight:s,inApp:{useMediaFromContent:n?.useAsNotification===S.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}else if(e.data.question.type===S.QuestionType.TWEET&&e.data.question.notification!==void 0){const n=e.data.question.options?.options.value,i={image:"",video:""};if(n.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const s=n.tweetMeta.tweet.meta.extendedEntities.media;if(s){const a=s.find(({type:u})=>u==="photo")||s[0];i.image=a.mediaUrlHttps,a.type==="video"&&(i.video=a.url)}}const o={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:n?.tweetMeta?.account||"",accountVerified:!!n?.tweetMeta?.accountVerified,tweet:n?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:i};this.notifications.add({type:me.QUESTION,action:()=>this.openQuestion(e.data?.question?.id,e.data?.feedItem),close:()=>this.closeQuestion(e.data?.question?.id),autoHideDuration:1e3*120,emitEvent:!0,id:this.background.getCurrentSessionId({prefix:"notification",entity:e.data.question.id}),data:{questionId:e.data.question.id,questionType:e.data.question.type,tweet:o,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const Fo={[V.SdkOverlayType.GAMES]:!0};class Do extends wn{constructor(e,r){super(e,r)}}const Ro=(t,e,r)=>t.type===V.SdkOverlayType.GAMES?new No(t,e,r):new Do(t,e),Vo=(t,e,r)=>{t.features=new Map,t.sdk.featuresList=new J(Q(new Set),"features-list"),t.activeFeature=new J(Q(V.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=n=>t.features.get(n),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=n=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(n)})},t.sdk.closeFeature=(n=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(V.SdkOverlayType.UNSET),n&&i){t.features.delete(i);const o=t.sdk.featuresList.getValue();o&&o.delete(i),t.sdk.featuresList.setValue(o)}},t.initFeature=(n,i=pe.ORGANIZATION)=>{if(n.type in Fo&&!t.features.has(n.type)){const o=Ro(n,i,t);t.features.set(n.type,o);let s=t.sdk.featuresList.getValue();s?s.add(n.type):s=new Set([n.type]),t.sdk.featuresList.setValue(new Set(s))}},t.updateFeature=(n,i)=>{t.features.get(n.type)?.update(n,i)},t.destroyFeature=n=>{t.features.delete(n.type);const i=t.sdk.featuresList.getValue();i&&i.delete(n.type),t.sdk.featuresList.setValue(new Set(i))},t.reinitializeFeatures=async()=>{const n=await t.stores.organizationSettings.getValue();t.features.clear(),t.sdk.featuresList.setValue(new Set);for(const i of n?.overlays||[])t.initFeature(i,pe.ORGANIZATION)},t.stores.providerStreamId.listen(n=>{n||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const n=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===pe.ORGANIZATION))for(const a of s.overlays)a.sdkEnable===!0&&(t.features.has(a.type)?t.updateFeature(a,o):t.initFeature(a,o))},i={organizationSettings:o=>{if(o.data)try{n(pe.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{n(pe.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},r()};class $o{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="invitation")switch(n.slEventBus.action){case"sent":this.sent(n.slEventBus.payload);break}};return q.listen(r)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:st.InvitationCategory.GAMES,from:st.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:st.InvitationCategory.GAMES,from:e||st.InvitationFrom.UNSET})}}class Bo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="interactions")switch(n.slEventBus.action){case"tap":this.tap();break;case"scroll":this.scroll();break}};return q.listen(r)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Fr.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:Fr.InteractionActionType.SCROLL})}}const Mo={[S.PromotionType.UNSET]:v.TopicSubType.UNSET,[S.PromotionType.INGAME_IAB21]:v.TopicSubType.PROMOTION_INGAME_IAB21,[S.PromotionType.INGAME_IAB11_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[S.PromotionType.INGAME_IAB11]:v.TopicSubType.PROMOTION_INGAME_IAB11,[S.PromotionType.INGAME_IAB21_LBAR]:v.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[S.PromotionType.INGAME_IAB61]:v.TopicSubType.PROMOTION_INGAME_IAB61,[S.PromotionType.EXTERNAL_AD]:v.TopicSubType.PROMOTION_GAM,[S.PromotionType.VIDEO_SIDE_BY_SIDE]:v.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[S.PromotionType.PICTURE_IN_PICTURE]:v.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[S.PromotionType.SHOP_LBAR]:v.TopicSubType.PROMOTION_SHOP_LBAR,[S.PromotionType.SHOP_OVERLAY]:v.TopicSubType.PROMOTION_SHOP_OVERLAY,[S.PromotionType.SHOP_SIDEBAR]:v.TopicSubType.PROMOTION_SHOP_SIDEBAR},ir=t=>t?Mo[t]:v.TopicSubType.UNSET;class qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(!n.slEventBus?.skipAnalytics&&n.slEventBus?.type==="advertisement"){const i=ir(n.slEventBus.payload.type);switch(n.slEventBus.action){case"videoPlay":this.videoPlay(n.slEventBus.payload,{topicSubType:i});break;case"buttonSelect":this.buttonSelect(n.slEventBus.payload,{topicSubType:i});break;case"bannerSelect":this.bannerSelect(n.slEventBus.payload,{topicSubType:i});break;case"received":this.received(n.slEventBus.payload,{topicSubType:i});break;case"opened":this.opened(n.slEventBus.payload,{topicSubType:i});break;case"viewed":this.viewed(n.slEventBus.payload,{topicSubType:i});break}}};return q.listen(r)})}received=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:r},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:r==="notification"?v.PollOpenedFrom.IN_APP:v.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:v.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_VIDEO_PLAYED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:v.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BUTTON_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:v.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:v.Kind.AD_BANNER_NAVIGATED,topicType:v.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const Je={[S.QuestionType.UNSET]:v.TopicType.UNSET,[S.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[S.QuestionType.POLL]:v.TopicType.POLLS_POLL,[S.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[S.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[S.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[S.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};S.QuestionType.UNSET+"",ee.NotificationKind.UNSET,S.QuestionType.FACTOID+"",ee.NotificationKind.POLLS,S.QuestionType.POLL+"",ee.NotificationKind.POLLS,S.QuestionType.PREDICTION+"",ee.NotificationKind.POLLS,S.QuestionType.PROMOTION+"",ee.NotificationKind.POLLS,S.QuestionType.TRIVIA+"",ee.NotificationKind.POLLS,S.QuestionType.TWEET+"",ee.NotificationKind.POLLS;const Uo={[V.SdkOverlayType.UNSET]:v.Category.UNSET,[V.SdkOverlayType.INPLAY]:v.Category.INPLAY,[V.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[V.SdkOverlayType.STATISTICS]:v.Category.STATS,[V.SdkOverlayType.BETTING]:v.Category.BETTING,[V.SdkOverlayType.TWITTER]:v.Category.TWITTER,[V.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[V.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[V.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[V.SdkOverlayType.TICKETS]:v.Category.TICKETS,[V.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[V.SdkOverlayType.PROFILE]:v.Category.PROFILE,[V.SdkOverlayType.GAMES]:v.Category.POLLS,[V.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[V.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[V.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class Qo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="notification")switch(n.slEventBus.action){case"rendered":this.received(n.slEventBus.payload);break;case"opened":this.opened(n.slEventBus.payload);break}if(n.slEventBus?.type==="advertisement")switch(n.slEventBus.action){case"notification-received":this.received({questionId:n.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:ir(n.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:n.slEventBus.payload.id,questionType:S.QuestionType.PROMOTION,topicSubType:ir(n.slEventBus.payload.type)});break}};return q.listen(r)})}received=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:r?Je[r]:v.TopicType.UNSET,topicSubType:n},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})};opened=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:r?Je[r]:v.TopicType.UNSET,topicSubType:n},notificationKind:ee.NotificationKind.POLLS,notificationType:ee.NotificationType.IN_APP})}}class jo{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="poll")switch(n.slEventBus.action){case"voted":this.voted(n.slEventBus.payload);break;case"navigated":this.navigated();break;case"onboardingPassed":this.onboardingPassed();break;case"received":this.received(n.slEventBus.payload);break;case"opened":this.opened(n.slEventBus.payload);break}};return q.listen(r)})}received=({questionId:e,questionType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_RECEIVED,topicId:e,topicType:r?Je[r]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};opened=({questionId:e,questionType:r,questionOpenedFrom:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_OPENED,topicId:e,topicType:r?Je[r]:v.TopicType.UNSET},pollOpenedFrom:n==="list"?v.PollOpenedFrom.PICK_HISTORY:v.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_VOTE,topicId:e,topicType:r?Je[r]:v.TopicType.UNSET},pollOpenedFrom:v.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.GAMES_JOINED},pollOpenedFrom:v.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.POLLS_NAVIGATED},pollOpenedFrom:v.PollOpenedFrom.UNSET})}}const xo=({transport:t,$commonStore:e})=>{let r;const n=Q(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(gn.AnalyticsService,{method:"send",params:[n]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(w){ye.error(w,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{ye.debug("mounted heartbeat"),r=a.subscribe(()=>{})},d=()=>{ye.debug("enabled heartbeat"),n.set(!0),a.lc===0&&u()},c=()=>{ye.debug("disabled heartbeat"),n.set(!1)};return{enable:d,disable:c,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),r?.(),r=void 0,c()}}},ye=ce("analytics");class Go{commonStore;notifications;polls;invitation;interactions;advertisement;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ie(H({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=xo({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new Qo(this),this.polls=new jo(this),this.invitation=new $o(this),this.interactions=new Bo(this),this.advertisement=new qo(this);const{client:r}=e.analyticsTransport.createPromiseClient(gn.AnalyticsService,{method:"send"});this.analyticsClient=r}connect=()=>{this.writeCommon("sessionId",Zt.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,r)=>{r&&this.analyticsClient.unary({message:{case:e,value:r}}).then(()=>{ye.trace("send analytics success",e,r)}).catch(n=>{ye.error(n,"send analytics failed")})};writeCommon=(e,r)=>{this.commonStore.setValue(e,r)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(r=>{this.writeCommon("eventId",r)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(r=>{r&&this.writeCommon("category",Uo[r]),r!==V.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Zt.v4()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const r=window.matchMedia("(orientation: portrait)"),n=i=>{this.writeCommon("screenOrientation",i.matches?v.ScreenOrientation.PORTRAIT:v.ScreenOrientation.LANDSCAPE)};return r.addEventListener("change",n),()=>{r.removeEventListener("change",n)}}),this.onConnect(()=>e.deepLink.$store.subscribe(r=>{r?.handled&&this.invitation.accepted()}))}}const Ko=(t,e,r)=>{t.analytics=new Go(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),r()};var gr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var mr={exports:{}},br={exports:{}};function Ho(t){var e=new t,r=e;function n(){var o=e;return o.next?e=o.next:(e=new t,r=e),o.next=null,o}function i(o){r.next=o,r=o}return{get:n,release:i}}var Wo=Ho,Yo=Wo;function _n(t,e,r){if(typeof t=="function"&&(r=e,e=t,t=null),!(r>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var n=Yo(Jo),i=null,o=null,s=0,a=null,u={push:g,drain:Y,saturated:Y,pause:c,paused:!1,get concurrency(){return r},set concurrency(N){if(!(N>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=N,!u.paused)for(;i&&s<r;)s++,T()},running:d,resume:w,idle:E,length:f,getQueue:p,unshift:m,empty:Y,kill:D,killAndDrain:K,error:X};return u;function d(){return s}function c(){u.paused=!0}function f(){for(var N=i,$=0;N;)N=N.next,$++;return $}function p(){for(var N=i,$=[];N;)$.push(N.value),N=N.next;return $}function w(){if(u.paused){if(u.paused=!1,i===null){s++,T();return}for(;i&&s<r;)s++,T()}}function E(){return s===0&&u.length()===0}function g(N,$){var _=n.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=r||u.paused?o?(o.next=_,o=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function m(N,$){var _=n.get();_.context=t,_.release=T,_.value=N,_.callback=$||Y,_.errorHandler=a,s>=r||u.paused?i?(_.next=i,i=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function T(N){N&&n.release(N);var $=i;$&&s<=r?u.paused?s--:(o===i&&(o=null),i=$.next,$.next=null,e.call(t,$.value,$.worked),o===null&&u.empty()):--s===0&&u.drain()}function D(){i=null,o=null,u.drain=Y}function K(){i=null,o=null,u.drain(),u.drain=Y}function X(N){a=N}}function Y(){}function Jo(){this.value=null,this.callback=Y,this.next=null,this.release=Y,this.context=null,this.errorHandler=null;var t=this;this.worked=function(r,n){var i=t.callback,o=t.errorHandler,s=t.value;t.value=null,t.callback=Y,t.errorHandler&&o(r,s),i.call(t.context,r,n),t.release(t)}}function Xo(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(c,f){e.call(this,c).then(function(p){f(null,p)},f)}var i=_n(t,n,r),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=d,i;function a(c){var f=new Promise(function(p,w){o(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function u(c){var f=new Promise(function(p,w){s(c,function(E,g){if(E){w(E);return}p(g)})});return f.catch(Y),f}function d(){if(i.idle())return new Promise(function(p){p()});var c=i.drain,f=new Promise(function(p){i.drain=function(){c(),p()}});return f}}br.exports=_n;br.exports.promise=Xo;var Cn=br.exports,vr={exports:{}},Ue=typeof Reflect=="object"?Reflect:null,xr=Ue&&typeof Ue.apply=="function"?Ue.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},lt;Ue&&typeof Ue.ownKeys=="function"?lt=Ue.ownKeys:Object.getOwnPropertySymbols?lt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:lt=function(e){return Object.getOwnPropertyNames(e)};function Zo(t){console&&console.warn&&console.warn(t)}var Pn=Number.isNaN||function(e){return e!==e};function F(){F.init.call(this)}vr.exports=F;vr.exports.once=ns;F.EventEmitter=F;F.prototype._events=void 0;F.prototype._eventsCount=0;F.prototype._maxListeners=void 0;var Gr=10;function _t(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(F,"defaultMaxListeners",{enumerable:!0,get:function(){return Gr},set:function(t){if(typeof t!="number"||t<0||Pn(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Gr=t}});F.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};F.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Pn(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function Ln(t){return t._maxListeners===void 0?F.defaultMaxListeners:t._maxListeners}F.prototype.getMaxListeners=function(){return Ln(this)};F.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var u=o[e];if(u===void 0)return!1;if(typeof u=="function")xr(u,this,r);else for(var d=u.length,c=Vn(u,d),n=0;n<d;++n)xr(c[n],this,r);return!0};function Nn(t,e,r,n){var i,o,s;if(_t(r),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]),s===void 0)s=o[e]=r,++t._eventsCount;else if(typeof s=="function"?s=o[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=Ln(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,Zo(a)}return t}F.prototype.addListener=function(e,r){return Nn(this,e,r,!1)};F.prototype.on=F.prototype.addListener;F.prototype.prependListener=function(e,r){return Nn(this,e,r,!0)};function es(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Fn(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=es.bind(n);return i.listener=r,n.wrapFn=i,i}F.prototype.once=function(e,r){return _t(r),this.on(e,Fn(this,e,r)),this};F.prototype.prependOnceListener=function(e,r){return _t(r),this.prependListener(e,Fn(this,e,r)),this};F.prototype.removeListener=function(e,r){var n,i,o,s,a;if(_t(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){a=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():ts(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};F.prototype.off=F.prototype.removeListener;F.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function Dn(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?rs(i):Vn(i,i.length)}F.prototype.listeners=function(e){return Dn(this,e,!0)};F.prototype.rawListeners=function(e){return Dn(this,e,!1)};F.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Rn.call(t,e)};F.prototype.listenerCount=Rn;function Rn(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}F.prototype.eventNames=function(){return this._eventsCount>0?lt(this._events):[]};function Vn(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function ts(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function rs(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function ns(t,e){return new Promise(function(r,n){function i(s){t.removeListener(e,o),n(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}$n(t,e,o,{once:!0}),e!=="error"&&is(t,i,{once:!0})})}function is(t,e,r){typeof t.on=="function"&&$n(t,"error",e,r)}function $n(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){n.once&&t.removeEventListener(e,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Bn=vr.exports,Ct={},Mn={},qn=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,r);if(s.value!==i||s.enumerable!==!0)return!1}return!0},os=qn,Pt=function(){return os()&&!!Symbol.toStringTag},ss=Error,as=EvalError,us=RangeError,cs=ReferenceError,Un=SyntaxError,Lt=TypeError,ds=URIError,Kr=typeof Symbol<"u"&&Symbol,ls=qn,fs=function(){return typeof Kr!="function"||typeof Symbol!="function"||typeof Kr("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ls()},Vt={__proto__:null,foo:{}},ps=Object,hs=function(){return{__proto__:Vt}.foo===Vt.foo&&!(Vt instanceof ps)},ys="Function.prototype.bind called on incompatible ",gs=Object.prototype.toString,ms=Math.max,bs="[object Function]",zr=function(e,r){for(var n=[],i=0;i<e.length;i+=1)n[i]=e[i];for(var o=0;o<r.length;o+=1)n[o+e.length]=r[o];return n},vs=function(e,r){for(var n=[],i=r,o=0;i<e.length;i+=1,o+=1)n[o]=e[i];return n},Ss=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r},ws=function(e){var r=this;if(typeof r!="function"||gs.apply(r)!==bs)throw new TypeError(ys+r);for(var n=vs(arguments,1),i,o=function(){if(this instanceof i){var c=r.apply(this,zr(n,arguments));return Object(c)===c?c:this}return r.apply(e,zr(n,arguments))},s=ms(0,r.length-n.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Ss(a,",")+"){ return binder.apply(this,arguments); }")(o),r.prototype){var d=function(){};d.prototype=r.prototype,i.prototype=new d,d.prototype=null}return i},Ts=ws,Sr=Function.prototype.bind||Ts,Es=Function.prototype.call,As=Object.prototype.hasOwnProperty,Is=Sr,Os=Is.call(Es,As),k,ks=ss,_s=as,Cs=us,Ps=cs,xe=Un,Qe=Lt,Ls=ds,Qn=Function,$t=function(t){try{return Qn('"use strict"; return ('+t+").constructor;")()}catch{}},Oe=Object.getOwnPropertyDescriptor;if(Oe)try{Oe({},"")}catch{Oe=null}var Bt=function(){throw new Qe},Ns=Oe?function(){try{return arguments.callee,Bt}catch{try{return Oe(arguments,"callee").get}catch{return Bt}}}():Bt,De=fs(),Fs=hs(),j=Object.getPrototypeOf||(Fs?function(t){return t.__proto__}:null),Ve={},Ds=typeof Uint8Array>"u"||!j?k:j(Uint8Array),ke={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?k:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?k:ArrayBuffer,"%ArrayIteratorPrototype%":De&&j?j([][Symbol.iterator]()):k,"%AsyncFromSyncIteratorPrototype%":k,"%AsyncFunction%":Ve,"%AsyncGenerator%":Ve,"%AsyncGeneratorFunction%":Ve,"%AsyncIteratorPrototype%":Ve,"%Atomics%":typeof Atomics>"u"?k:Atomics,"%BigInt%":typeof BigInt>"u"?k:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?k:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?k:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?k:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":ks,"%eval%":eval,"%EvalError%":_s,"%Float32Array%":typeof Float32Array>"u"?k:Float32Array,"%Float64Array%":typeof Float64Array>"u"?k:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?k:FinalizationRegistry,"%Function%":Qn,"%GeneratorFunction%":Ve,"%Int8Array%":typeof Int8Array>"u"?k:Int8Array,"%Int16Array%":typeof Int16Array>"u"?k:Int16Array,"%Int32Array%":typeof Int32Array>"u"?k:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":De&&j?j(j([][Symbol.iterator]())):k,"%JSON%":typeof JSON=="object"?JSON:k,"%Map%":typeof Map>"u"?k:Map,"%MapIteratorPrototype%":typeof Map>"u"||!De||!j?k:j(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?k:Promise,"%Proxy%":typeof Proxy>"u"?k:Proxy,"%RangeError%":Cs,"%ReferenceError%":Ps,"%Reflect%":typeof Reflect>"u"?k:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?k:Set,"%SetIteratorPrototype%":typeof Set>"u"||!De||!j?k:j(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?k:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":De&&j?j(""[Symbol.iterator]()):k,"%Symbol%":De?Symbol:k,"%SyntaxError%":xe,"%ThrowTypeError%":Ns,"%TypedArray%":Ds,"%TypeError%":Qe,"%Uint8Array%":typeof Uint8Array>"u"?k:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?k:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?k:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?k:Uint32Array,"%URIError%":Ls,"%WeakMap%":typeof WeakMap>"u"?k:WeakMap,"%WeakRef%":typeof WeakRef>"u"?k:WeakRef,"%WeakSet%":typeof WeakSet>"u"?k:WeakSet};if(j)try{null.error}catch(t){var Rs=j(j(t));ke["%Error.prototype%"]=Rs}var Vs=function t(e){var r;if(e==="%AsyncFunction%")r=$t("async function () {}");else if(e==="%GeneratorFunction%")r=$t("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=$t("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&j&&(r=j(i.prototype))}return ke[e]=r,r},Hr={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},et=Sr,vt=Os,$s=et.call(Function.call,Array.prototype.concat),Bs=et.call(Function.apply,Array.prototype.splice),Wr=et.call(Function.call,String.prototype.replace),St=et.call(Function.call,String.prototype.slice),Ms=et.call(Function.call,RegExp.prototype.exec),qs=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Us=/\\(\\)?/g,Qs=function(e){var r=St(e,0,1),n=St(e,-1);if(r==="%"&&n!=="%")throw new xe("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new xe("invalid intrinsic syntax, expected opening `%`");var i=[];return Wr(e,qs,function(o,s,a,u){i[i.length]=a?Wr(u,Us,"$1"):s||o}),i},js=function(e,r){var n=e,i;if(vt(Hr,n)&&(i=Hr[n],n="%"+i[0]+"%"),vt(ke,n)){var o=ke[n];if(o===Ve&&(o=Vs(n)),typeof o>"u"&&!r)throw new Qe("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new xe("intrinsic "+e+" does not exist!")},tt=function(e,r){if(typeof e!="string"||e.length===0)throw new Qe("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Qe('"allowMissing" argument must be a boolean');if(Ms(/^%?[^%]*%?$/,e)===null)throw new xe("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=Qs(e),i=n.length>0?n[0]:"",o=js("%"+i+"%",r),s=o.name,a=o.value,u=!1,d=o.alias;d&&(i=d[0],Bs(n,$s([0,1],d)));for(var c=1,f=!0;c<n.length;c+=1){var p=n[c],w=St(p,0,1),E=St(p,-1);if((w==='"'||w==="'"||w==="`"||E==='"'||E==="'"||E==="`")&&w!==E)throw new xe("property names with quotes must have matching quotes");if((p==="constructor"||!f)&&(u=!0),i+="."+p,s="%"+i+"%",vt(ke,s))a=ke[s];else if(a!=null){if(!(p in a)){if(!r)throw new Qe("base intrinsic for "+e+" exists, but the property is not available.");return}if(Oe&&c+1>=n.length){var g=Oe(a,p);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?a=g.get:a=a[p]}else f=vt(a,p),a=a[p];f&&!u&&(ke[s]=a)}}return a},jn={exports:{}},Mt,Yr;function wr(){if(Yr)return Mt;Yr=1;var t=tt,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Mt=e,Mt}var xs=tt,ft=xs("%Object.getOwnPropertyDescriptor%",!0);if(ft)try{ft([],"length")}catch{ft=null}var Nt=ft,Jr=wr(),Gs=Un,Re=Lt,Xr=Nt,Ks=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Re("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Re("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Re("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Re("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Re("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Re("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,o=arguments.length>4?arguments[4]:null,s=arguments.length>5?arguments[5]:null,a=arguments.length>6?arguments[6]:!1,u=!!Xr&&Xr(e,r);if(Jr)Jr(e,r,{configurable:s===null&&u?u.configurable:!s,enumerable:i===null&&u?u.enumerable:!i,value:n,writable:o===null&&u?u.writable:!o});else if(a||!i&&!o&&!s)e[r]=n;else throw new Gs("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},or=wr(),xn=function(){return!!or};xn.hasArrayLengthDefineBug=function(){if(!or)return null;try{return or([],"length",{value:1}).length!==1}catch{return!0}};var zs=xn,Hs=tt,Zr=Ks,Ws=zs(),en=Nt,tn=Lt,Ys=Hs("%Math.floor%"),Js=function(e,r){if(typeof e!="function")throw new tn("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Ys(r)!==r)throw new tn("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&en){var s=en(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!n)&&(Ws?Zr(e,"length",r,!0,!0):Zr(e,"length",r)),e};(function(t){var e=Sr,r=tt,n=Js,i=Lt,o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||e.call(s,o),u=wr(),d=r("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var w=a(e,s,arguments);return n(w,1+d(0,p.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(jn);var Tr=jn.exports,Gn=tt,Kn=Tr,Xs=Kn(Gn("String.prototype.indexOf")),Er=function(e,r){var n=Gn(e,!!r);return typeof n=="function"&&Xs(e,".prototype.")>-1?Kn(n):n},Zs=Pt(),ea=Er,sr=ea("Object.prototype.toString"),Ft=function(e){return Zs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:sr(e)==="[object Arguments]"},zn=function(e){return Ft(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&sr(e)!=="[object Array]"&&sr(e.callee)==="[object Function]"},ta=function(){return Ft(arguments)}();Ft.isLegacyArguments=zn;var ra=ta?Ft:zn,na=Object.prototype.toString,ia=Function.prototype.toString,oa=/^\s*(?:function)?\*/,Hn=Pt(),qt=Object.getPrototypeOf,sa=function(){if(!Hn)return!1;try{return Function("return function*() {}")()}catch{}},Ut,aa=function(e){if(typeof e!="function")return!1;if(oa.test(ia.call(e)))return!0;if(!Hn){var r=na.call(e);return r==="[object GeneratorFunction]"}if(!qt)return!1;if(typeof Ut>"u"){var n=sa();Ut=n?qt(n):!1}return qt(e)===Ut},Wn=Function.prototype.toString,Be=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,ar,pt;if(typeof Be=="function"&&typeof Object.defineProperty=="function")try{ar=Object.defineProperty({},"length",{get:function(){throw pt}}),pt={},Be(function(){throw 42},null,ar)}catch(t){t!==pt&&(Be=null)}else Be=null;var ua=/^\s*class\b/,ur=function(e){try{var r=Wn.call(e);return ua.test(r)}catch{return!1}},Qt=function(e){try{return ur(e)?!1:(Wn.call(e),!0)}catch{return!1}},ht=Object.prototype.toString,ca="[object Object]",da="[object Function]",la="[object GeneratorFunction]",fa="[object HTMLAllCollection]",pa="[object HTML document.all class]",ha="[object HTMLCollection]",ya=typeof Symbol=="function"&&!!Symbol.toStringTag,ga=!(0 in[,]),cr=function(){return!1};if(typeof document=="object"){var ma=document.all;ht.call(ma)===ht.call(document.all)&&(cr=function(e){if((ga||!e)&&(typeof e>"u"||typeof e=="object"))try{var r=ht.call(e);return(r===fa||r===pa||r===ha||r===ca)&&e("")==null}catch{}return!1})}var ba=Be?function(e){if(cr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Be(e,null,ar)}catch(r){if(r!==pt)return!1}return!ur(e)&&Qt(e)}:function(e){if(cr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(ya)return Qt(e);if(ur(e))return!1;var r=ht.call(e);return r!==da&&r!==la&&!/^\[object HTML/.test(r)?!1:Qt(e)},va=ba,Sa=Object.prototype.toString,Yn=Object.prototype.hasOwnProperty,wa=function(e,r,n){for(var i=0,o=e.length;i<o;i++)Yn.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Ta=function(e,r,n){for(var i=0,o=e.length;i<o;i++)n==null?r(e.charAt(i),i,e):r.call(n,e.charAt(i),i,e)},Ea=function(e,r,n){for(var i in e)Yn.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Aa=function(e,r,n){if(!va(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=n),Sa.call(e)==="[object Array]"?wa(e,r,i):typeof e=="string"?Ta(e,r,i):Ea(e,r,i)},Jn=Aa,Ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],jt=Ia,Oa=typeof globalThis>"u"?gr:globalThis,Xn=function(){for(var e=[],r=0;r<jt.length;r++)typeof Oa[jt[r]]=="function"&&(e[e.length]=jt[r]);return e},wt=Jn,ka=Xn,rn=Tr,Ar=Er,yt=Nt,_a=Ar("Object.prototype.toString"),Zn=Pt(),nn=typeof globalThis>"u"?gr:globalThis,dr=ka(),Ir=Ar("String.prototype.slice"),xt=Object.getPrototypeOf,Ca=Ar("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},Tt={__proto__:null};Zn&&yt&&xt?wt(dr,function(t){var e=new nn[t];if(Symbol.toStringTag in e){var r=xt(e),n=yt(r,Symbol.toStringTag);if(!n){var i=xt(r);n=yt(i,Symbol.toStringTag)}Tt["$"+t]=rn(n.get)}}):wt(dr,function(t){var e=new nn[t],r=e.slice||e.set;r&&(Tt["$"+t]=rn(r))});var Pa=function(e){var r=!1;return wt(Tt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Ir(i,1))}catch{}}),r},La=function(e){var r=!1;return wt(Tt,function(n,i){if(!r)try{n(e),r=Ir(i,1)}catch{}}),r},Na=function(e){if(!e||typeof e!="object")return!1;if(!Zn){var r=Ir(_a(e),8,-1);return Ca(dr,r)>-1?r:r!=="Object"?!1:La(e)}return yt?Pa(e):null},Et=Jn,Fa=Xn,on=Tr,Or=Er,gt=Nt,Da=Or("Object.prototype.toString"),ei=Pt(),sn=typeof globalThis>"u"?gr:globalThis,lr=Fa(),kr=Or("String.prototype.slice"),Gt=Object.getPrototypeOf,Ra=Or("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},At={__proto__:null};ei&>&&Gt?Et(lr,function(t){var e=new sn[t];if(Symbol.toStringTag in e){var r=Gt(e),n=gt(r,Symbol.toStringTag);if(!n){var i=Gt(r);n=gt(i,Symbol.toStringTag)}At["$"+t]=on(n.get)}}):Et(lr,function(t){var e=new sn[t],r=e.slice||e.set;r&&(At["$"+t]=on(r))});var Va=function(e){var r=!1;return Et(At,function(n,i){if(!r)try{"$"+n(e)===i&&(r=kr(i,1))}catch{}}),r},$a=function(e){var r=!1;return Et(At,function(n,i){if(!r)try{n(e),r=kr(i,1)}catch{}}),r},Ba=function(e){if(!e||typeof e!="object")return!1;if(!ei){var r=kr(Da(e),8,-1);return Ra(lr,r)>-1?r:r!=="Object"?!1:$a(e)}return gt?Va(e):null},Ma=Ba,qa=function(e){return!!Ma(e)};(function(t){var e=ra,r=aa,n=Na,i=qa;function o(y){return y.call.bind(y)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),d=o(Number.prototype.valueOf),c=o(String.prototype.valueOf),f=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var w=o(Symbol.prototype.valueOf);function E(y,ai){if(typeof y!="object")return!1;try{return ai(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=i;function g(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=g;function m(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||h(y)}t.isArrayBufferView=m;function T(y){return n(y)==="Uint8Array"}t.isUint8Array=T;function D(y){return n(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=D;function K(y){return n(y)==="Uint16Array"}t.isUint16Array=K;function X(y){return n(y)==="Uint32Array"}t.isUint32Array=X;function N(y){return n(y)==="Int8Array"}t.isInt8Array=N;function $(y){return n(y)==="Int16Array"}t.isInt16Array=$;function _(y){return n(y)==="Int32Array"}t.isInt32Array=_;function ne(y){return n(y)==="Float32Array"}t.isFloat32Array=ne;function ie(y){return n(y)==="Float64Array"}t.isFloat64Array=ie;function _e(y){return n(y)==="BigInt64Array"}t.isBigInt64Array=_e;function we(y){return n(y)==="BigUint64Array"}t.isBigUint64Array=we;function de(y){return u(y)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Dt(y){return typeof Map>"u"?!1:de.working?de(y):y instanceof Map}t.isMap=Dt;function ve(y){return u(y)==="[object Set]"}ve.working=typeof Set<"u"&&ve(new Set);function He(y){return typeof Set>"u"?!1:ve.working?ve(y):y instanceof Set}t.isSet=He;function Ce(y){return u(y)==="[object WeakMap]"}Ce.working=typeof WeakMap<"u"&&Ce(new WeakMap);function Rt(y){return typeof WeakMap>"u"?!1:Ce.working?Ce(y):y instanceof WeakMap}t.isWeakMap=Rt;function Pe(y){return u(y)==="[object WeakSet]"}Pe.working=typeof WeakSet<"u"&&Pe(new WeakSet);function le(y){return Pe(y)}t.isWeakSet=le;function Le(y){return u(y)==="[object ArrayBuffer]"}Le.working=typeof ArrayBuffer<"u"&&Le(new ArrayBuffer);function rt(y){return typeof ArrayBuffer>"u"?!1:Le.working?Le(y):y instanceof ArrayBuffer}t.isArrayBuffer=rt;function l(y){return u(y)==="[object DataView]"}l.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&l(new DataView(new ArrayBuffer(1),0,1));function h(y){return typeof DataView>"u"?!1:l.working?l(y):y instanceof DataView}t.isDataView=h;var b=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function A(y){return u(y)==="[object SharedArrayBuffer]"}function P(y){return typeof b>"u"?!1:(typeof A.working>"u"&&(A.working=A(new b)),A.working?A(y):y instanceof b)}t.isSharedArrayBuffer=P;function L(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=L;function O(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=O;function C(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=C;function R(y){return u(y)==="[object Generator]"}t.isGeneratorObject=R;function z(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=z;function Te(y){return E(y,d)}t.isNumberObject=Te;function nt(y){return E(y,c)}t.isStringObject=nt;function Ne(y){return E(y,f)}t.isBooleanObject=Ne;function it(y){return s&&E(y,p)}t.isBigIntObject=it;function Pr(y){return a&&E(y,w)}t.isSymbolObject=Pr;function oi(y){return Te(y)||nt(y)||Ne(y)||it(y)||Pr(y)}t.isBoxedPrimitive=oi;function si(y){return typeof Uint8Array<"u"&&(rt(y)||P(y))}t.isAnyArrayBuffer=si,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})(Mn);var Ua=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},fr={exports:{}};typeof Object.create=="function"?fr.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:fr.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}};var Qa=fr.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(h){for(var b=Object.keys(h),A={},P=0;P<b.length;P++)A[b[P]]=Object.getOwnPropertyDescriptor(h,b[P]);return A},r=/%[sdj%]/g;t.format=function(l){if(!N(l)){for(var h=[],b=0;b<arguments.length;b++)h.push(s(arguments[b]));return h.join(" ")}for(var b=1,A=arguments,P=A.length,L=String(l).replace(r,function(C){if(C==="%%")return"%";if(b>=P)return C;switch(C){case"%s":return String(A[b++]);case"%d":return Number(A[b++]);case"%j":try{return JSON.stringify(A[b++])}catch{return"[Circular]"}default:return C}}),O=A[b];b<P;O=A[++b])D(O)||!ie(O)?L+=" "+O:L+=" "+s(O);return L},t.deprecate=function(l,h){if(typeof I<"u"&&I.noDeprecation===!0)return l;if(typeof I>"u")return function(){return t.deprecate(l,h).apply(this,arguments)};var b=!1;function A(){if(!b){if(I.throwDeprecation)throw new Error(h);I.traceDeprecation?console.trace(h):console.error(h),b=!0}return l.apply(this,arguments)}return A};var n={},i=/^$/;if(I.env.NODE_DEBUG){var o=I.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(l){if(l=l.toUpperCase(),!n[l])if(i.test(l)){var h=I.pid;n[l]=function(){var b=t.format.apply(t,arguments);console.error("%s %d: %s",l,h,b)}}else n[l]=function(){};return n[l]};function s(l,h){var b={seen:[],stylize:u};return arguments.length>=3&&(b.depth=arguments[2]),arguments.length>=4&&(b.colors=arguments[3]),T(h)?b.showHidden=h:h&&t._extend(b,h),_(b.showHidden)&&(b.showHidden=!1),_(b.depth)&&(b.depth=2),_(b.colors)&&(b.colors=!1),_(b.customInspect)&&(b.customInspect=!0),b.colors&&(b.stylize=a),c(b,l,b.depth)}t.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function a(l,h){var b=s.styles[h];return b?"\x1B["+s.colors[b][0]+"m"+l+"\x1B["+s.colors[b][1]+"m":l}function u(l,h){return l}function d(l){var h={};return l.forEach(function(b,A){h[b]=!0}),h}function c(l,h,b){if(l.customInspect&&h&&de(h.inspect)&&h.inspect!==t.inspect&&!(h.constructor&&h.constructor.prototype===h)){var A=h.inspect(b,l);return N(A)||(A=c(l,A,b)),A}var P=f(l,h);if(P)return P;var L=Object.keys(h),O=d(L);if(l.showHidden&&(L=Object.getOwnPropertyNames(h)),we(h)&&(L.indexOf("message")>=0||L.indexOf("description")>=0))return p(h);if(L.length===0){if(de(h)){var C=h.name?": "+h.name:"";return l.stylize("[Function"+C+"]","special")}if(ne(h))return l.stylize(RegExp.prototype.toString.call(h),"regexp");if(_e(h))return l.stylize(Date.prototype.toString.call(h),"date");if(we(h))return p(h)}var R="",z=!1,Te=["{","}"];if(m(h)&&(z=!0,Te=["[","]"]),de(h)){var nt=h.name?": "+h.name:"";R=" [Function"+nt+"]"}if(ne(h)&&(R=" "+RegExp.prototype.toString.call(h)),_e(h)&&(R=" "+Date.prototype.toUTCString.call(h)),we(h)&&(R=" "+p(h)),L.length===0&&(!z||h.length==0))return Te[0]+R+Te[1];if(b<0)return ne(h)?l.stylize(RegExp.prototype.toString.call(h),"regexp"):l.stylize("[Object]","special");l.seen.push(h);var Ne;return z?Ne=w(l,h,b,O,L):Ne=L.map(function(it){return E(l,h,b,O,it,z)}),l.seen.pop(),g(Ne,R,Te)}function f(l,h){if(_(h))return l.stylize("undefined","undefined");if(N(h)){var b="'"+JSON.stringify(h).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return l.stylize(b,"string")}if(X(h))return l.stylize(""+h,"number");if(T(h))return l.stylize(""+h,"boolean");if(D(h))return l.stylize("null","null")}function p(l){return"["+Error.prototype.toString.call(l)+"]"}function w(l,h,b,A,P){for(var L=[],O=0,C=h.length;O<C;++O)Pe(h,String(O))?L.push(E(l,h,b,A,String(O),!0)):L.push("");return P.forEach(function(R){R.match(/^\d+$/)||L.push(E(l,h,b,A,R,!0))}),L}function E(l,h,b,A,P,L){var O,C,R;if(R=Object.getOwnPropertyDescriptor(h,P)||{value:h[P]},R.get?R.set?C=l.stylize("[Getter/Setter]","special"):C=l.stylize("[Getter]","special"):R.set&&(C=l.stylize("[Setter]","special")),Pe(A,P)||(O="["+P+"]"),C||(l.seen.indexOf(R.value)<0?(D(b)?C=c(l,R.value,null):C=c(l,R.value,b-1),C.indexOf(`
|
|
3
3
|
`)>-1&&(L?C=C.split(`
|
|
4
4
|
`).map(function(z){return" "+z}).join(`
|
|
5
5
|
`).slice(2):C=`
|
|
6
6
|
`+C.split(`
|
|
7
7
|
`).map(function(z){return" "+z}).join(`
|
|
8
|
-
`))):C=
|
|
8
|
+
`))):C=l.stylize("[Circular]","special")),_(O)){if(L&&P.match(/^\d+$/))return C;O=JSON.stringify(""+P),O.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(O=O.slice(1,-1),O=l.stylize(O,"name")):(O=O.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),O=l.stylize(O,"string"))}return O+": "+C}function g(l,h,b){var A=l.reduce(function(P,L){return L.indexOf(`
|
|
9
9
|
`)>=0,P+L.replace(/\u001b\[\d\d?m/g,"").length+1},0);return A>60?b[0]+(h===""?"":h+`
|
|
10
|
-
`)+" "+
|
|
11
|
-
`)+" "+b[1]:b[0]+h+" "+
|
|
10
|
+
`)+" "+l.join(`,
|
|
11
|
+
`)+" "+b[1]:b[0]+h+" "+l.join(", ")+" "+b[1]}t.types=Mn;function m(l){return Array.isArray(l)}t.isArray=m;function T(l){return typeof l=="boolean"}t.isBoolean=T;function D(l){return l===null}t.isNull=D;function K(l){return l==null}t.isNullOrUndefined=K;function X(l){return typeof l=="number"}t.isNumber=X;function N(l){return typeof l=="string"}t.isString=N;function $(l){return typeof l=="symbol"}t.isSymbol=$;function _(l){return l===void 0}t.isUndefined=_;function ne(l){return ie(l)&&ve(l)==="[object RegExp]"}t.isRegExp=ne,t.types.isRegExp=ne;function ie(l){return typeof l=="object"&&l!==null}t.isObject=ie;function _e(l){return ie(l)&&ve(l)==="[object Date]"}t.isDate=_e,t.types.isDate=_e;function we(l){return ie(l)&&(ve(l)==="[object Error]"||l instanceof Error)}t.isError=we,t.types.isNativeError=we;function de(l){return typeof l=="function"}t.isFunction=de;function Dt(l){return l===null||typeof l=="boolean"||typeof l=="number"||typeof l=="string"||typeof l=="symbol"||typeof l>"u"}t.isPrimitive=Dt,t.isBuffer=Ua;function ve(l){return Object.prototype.toString.call(l)}function He(l){return l<10?"0"+l.toString(10):l.toString(10)}var Ce=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Rt(){var l=new Date,h=[He(l.getHours()),He(l.getMinutes()),He(l.getSeconds())].join(":");return[l.getDate(),Ce[l.getMonth()],h].join(" ")}t.log=function(){console.log("%s - %s",Rt(),t.format.apply(t,arguments))},t.inherits=Qa,t._extend=function(l,h){if(!h||!ie(h))return l;for(var b=Object.keys(h),A=b.length;A--;)l[b[A]]=h[b[A]];return l};function Pe(l,h){return Object.prototype.hasOwnProperty.call(l,h)}var le=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(h){if(typeof h!="function")throw new TypeError('The "original" argument must be of type Function');if(le&&h[le]){var b=h[le];if(typeof b!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(b,le,{value:b,enumerable:!1,writable:!1,configurable:!0}),b}function b(){for(var A,P,L=new Promise(function(R,z){A=R,P=z}),O=[],C=0;C<arguments.length;C++)O.push(arguments[C]);O.push(function(R,z){R?P(R):A(z)});try{h.apply(this,O)}catch(R){P(R)}return L}return Object.setPrototypeOf(b,Object.getPrototypeOf(h)),le&&Object.defineProperty(b,le,{value:b,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(b,e(h))},t.promisify.custom=le;function Le(l,h){if(!l){var b=new Error("Promise was rejected with a falsy value");b.reason=l,l=b}return h(l)}function rt(l){if(typeof l!="function")throw new TypeError('The "original" argument must be of type Function');function h(){for(var b=[],A=0;A<arguments.length;A++)b.push(arguments[A]);var P=b.pop();if(typeof P!="function")throw new TypeError("The last argument must be of type Function");var L=this,O=function(){return P.apply(L,arguments)};l.apply(this,b).then(function(C){I.nextTick(O.bind(null,null,C))},function(C){I.nextTick(Le.bind(null,C,O))})}return Object.setPrototypeOf(h,Object.getPrototypeOf(l)),Object.defineProperties(h,e(l)),h}t.callbackify=rt})(Ct);const{inherits:ja,format:Kt}=Ct;function Ee(t,e,r=Error){if(!t)throw new Error("Avvio error code must not be empty");if(!e)throw new Error("Avvio base error message must not be empty");function n(i,o,s){if(!new.target)return new n(i,o,s);Error.captureStackTrace(this,n),this.code=t,this.message=e,this.name="AvvioError",i&&o&&s?this.message=Kt(e,i,o,s):i&&o?this.message=Kt(e,i,o):i?this.message=Kt(e,i):this.message=e}return n.prototype[Symbol.toStringTag]="Error",n.prototype.toString=function(){return`${this.name} [${this.code}]: ${this.message}`},ja(n,r),n}var ti={createError:Ee,AVV_ERR_EXPOSE_ALREADY_DEFINED:Ee("AVV_ERR_EXPOSE_ALREADY_DEFINED","'%s' () is already defined, specify an expose option"),AVV_ERR_CALLBACK_NOT_FN:Ee("AVV_ERR_CALLBACK_NOT_FN","Callback for '%s' hook is not a function. Received: '%s'"),AVV_ERR_PLUGIN_NOT_VALID:Ee("AVV_ERR_PLUGIN_NOT_VALID","Plugin must be a function or a promise. Received: '%s'"),AVV_ERR_ROOT_PLG_BOOTED:Ee("AVV_ERR_PLUGIN_NOT_VALID","Root plugin has already booted"),AVV_ERR_PARENT_PLG_LOADED:Ee("AVV_ERR_PARENT_PLG_LOADED","Impossible to load '%s' plugin because the parent '%s' was already loaded"),AVV_ERR_READY_TIMEOUT:Ee("AVV_ERR_READY_TIMEOUT","Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise")},xa=function t(e,r,n){r===void 0&&(r=""),n||(n={});var i=function(u){var d={"│":"|","└":"`","├":"+","─":"-","┬":"-"};return n.unicode===!1?d[u]:u};typeof e=="string"&&(e={label:e});var o=e.nodes||[],s=(e.label||"").split(`
|
|
12
12
|
`),a=`
|
|
13
|
-
`+
|
|
14
|
-
`+o.map(function(u,
|
|
15
|
-
`).slice(0,2).map(n=>n.trim()).join(" -- ")}function nu(){const t={};return t.promise=new Promise((e,n)=>{t.resolve=e,t.reject=n}),t}function Ge(t,e,n,r,i){this.started=!1,this.func=e,this.opts=n,this.onFinish=null,this.parent=t,this.timeout=i===void 0?t._timeout:i,this.name=tu(e,n),this.isAfter=r,this.q=Ja(t,ru,1),this.q.pause(),this._error=null,this.loaded=!1,this._promise=null}Za(Ge,Xa);Ge.prototype.exec=function(t,e){const n=this.func;let r=!1;const i=this.name;if(this.parent._error&&!this.isAfter){x("skipping loading of plugin as parent errored and it is not an after",i),I.nextTick(e);return}if(this.isAfter)this.server=t;else try{this.server=this.parent.override(t,n,this.opts)}catch(u){return x("override errored",i),e(u)}this.opts=typeof this.opts=="function"?this.opts(this.server):this.opts,x("exec",i);let o;const s=u=>{if(r){x("loading complete",i);return}this._error=u,x(u?"exec errored":"exec completed",i),r=!0,o&&clearTimeout(o),e(u)};this.timeout>0&&(x("setting up timeout",i,this.timeout),o=setTimeout(function(){x("timed out",i),o=null;const u=new eu(i);u.fn=n,s(u)},this.timeout)),this.started=!0,this.emit("start",this.server?this.server.name:null,this.name,Date.now());const a=n(this.server,this.opts,s);a&&typeof a.then=="function"&&(x("exec: resolving promise",i),a.then(()=>I.nextTick(s),u=>I.nextTick(s,u)))};Ge.prototype.loadedSoFar=function(){if(this.loaded)return Promise.resolve();const t=()=>{this.server.after((n,r)=>{this._error=n,this.q.pause(),n?(x("rejecting promise",this.name,n),this._promise.reject(n)):(x("resolving promise",this.name),this._promise.resolve()),this._promise=null,I.nextTick(r,n)}),this.q.resume()};let e;return this._promise?e=Promise.resolve():(this._promise=nu(),e=this._promise.promise,this.server?t():this.on("start",t)),e};Ge.prototype.enqueue=function(t,e){x("enqueue",this.name,t.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.q.push(t,e)};Ge.prototype.finish=function(t,e){x("finish",this.name,t);const n=()=>{this.loaded||(x("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,e(t))};if(t){this._promise&&(this._promise.reject(t),this._promise=null),n();return}const r=()=>{if(x("check",this.name,this.q.length(),this.q.running(),this._promise),this.q.length()===0&&this.q.running()===0)if(this._promise){const i=()=>{x("wrap"),queueMicrotask(r)};this._promise.resolve(),this._promise.promise.then(i,i),this._promise=null}else n();else x("delayed",this.name),this.q.drain=()=>{x("drain",this.name),this.q.drain=iu,queueMicrotask(r)}};queueMicrotask(r),this.q.resume()};function ru(t,e){const n=this;I.nextTick(Pn.bind(n),t,e)}function Pn(t,e){if(typeof t.func.then=="function"){t.func.then(r=>{typeof r.default=="function"&&(r=r.default),t.func=r,Pn.call(this,t,e)},e);return}const n=this._current[0];this._current.unshift(t),t.exec(n&&n.server||this._server,r=>{t.finish(r,i=>{this._current.shift(),e(i)})})}function iu(){}Cn.exports=Ge;Cn.exports.loadPlugin=Pn;var ou=Cn.exports;const dr=_r,su=Vr.EventEmitter,au=Ct.inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:Yt,AVV_ERR_CALLBACK_NOT_FN:Ye,AVV_ERR_PLUGIN_NOT_VALID:uu,AVV_ERR_ROOT_PLG_BOOTED:cu,AVV_ERR_READY_TIMEOUT:du}=Zr,lu=za,yn=ou,Qe=ei("avvio"),It=Symbol("kAvvio"),Jt=Symbol("kThenifyDoNotWrap");function fu(t,e,n){const r=e.expose||{},i=r.use||"use",o=r.after||"after",s=r.ready||"ready",a=r.onClose||"onClose",u=r.close||"close";if(t[i])throw new Yt(i);if(t[o])throw new Yt(o);if(t[s])throw new Yt(s);t[i]=function(l,c){return n.use(l,c),this},Object.defineProperty(t,"then",{get:ti.bind(n)}),t[It]=!0,t[o]=function(l){return typeof l!="function"?n._loadRegistered():(n.after(Xt(l,this)),this)},t[s]=function(l){if(l&&typeof l!="function")throw new Ye(s,typeof l);return n.ready(l?Xt(l,this):void 0)},t[a]=function(l){if(typeof l!="function")throw new Ye(a,typeof l);return n.onClose(mu(l,this)),this},t[u]=function(l){if(l&&typeof l!="function")throw new Ye(u,typeof l);return l?(n.close(Xt(l,this)),this):n.close()}}function G(t,e,n){if(typeof t=="function"&&arguments.length===1&&(n=t,e={},t=null),typeof e=="function"&&(n=e,e={}),e=e||{},!(this instanceof G)){const r=new G(t,e,n);return t&&fu(t,e,r),r}e.autostart!==!1&&(e.autostart=!0),t=t||this,this._timeout=Number(e.timeout)||0,this._server=t,this._current=[],this._error=null,this._isOnCloseHandlerKey=Symbol("isOnCloseHandler"),this._lastUsed=null,this.setMaxListeners(0),n&&this.once("start",n),this.started=!1,this.booted=!1,this.pluginTree=new lu,this._readyQ=dr(this,ni,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=lr},this._closeQ=dr(this,gu,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=lr},this._doStart=null,this._root=new yn(this,pu.bind(this),e,!1,0),this._root.once("start",(r,i,o)=>{const s=this.pluginTree.start(null,i,o);this._root.once("loaded",(a,u,l)=>{this.pluginTree.stop(s,l)})}),yn.loadPlugin.call(this,this._root,r=>{Qe("root plugin ready");try{this.emit("preReady"),this._root=null}catch(i){r=r||this._error||i}if(r){if(this._error=r,this._readyQ.length()===0)throw r}else this.booted=!0;this._readyQ.resume()})}function pu(t,e,n){this._doStart=n,e.autostart&&this.start()}au(G,su);G.prototype.start=function(){return this.started=!0,I.nextTick(this._doStart),this};G.prototype.override=function(t,e,n){return t};function hu(t){if(t&&typeof t=="object"&&typeof t.default=="function"&&(t=t.default),!(t&&(typeof t=="function"||typeof t.then=="function")))throw new uu(typeof t);return t}G.prototype[It]=!0;G.prototype.use=function(t,e){return this._lastUsed=this._addPlugin(t,e,!1),this};G.prototype._loadRegistered=function(){const t=this._current[0];return!this.started&&!this.booted&&I.nextTick(()=>this._root.q.resume()),t?t.loadedSoFar():Promise.resolve()};Object.defineProperty(G.prototype,"then",{get:ti});G.prototype._addPlugin=function(t,e,n){if(t=hu(t),e=e||{},this.booted)throw new cu;const r=this._current[0],i=new yn(this,t,e,n);if(i.once("start",(o,s,a)=>{const u=this.pluginTree.start(r.name,s,a);i.once("loaded",(l,c,f)=>{this.pluginTree.stop(u,f)})}),r.loaded)throw new Error(i.name,r.name);return r.enqueue(i,o=>{o&&(this._error=o)}),i};G.prototype.after=function(t){if(!t)return this._loadRegistered();this._addPlugin(e.bind(this),{},!0);function e(n,r,i){ni.call(this,t,i)}return this};G.prototype.onClose=function(t){if(typeof t!="function")throw new Error("not a function");t[this._isOnCloseHandlerKey]=!0,this._closeQ.unshift(t,e.bind(this));function e(n){n&&(this._error=n)}return this};G.prototype.close=function(t){let e;if(t){if(typeof t!="function")throw new Ye("close",typeof t)}else e=new Promise(function(n,r){t=function(i){if(i)return r(i);n()}});return this.ready(()=>{this._error=null,this._closeQ.push(t),I.nextTick(this._closeQ.resume.bind(this._closeQ))}),e};G.prototype.ready=function(t){if(t){if(typeof t!="function")throw new Ye("ready",typeof t);this._readyQ.push(t),queueMicrotask(this.start.bind(this));return}return new Promise((e,n)=>{this._readyQ.push(i),this.start();const r=this._current[0].server;function i(o,s,a){o?n(o):e(r),I.nextTick(a)}})};G.prototype.prettyPrint=function(){return this.pluginTree.prittyPrint()};G.prototype.toJSON=function(){return this.pluginTree.toJSON()};function lr(){}function ti(){if(this.booted){Qe("thenify returning null because we are already booted");return}if(this[Jt]){this[Jt]=!1;return}return Qe("thenify"),(t,e)=>this._loadRegistered().then(()=>(this[Jt]=!0,t(this._server)),e)}function ni(t,e){const n=this._server,r=this._error;let i;if(this._error=null,t.length===0)this._error=r,i=t(),i&&!i[It]&&typeof i.then=="function"?i.then(()=>I.nextTick(e),o=>I.nextTick(e,o)):I.nextTick(e);else if(t.length===1)i=t(r),i&&!i[It]&&typeof i.then=="function"?i.then(()=>I.nextTick(e),o=>I.nextTick(e,o)):I.nextTick(e);else if(this._timeout===0){const o=s=>{this._error=s,e(this._error)};t.length===2?t(r,o):t(r,n,o)}else yu.call(this,t,r,n,e)}function yu(t,e,n,r){const i=t.name;Qe("setting up ready timeout",i,this._timeout);let o=setTimeout(()=>{Qe("timed out",i),o=null;const a=new du(i);a.fn=t,this._error=a,r(a)},this._timeout);t.length===2?t(e,s.bind(this)):t(e,n,s.bind(this));function s(a){o&&(clearTimeout(o),this._error=a,r(this._error))}}function gu(t,e){const n=this._server,r=t[this._isOnCloseHandlerKey];if(t.length===0||t.length===1){let i;r?i=t(n):i=t(this._error),i&&typeof i.then=="function"?(Qe("resolving close/onClose promise"),i.then(()=>I.nextTick(e),o=>I.nextTick(e,o))):I.nextTick(e)}else t.length===2?t(r?n:this._error,e):r?t(n,e):t(this._error,n,e)}function mu(t,e){return n.bind(e);function n(r,i){let o;t.length===0?(o=t(),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t.length===1?(o=t(this),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t(this,i)}}function Xt(t,e){return n.bind(e);function n(r,i){let o;t?t.length===0?(o=t(),o&&o.then?o.then(function(){I.nextTick(i,r)},i):I.nextTick(i,r)):t.length===1?(o=t(r),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t.length===2?t(r,i):t(r,this,i):I.nextTick(i)}}bn.exports=G;bn.exports.express=function(t){return G(t,{expose:{use:"load"}})};var bu=bn.exports;const vu=zo(bu);(function(){if(window.requestAnimationFrame&&window.cancelAnimationFrame)return;const t=["webkit","moz","ms","o"];for(const e of t)window.requestAnimationFrame=window.requestAnimationFrame||window[`${e}RequestAnimationFrame`],window.cancelAnimationFrame=window.cancelAnimationFrame||window[`${e}CancelAnimationFrame`]||window[`${e}CancelRequestAnimationFrame`];if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){let e=0;const n=!!(window.performance&&window.performance.now);window.requestAnimationFrame=function(r){const i=n?window.performance.now():new Date().getTime(),o=Math.max(0,16-(i-e)),s=window.setTimeout(function(){r(i+o)},o);return e=i+o,s},window.cancelAnimationFrame=clearTimeout}})();function Su(t,e=!0,n=!0,r={friendsTab:"enabled"}){const i=e?"https://grpc-sdk.streamlayer.io:443":"https://grpc-sdk.next.streamlayer.io:443",o=e?"https://grpc.streamlayer.io:443":"https://grpc.next.streamlayer.io:443",s=vu(Object.create({}),{autostart:!1});return s.use(Eo,{hideFriends:r.hideFriends,skipOnboarding:r.skipOnboarding,friendsTab:r.friendsTab,theme:r.theme,themeMode:r.themeMode}),s.use(go,{onDeepLinkHandled:r?.onDeepLinkHandled}),s.use(So,{videoPlayerController:r?.videoPlayerController}),s.use(To,{onContentActivate:r?.onContentActivate,withAd:r?.withAd,withAdNotification:r?.withAdNotification}),s.use(Di,{sdkKey:t,host:i,analyticsHost:o,version:r?.version}),s.use(Bi),s.use(vo),s.use(Vo),s.use(ao),s.use(Ko),s.after((a,u,l)=>{if(a)throw a;u.ready(),l()}),n&&s.after(async(a,u,l)=>{if(a)throw a;await u.sdk.initializeApp(),l()}),s.onClose(()=>{console.log("close")}),s}exports.StreamLayer=Su;
|
|
13
|
+
`+r+(o.length?i("│"):" ")+" ";return r+s.join(a)+`
|
|
14
|
+
`+o.map(function(u,d){var c=d===o.length-1,f=u.nodes&&u.nodes.length,p=r+(c?" ":i("│"))+" ";return r+i(c?"└":"├")+i("─")+i(f?"┬":"─")+" "+t(u,p,n).slice(r.length+2)}).join("")};const Ga=xa,an=Symbol("avvio.TimeTree.untrackNode"),zt=Symbol("avvio.TimeTree.trackNode"),un=Symbol("avvio.TimeTree.getParent"),cn=Symbol("avvio.TimeTree.getNode"),dn=Symbol("avvio.TimeTree.addNode");let Ka=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[zt](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[an](e){this.tableId.delete(e.id);const r=this.tableLabel.get(e.label);if(r.id){this.tableLabel.delete(e.label);return}r.pop(),r.length===0&&this.tableLabel.delete(e.label)}[un](e){if(e===null)return this.root;const r=this.tableLabel.get(e);return r.id?r:r[r.length-1]}[cn](e){return this.tableId.get(e)}[dn](e,r,n){if(e===null)return this.root={id:"root",label:r,start:n,nodes:[]},this[zt](this.root),this.root.id;const o=this[un](e),s=`${r}-${Math.random()}`,a={id:s,parent:e,start:n,label:r,nodes:[]};return o.nodes.push(a),this[zt](a),s}start(e,r,n=Date.now()){return this[dn](e,r,n)}stop(e,r=Date.now()){const n=this[cn](e);n&&(n.stop=r,n.diff=n.stop-n.start||0,this[an](n))}toJSON(){return Object.assign({},this.root)}prittyPrint(){const e=n=>(n.label=`${n.label} ${n.diff} ms`,n.nodes.length>0&&(n.nodes=n.nodes.map(i=>e(i))),n),r=e(this.toJSON());return Ga(r)}};var za=Ka,_r={exports:{}},pr={exports:{}},Ht,ln;function Ha(){if(ln)return Ht;ln=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,o=n*365.25;Ht=function(c,f){f=f||{};var p=typeof c;if(p==="string"&&c.length>0)return s(c);if(p==="number"&&isFinite(c))return f.long?u(c):a(c);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(c))};function s(c){if(c=String(c),!(c.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(c);if(f){var p=parseFloat(f[1]),w=(f[2]||"ms").toLowerCase();switch(w){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*i;case"days":case"day":case"d":return p*n;case"hours":case"hour":case"hrs":case"hr":case"h":return p*r;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function a(c){var f=Math.abs(c);return f>=n?Math.round(c/n)+"d":f>=r?Math.round(c/r)+"h":f>=e?Math.round(c/e)+"m":f>=t?Math.round(c/t)+"s":c+"ms"}function u(c){var f=Math.abs(c);return f>=n?d(c,f,n,"day"):f>=r?d(c,f,r,"hour"):f>=e?d(c,f,e,"minute"):f>=t?d(c,f,t,"second"):c+" ms"}function d(c,f,p,w){var E=f>=p*1.5;return Math.round(c/p)+" "+w+(E?"s":"")}return Ht}function Wa(t){r.debug=r,r.default=r,r.coerce=u,r.disable=o,r.enable=i,r.enabled=s,r.humanize=Ha(),r.destroy=d,Object.keys(t).forEach(c=>{r[c]=t[c]}),r.names=[],r.skips=[],r.formatters={};function e(c){let f=0;for(let p=0;p<c.length;p++)f=(f<<5)-f+c.charCodeAt(p),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(c){let f,p=null,w,E;function g(...m){if(!g.enabled)return;const T=g,D=Number(new Date),K=D-(f||D);T.diff=K,T.prev=f,T.curr=D,f=D,m[0]=r.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let X=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,($,_)=>{if($==="%%")return"%";X++;const ne=r.formatters[_];if(typeof ne=="function"){const ie=m[X];$=ne.call(T,ie),m.splice(X,1),X--}return $}),r.formatArgs.call(T,m),(T.log||r.log).apply(T,m)}return g.namespace=c,g.useColors=r.useColors(),g.color=r.selectColor(c),g.extend=n,g.destroy=r.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(w!==r.namespaces&&(w=r.namespaces,E=r.enabled(c)),E),set:m=>{p=m}}),typeof r.init=="function"&&r.init(g),g}function n(c,f){const p=r(this.namespace+(typeof f>"u"?":":f)+c);return p.log=this.log,p}function i(c){r.save(c),r.namespaces=c,r.names=[],r.skips=[];let f;const p=(typeof c=="string"?c:"").split(/[\s,]+/),w=p.length;for(f=0;f<w;f++)p[f]&&(c=p[f].replace(/\*/g,".*?"),c[0]==="-"?r.skips.push(new RegExp("^"+c.slice(1)+"$")):r.names.push(new RegExp("^"+c+"$")))}function o(){const c=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),c}function s(c){if(c[c.length-1]==="*")return!0;let f,p;for(f=0,p=r.skips.length;f<p;f++)if(r.skips[f].test(c))return!1;for(f=0,p=r.names.length;f<p;f++)if(r.names[f].test(c))return!0;return!1}function a(c){return c.toString().substring(2,c.toString().length-2).replace(/\.\*\?$/,"*")}function u(c){return c instanceof Error?c.stack||c.message:c}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var Ya=Wa;(function(t,e){e.formatArgs=n,e.save=i,e.load=o,e.useColors=r,e.storage=s(),e.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const d="color: "+this.color;u.splice(1,0,d,"color: inherit");let c=0,f=0;u[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(c++,p==="%c"&&(f=c))}),u.splice(f,0,d)}e.log=console.debug||console.log||(()=>{});function i(u){try{u?e.storage.setItem("debug",u):e.storage.removeItem("debug")}catch{}}function o(){let u;try{u=e.storage.getItem("debug")}catch{}return!u&&typeof I<"u"&&"env"in I&&(u=I.env.DEBUG),u}function s(){try{return localStorage}catch{}}t.exports=Ya(e);const{formatters:a}=t.exports;a.j=function(u){try{return JSON.stringify(u)}catch(d){return"[UnexpectedJSONParseError]: "+d.message}}})(pr,pr.exports);var ri=pr.exports;const Ja=Cn,Xa=Bn.EventEmitter,Za=Ct.inherits,x=ri("avvio"),{AVV_ERR_READY_TIMEOUT:eu}=ti,Wt=Symbol.for("plugin-meta");function tu(t,e){return t[Wt]&&t[Wt].name?t[Wt].name:typeof e<"u"&&typeof e!="function"&&e.name?e.name:t.name?t.name:t.toString().split(`
|
|
15
|
+
`).slice(0,2).map(r=>r.trim()).join(" -- ")}function ru(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function ze(t,e,r,n,i){this.started=!1,this.func=e,this.opts=r,this.onFinish=null,this.parent=t,this.timeout=i===void 0?t._timeout:i,this.name=tu(e,r),this.isAfter=n,this.q=Ja(t,nu,1),this.q.pause(),this._error=null,this.loaded=!1,this._promise=null}Za(ze,Xa);ze.prototype.exec=function(t,e){const r=this.func;let n=!1;const i=this.name;if(this.parent._error&&!this.isAfter){x("skipping loading of plugin as parent errored and it is not an after",i),I.nextTick(e);return}if(this.isAfter)this.server=t;else try{this.server=this.parent.override(t,r,this.opts)}catch(u){return x("override errored",i),e(u)}this.opts=typeof this.opts=="function"?this.opts(this.server):this.opts,x("exec",i);let o;const s=u=>{if(n){x("loading complete",i);return}this._error=u,x(u?"exec errored":"exec completed",i),n=!0,o&&clearTimeout(o),e(u)};this.timeout>0&&(x("setting up timeout",i,this.timeout),o=setTimeout(function(){x("timed out",i),o=null;const u=new eu(i);u.fn=r,s(u)},this.timeout)),this.started=!0,this.emit("start",this.server?this.server.name:null,this.name,Date.now());const a=r(this.server,this.opts,s);a&&typeof a.then=="function"&&(x("exec: resolving promise",i),a.then(()=>I.nextTick(s),u=>I.nextTick(s,u)))};ze.prototype.loadedSoFar=function(){if(this.loaded)return Promise.resolve();const t=()=>{this.server.after((r,n)=>{this._error=r,this.q.pause(),r?(x("rejecting promise",this.name,r),this._promise.reject(r)):(x("resolving promise",this.name),this._promise.resolve()),this._promise=null,I.nextTick(n,r)}),this.q.resume()};let e;return this._promise?e=Promise.resolve():(this._promise=ru(),e=this._promise.promise,this.server?t():this.on("start",t)),e};ze.prototype.enqueue=function(t,e){x("enqueue",this.name,t.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.q.push(t,e)};ze.prototype.finish=function(t,e){x("finish",this.name,t);const r=()=>{this.loaded||(x("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,e(t))};if(t){this._promise&&(this._promise.reject(t),this._promise=null),r();return}const n=()=>{if(x("check",this.name,this.q.length(),this.q.running(),this._promise),this.q.length()===0&&this.q.running()===0)if(this._promise){const i=()=>{x("wrap"),queueMicrotask(n)};this._promise.resolve(),this._promise.promise.then(i,i),this._promise=null}else r();else x("delayed",this.name),this.q.drain=()=>{x("drain",this.name),this.q.drain=iu,queueMicrotask(n)}};queueMicrotask(n),this.q.resume()};function nu(t,e){const r=this;I.nextTick(Cr.bind(r),t,e)}function Cr(t,e){if(typeof t.func.then=="function"){t.func.then(n=>{typeof n.default=="function"&&(n=n.default),t.func=n,Cr.call(this,t,e)},e);return}const r=this._current[0];this._current.unshift(t),t.exec(r&&r.server||this._server,n=>{t.finish(n,i=>{this._current.shift(),e(i)})})}function iu(){}_r.exports=ze;_r.exports.loadPlugin=Cr;var ou=_r.exports;const fn=Cn,su=Bn.EventEmitter,au=Ct.inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:Yt,AVV_ERR_CALLBACK_NOT_FN:Xe,AVV_ERR_PLUGIN_NOT_VALID:uu,AVV_ERR_ROOT_PLG_BOOTED:cu,AVV_ERR_READY_TIMEOUT:du}=ti,lu=za,hr=ou,Ge=ri("avvio"),It=Symbol("kAvvio"),Jt=Symbol("kThenifyDoNotWrap");function fu(t,e,r){const n=e.expose||{},i=n.use||"use",o=n.after||"after",s=n.ready||"ready",a=n.onClose||"onClose",u=n.close||"close";if(t[i])throw new Yt(i);if(t[o])throw new Yt(o);if(t[s])throw new Yt(s);t[i]=function(d,c){return r.use(d,c),this},Object.defineProperty(t,"then",{get:ni.bind(r)}),t[It]=!0,t[o]=function(d){return typeof d!="function"?r._loadRegistered():(r.after(Xt(d,this)),this)},t[s]=function(d){if(d&&typeof d!="function")throw new Xe(s,typeof d);return r.ready(d?Xt(d,this):void 0)},t[a]=function(d){if(typeof d!="function")throw new Xe(a,typeof d);return r.onClose(mu(d,this)),this},t[u]=function(d){if(d&&typeof d!="function")throw new Xe(u,typeof d);return d?(r.close(Xt(d,this)),this):r.close()}}function G(t,e,r){if(typeof t=="function"&&arguments.length===1&&(r=t,e={},t=null),typeof e=="function"&&(r=e,e={}),e=e||{},!(this instanceof G)){const n=new G(t,e,r);return t&&fu(t,e,n),n}e.autostart!==!1&&(e.autostart=!0),t=t||this,this._timeout=Number(e.timeout)||0,this._server=t,this._current=[],this._error=null,this._isOnCloseHandlerKey=Symbol("isOnCloseHandler"),this._lastUsed=null,this.setMaxListeners(0),r&&this.once("start",r),this.started=!1,this.booted=!1,this.pluginTree=new lu,this._readyQ=fn(this,ii,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=pn},this._closeQ=fn(this,gu,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=pn},this._doStart=null,this._root=new hr(this,pu.bind(this),e,!1,0),this._root.once("start",(n,i,o)=>{const s=this.pluginTree.start(null,i,o);this._root.once("loaded",(a,u,d)=>{this.pluginTree.stop(s,d)})}),hr.loadPlugin.call(this,this._root,n=>{Ge("root plugin ready");try{this.emit("preReady"),this._root=null}catch(i){n=n||this._error||i}if(n){if(this._error=n,this._readyQ.length()===0)throw n}else this.booted=!0;this._readyQ.resume()})}function pu(t,e,r){this._doStart=r,e.autostart&&this.start()}au(G,su);G.prototype.start=function(){return this.started=!0,I.nextTick(this._doStart),this};G.prototype.override=function(t,e,r){return t};function hu(t){if(t&&typeof t=="object"&&typeof t.default=="function"&&(t=t.default),!(t&&(typeof t=="function"||typeof t.then=="function")))throw new uu(typeof t);return t}G.prototype[It]=!0;G.prototype.use=function(t,e){return this._lastUsed=this._addPlugin(t,e,!1),this};G.prototype._loadRegistered=function(){const t=this._current[0];return!this.started&&!this.booted&&I.nextTick(()=>this._root.q.resume()),t?t.loadedSoFar():Promise.resolve()};Object.defineProperty(G.prototype,"then",{get:ni});G.prototype._addPlugin=function(t,e,r){if(t=hu(t),e=e||{},this.booted)throw new cu;const n=this._current[0],i=new hr(this,t,e,r);if(i.once("start",(o,s,a)=>{const u=this.pluginTree.start(n.name,s,a);i.once("loaded",(d,c,f)=>{this.pluginTree.stop(u,f)})}),n.loaded)throw new Error(i.name,n.name);return n.enqueue(i,o=>{o&&(this._error=o)}),i};G.prototype.after=function(t){if(!t)return this._loadRegistered();this._addPlugin(e.bind(this),{},!0);function e(r,n,i){ii.call(this,t,i)}return this};G.prototype.onClose=function(t){if(typeof t!="function")throw new Error("not a function");t[this._isOnCloseHandlerKey]=!0,this._closeQ.unshift(t,e.bind(this));function e(r){r&&(this._error=r)}return this};G.prototype.close=function(t){let e;if(t){if(typeof t!="function")throw new Xe("close",typeof t)}else e=new Promise(function(r,n){t=function(i){if(i)return n(i);r()}});return this.ready(()=>{this._error=null,this._closeQ.push(t),I.nextTick(this._closeQ.resume.bind(this._closeQ))}),e};G.prototype.ready=function(t){if(t){if(typeof t!="function")throw new Xe("ready",typeof t);this._readyQ.push(t),queueMicrotask(this.start.bind(this));return}return new Promise((e,r)=>{this._readyQ.push(i),this.start();const n=this._current[0].server;function i(o,s,a){o?r(o):e(n),I.nextTick(a)}})};G.prototype.prettyPrint=function(){return this.pluginTree.prittyPrint()};G.prototype.toJSON=function(){return this.pluginTree.toJSON()};function pn(){}function ni(){if(this.booted){Ge("thenify returning null because we are already booted");return}if(this[Jt]){this[Jt]=!1;return}return Ge("thenify"),(t,e)=>this._loadRegistered().then(()=>(this[Jt]=!0,t(this._server)),e)}function ii(t,e){const r=this._server,n=this._error;let i;if(this._error=null,t.length===0)this._error=n,i=t(),i&&!i[It]&&typeof i.then=="function"?i.then(()=>I.nextTick(e),o=>I.nextTick(e,o)):I.nextTick(e);else if(t.length===1)i=t(n),i&&!i[It]&&typeof i.then=="function"?i.then(()=>I.nextTick(e),o=>I.nextTick(e,o)):I.nextTick(e);else if(this._timeout===0){const o=s=>{this._error=s,e(this._error)};t.length===2?t(n,o):t(n,r,o)}else yu.call(this,t,n,r,e)}function yu(t,e,r,n){const i=t.name;Ge("setting up ready timeout",i,this._timeout);let o=setTimeout(()=>{Ge("timed out",i),o=null;const a=new du(i);a.fn=t,this._error=a,n(a)},this._timeout);t.length===2?t(e,s.bind(this)):t(e,r,s.bind(this));function s(a){o&&(clearTimeout(o),this._error=a,n(this._error))}}function gu(t,e){const r=this._server,n=t[this._isOnCloseHandlerKey];if(t.length===0||t.length===1){let i;n?i=t(r):i=t(this._error),i&&typeof i.then=="function"?(Ge("resolving close/onClose promise"),i.then(()=>I.nextTick(e),o=>I.nextTick(e,o))):I.nextTick(e)}else t.length===2?t(n?r:this._error,e):n?t(r,e):t(this._error,r,e)}function mu(t,e){return r.bind(e);function r(n,i){let o;t.length===0?(o=t(),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t.length===1?(o=t(this),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t(this,i)}}function Xt(t,e){return r.bind(e);function r(n,i){let o;t?t.length===0?(o=t(),o&&o.then?o.then(function(){I.nextTick(i,n)},i):I.nextTick(i,n)):t.length===1?(o=t(n),o&&o.then?o.then(function(){I.nextTick(i)},i):I.nextTick(i)):t.length===2?t(n,i):t(n,this,i):I.nextTick(i)}}mr.exports=G;mr.exports.express=function(t){return G(t,{expose:{use:"load"}})};var bu=mr.exports;const vu=zo(bu);(function(){if(window.requestAnimationFrame&&window.cancelAnimationFrame)return;const t=["webkit","moz","ms","o"];for(const e of t)window.requestAnimationFrame=window.requestAnimationFrame||window[`${e}RequestAnimationFrame`],window.cancelAnimationFrame=window.cancelAnimationFrame||window[`${e}CancelAnimationFrame`]||window[`${e}CancelRequestAnimationFrame`];if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){let e=0;const r=!!(window.performance&&window.performance.now);window.requestAnimationFrame=function(n){const i=r?window.performance.now():new Date().getTime(),o=Math.max(0,16-(i-e)),s=window.setTimeout(function(){n(i+o)},o);return e=i+o,s},window.cancelAnimationFrame=clearTimeout}})();function Su(t,e=!0,r=!0,n={friendsTab:"enabled"}){const i=e?"https://grpc-sdk.streamlayer.io:443":"https://grpc-sdk.next.streamlayer.io:443",o=e?"https://grpc.streamlayer.io:443":"https://grpc.next.streamlayer.io:443",s=vu(Object.create({}),{autostart:!1});return s.use(Ao,{hideFriends:n.hideFriends,skipOnboarding:n.skipOnboarding,betPack:n.betPack,friendsTab:n.friendsTab,theme:n.theme,themeMode:n.themeMode}),s.use(mo,{onDeepLinkHandled:n?.onDeepLinkHandled}),s.use(wo,{videoPlayerController:n?.videoPlayerController}),s.use(Eo,{onContentActivate:n?.onContentActivate,withAd:n?.withAd,withAdNotification:n?.withAdNotification}),s.use(Vi,{sdkKey:t,host:i,analyticsHost:o,version:n?.version}),s.use(Ui),s.use(So),s.use(Vo),s.use(co),s.use(Ko),s.after((a,u,d)=>{if(a)throw a;u.ready(),d()}),r&&s.after(async(a,u,d)=>{if(a)throw a;await u.sdk.initializeApp(),d()}),s.onClose(()=>{console.log("close")}),s}exports.StreamLayer=Su;
|