@streamlayer/sdk-web 0.33.5 → 0.33.6
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 +1 -1
- package/lib/es/index.js +4 -4
- package/package.json +5 -5
package/lib/cjs/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Yn=require("pino"),C=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),rt=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),R=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),nt=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),X=require("nanostores"),Wt=require("nanoid"),M=require("@connectrpc/connect"),Or=require("@connectrpc/connect-web"),Cr=require("@nanostores/query"),Xn=require("@streamlayer/sl-eslib/sports/events/events_connect"),Je=require("@streamlayer/sl-eslib/sdkSettings/client/client_connect"),lr=require("@streamlayer/sl-eslib/users/users_connect"),me=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_connect"),sn=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_connect");require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb");const Zn=require("@streamlayer/sl-eslib/shortLinks/linksClient_connect"),v=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),an=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_connect"),_r=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),Y=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function ei(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var un={exports:{}},j=un.exports={},te,re;function Jt(){throw new Error("setTimeout has not been defined")}function Yt(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?te=setTimeout:te=Jt}catch{te=Jt}try{typeof clearTimeout=="function"?re=clearTimeout:re=Yt}catch{re=Yt}})();function cn(t){if(te===setTimeout)return setTimeout(t,0);if((te===Jt||!te)&&setTimeout)return te=setTimeout,setTimeout(t,0);try{return te(t,0)}catch{try{return te.call(null,t,0)}catch{return te.call(this,t,0)}}}function ti(t){if(re===clearTimeout)return clearTimeout(t);if((re===Yt||!re)&&clearTimeout)return re=clearTimeout,clearTimeout(t);try{return re(t)}catch{try{return re.call(null,t)}catch{return re.call(this,t)}}}var de=[],je=!1,Te,st=-1;function ri(){!je||!Te||(je=!1,Te.length?de=Te.concat(de):st=-1,de.length&&ln())}function ln(){if(!je){var t=cn(ri);je=!0;for(var e=de.length;e;){for(Te=de,de=[];++st<e;)Te&&Te[st].run();st=-1,e=de.length}Te=null,je=!1,ti(t)}}j.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];de.push(new dn(t,e)),de.length===1&&!je&&cn(ln)};function dn(t,e){this.fun=t,this.array=e}dn.prototype.run=function(){this.fun.apply(null,this.array)};j.title="browser";j.browser=!0;j.env={};j.argv=[];j.version="";j.versions={};function he(){}j.on=he;j.addListener=he;j.once=he;j.off=he;j.removeListener=he;j.removeAllListeners=he;j.emit=he;j.prependListener=he;j.prependOnceListener=he;j.listeners=function(t){return[]};j.binding=function(t){throw new Error("process.binding is not supported")};j.cwd=function(){return"/"};j.chdir=function(t){throw new Error("process.chdir is not supported")};j.umask=function(){return 0};var ni=un.exports;const T=ei(ni),ii=Yn.pino({level:"trace",enabled:!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),ve=(t,e)=>ii.child({name:t},e);class oi extends Event{slEventBus;constructor(e,r){super(e),this.slEventBus=r}}const si=ve("event-bus");class ai{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,r)=>{const n=new oi(this.name,{...r,type:e});si.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 ui{}window.slStore=Object.create(null);class wt{store;name;constructor(e,r){this.store=e,this.name=r}getStore(){return this.store}}const ci=t=>{const e=Object.keys(t);return X.computed(e.map(r=>t[r].getStore()),(...r)=>Object.fromEntries(e.map((n,i)=>[n,r[i]])))};class Ae extends wt{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 ie=t=>X.map(t);var ue;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(ue||(ue={}));const li={[R.SdkOverlayType.BETTING]:"betting",[R.SdkOverlayType.GAMES]:"games",[R.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[R.SdkOverlayType.TWITTER]:"twitter"};var Ke;(function(t){t.Ready="ready",t.Suspended="suspended"})(Ke||(Ke={}));class fn{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...r},n){this.settingsKey=li[r.type],this.status=X.atom(Ke.Suspended),this.config=new Ae(ie(r),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ae(ie(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ae(ie({}),`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(Ke.Ready)};disable=()=>{this.status.set(Ke.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===ue.STREAM&&r===ue.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 H extends wt{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=>X.atom(t);class pe extends wt{atomStore;constructor(e,r,n){super(e,`api:${r}`),this.atomStore=X.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 fe=new ai;async function*di(t,e){for await(const r of e){t.response.message=r,t.received_at=Date.now();const n={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(n),yield r}}const fi=()=>t=>async e=>{const r={name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries())},response:{}};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){r.request.message=e.message;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...r,stream:!1}};return window.postMessage(i),{...n,message:di(r,n.message)}}else{r.request.message=e.message,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.request.message=e.message,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"));var J;(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"})(J||(J={}));class pi{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,r,n,i){const o={status:J.Init,ts:new Date,log:[]};this.state=new Ae(ie(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 H(Q(null),`subscription:${i.name}:store`)),"subscribe"in n&&typeof n.subscribe=="function"&&(this.paramsListener=n.subscribe(s=>{this.state.getValue("status")===J.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(J.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}`;r.push(n),this.state.setValue("log",r),window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
-
`+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(J.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(J.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(J.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(J.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(J.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(J.Failed),this.state.setValue("error",e),this.reconnect();return}this.disconnect()}}}const hi=new Set([M.Code.Unknown,M.Code.Internal,M.Code.DeadlineExceeded,M.Code.ResourceExhausted,M.Code.FailedPrecondition,M.Code.Unavailable,M.Code.DataLoss]),Lr=ve("grpc:retry"),yi=t=>async e=>{const r=e.contextValues.get(Xt.retryAttempts),n=300,i=e.contextValues.get(Xt.retryDelay);if(e.stream||r===0)return t(e);Lr.trace({url:e.url,attempts:r,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Lr.trace({attempt:o,error:s},"retry attempt");const a=M.ConnectError.from(s);if(o>=r||!(a instanceof M.ConnectError)||!hi.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))}},Xt={retryAttempts:M.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:M.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},gi=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Wt.nanoid();return localStorage.setItem("sl-device-id",e),e},mi=()=>navigator.userAgentData?.platform||navigator.platform;class kr{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 Ae(ie({"sl-device-id":gi(),"sl-device-os":mi()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[n,i,o]=Cr.nanoquery({dedupeTime:r?.dedupeTime,refetchInterval:r?.refetchInterval});this.nanoquery={createFetcherStore:n,createMutatorStore:i,utils:o},this.transport=Or.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors,useBinaryFormat:!0}),this.streamTransport=Or.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors,useBinaryFormat:!0})}addSubscription=(e,r,n)=>{const i=this.subscriptions.get(r);if(i)return i;const o=new pi(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]=Cr.nanoquery({dedupeTime:1e3*60*5,refetchInterval:1e3*60*5});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.createPromiseClient(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.createPromiseClient(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 h=Xt[f];c.set(h,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(fi()),this.opts?.retryable&&this.interceptors.push(yi)}}const vi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Xn.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""}}})},bi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.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})},Si=(t,e)=>{const{queryKey:r,client:n}=e.createPromiseClient(lr.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:()=>n.me({})})},wi=t=>{const{client:e,createRequestOptions:r}=t.createPromiseClient(lr.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})},Ti=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.get({})).data?.attributes})},Ai=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.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}})},Ei=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.getOrganizationAdvertising({})).data?.attributes})},Ii=(t,e,r)=>{t.transport=new kr(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new kr(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()};class Tt{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()||"";this.storage.setItem(this.generateKey(e),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 ae;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(ae||(ae={}));class Re extends Tt{constructor(){super("user")}setSchema=e=>{this.write(ae.SCHEMA,e)};getSchema=()=>this.read(ae.SCHEMA);setToken=e=>{this.write(ae.TOKEN,e)};getToken=()=>this.read(ae.TOKEN);setExternalToken=e=>{this.write(ae.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(ae.EXTERNAL_TOKEN);removeToken=()=>{this.remove(ae.TOKEN)}}var ce;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(ce||(ce={}));const Oi=t=>{const e=new Re,r=new H(Q(e.getExternalToken()),"userKey"),n=new H(Q(e.getToken()),"userToken"),i=new pe(Si(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 pe(Ti(n.getStore(),t),"userSettings");return{userKey:r,userToken:n,user:i,userSettings:o}},Ci=t=>{const e=new H(Q(void 0),"providerStreamId"),r=new pe(vi(e.getStore(),t),"slStreamId",i=>i?.data),n=new pe(bi(r.getAtomStore(),t),"streamSettings");return r.getAtomStore().listen(i=>{(i===""||i===void 0)&&n.getStore().mutate(void 0)}),{providerStreamId:e,slStreamId:r,streamSettings:n}},_i=t=>{const e=new H(Q(void 0),"enabled"),r=new H(Q(ce.DISABLED),"status"),n=new pe(Ai(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new pe(Ei(n.getAtomStore(),t),"organizationAdvertising"),o=Oi(t),s=Ci(t);return{enabled:e,status:r,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:n,organizationAdvertising:i}};class Li extends wt{stores;constructor(e){const r=_i(e),n=ci(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 ki=(t,e,r)=>{t.store=new Li(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.storeUnsubscribe=()=>{t.store.unsubscribe()},r()},Pi=t=>{const{client:e}=t.createPromiseClient(sn.Leaderboard,{method:"list"});return r=>e.list(r)},pn=t=>{const{client:e}=t.createPromiseClient(sn.Leaderboard,{method:"summary"});return r=>e.summary(r)},Fi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(lr.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.getFriends({})).data:[]})},Ni=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.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})},Di=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.Feed,{method:"syncQuestion",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.syncQuestion({filter:{eventId:s}})).data?.attributes:void 0,dedupeTime:1e3*60*10,refetchInterval:0})},Ri=(t,e)=>{const{client:r}=e.createStreamClient(me.Feed),n=X.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{n.set({eventId:o,feedId:""})}),e.addSubscription(r.subscription,n,{name:"feedSubscription"})},$i=(t,e)=>{const{client:r}=e.createStreamClient(me.Feed);return e.addSubscription(r.questionSubscription,{questionId:t},{name:"questionSubscription"})},Zt=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.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})},Vi=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(me.Feed,{method:"list",params:[t,e]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>a?(await n.list({eventId:a,filter:{types:u===Ee.ALLOWED?[]:[C.QuestionType.FACTOID,C.QuestionType.PROMOTION,C.QuestionType.TWEET],statuses:[C.QuestionStatus.ACTIVE,C.QuestionStatus.RESOLVED]}})).data:[],dedupeTime:0,refetchInterval:0})},ji=(t,e,r)=>{const n=X.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=X.batched(n,a=>a&&a.type==="question"?a.id:void 0),o=Zt(i,t);return{$store:n,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,d=(c,f)=>{if(!c||!f)return c||f||[];const h=[];for(let m=0;m<c.length;m++)h.push({...c[m],...f[m],correct:c[m].correct,youVoted:c[m].youVoted,pointsEarned:c[m].pointsEarned});return h};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:d(u?.answers,a?.answers)})}}};var Ee;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Ee||(Ee={}));class Mi{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;moderationId;moderation;feedSubscription;questionSubscription;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ve("gamification-background"),this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new H(Q(void 0),"moderationId").getStore(),this.interactiveAllowed=new H(Q(Ee.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new H(Q(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new pe(Ni(this.slStreamId,e.transport),"gamification:moderation"),this.feedList=new pe(Vi(this.slStreamId,this.interactiveAllowed,e.transport),"gamification:feedList"),this.activeQuestionId=Di(this.slStreamId,e.transport),this.openedQuestion=ji(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(r=>{this.log.debug({item:r},"received question"),r?.questionId?(this.questionSubscription=$i(r.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",n=>{this.openedQuestion.updateExtendedQuestion(n.data?.attributes?.question)}),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=Ri(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",r=>{const n=this.activeQuestionId.get().data?.question?.id,i=r.data?.attributes?.question;i&&(n&&i.status===C.QuestionStatus.RESOLVED&&i.id!==n||this.activeQuestionId.mutate(r.data?.attributes))})),this.cancels.add(this.feedSubscription.addListener("moderation update",r=>{window.requestAnimationFrame(()=>{r.data?.attributes?.question===void 0&&r.data?.attributes?.moderation&&this.moderation.invalidate()})})),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 r of this.cancels)r(),this.cancels.delete(r)})}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 Ui{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ve("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}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")},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 pt;(function(t){t.OPENED="opened"})(pt||(pt={}));class qi extends Tt{constructor(){super("notification")}setOpened=e=>{this.write(pt.OPENED,e,"true")};isOpened=e=>this.read(pt.OPENED,e);clearNotification=()=>{this.clear()}}var ge;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(ge||(ge={}));class xi{queue;storage;constructor(e={}){this.storage=new qi,this.queue=new Ui({concurrency:1,animationDelay:1600,...e})}add=e=>{if(!this.storage.isOpened(e.id)){if(e.data&&e.emitEvent){const n=e.action;e.action=(...i)=>{n&&n(...i),fe.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===ge.ONBOARDING)return n;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const Bi=(t,e,r)=>{t.notifications=new xi(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 We;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(We||(We={}));const Qi=async(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(me.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(We.ALREADY_VOTED):new Error(We.UNKNOWN)}},Gi=(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(me.Feed,{method:"submitInplay"}),i=n({retryAttempts:0});return r.submitInplay({data:{eventId:+e}},{contextValues:i})};var $e;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io"})($e||($e={}));class hn extends Tt{constructor(){super("gamification")}saveOnboardingStatus=({userId:e,eventId:r,organizationId:n},i)=>{this.write($e.ONBOARDING,n,e,r,i)};getOnboardingStatus=({userId:e,eventId:r,organizationId:n})=>this.read($e.ONBOARDING,n,e,r);setOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{const i=this.generateKey([$e.ONBOARDING_IO,n,e,r]);window.sessionStorage.setItem(i,"1")};getOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{const i=this.generateKey([$e.ONBOARDING_IO,n,e,r]);return window.sessionStorage.getItem(i)}}const Ki={pageSize:10},zi=(t,e,r,n,i)=>{let o=0;const s=Q({pageSize:i?.pageSize||Ki.pageSize,page:0}),a=ie({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Pi(t),d=async()=>{const h=e.get(),m=n.getStore().get().data?.map(b=>b.slId)||[];if(h&&m?.length){const b=r.get();b&&m.push(b),a.setKey("loading",!0),a.setKey("data",[]);const S=await u({eventId:h,usersIds:m});a.set({data:S.data.map((P,V)=>({...P.attributes,friendsRank:V+1})),hasMore:!1,key:Date.now(),loading:!1}),S.meta&&(o=Math.round(S.meta.count/S.meta.pageSize))}},c=()=>{d()},f=h=>{const m=s.get(),b=h||m.page+1;b<=o&&s.set({...m,page:b})};return X.onMount(a,()=>{const h=e.listen(d),m=n.listen(d);return()=>{h(),m()}}),{$store:a,fetchMore:f,invalidate:c}};class Hi extends Tt{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Pr="sldl",At="sldl_uid",yn="sldl_eid",gn="sldl_e_eid",Wi=new Set([At,yn,gn]),Fr=t=>{const e={},r={};for(const[n,i]of t)Wi.has(n)?e[n]=i:r[n]=i;return{result:e,remain:r}},Ji=({hash:t,search:e})=>{if(t&&t.includes(Pr)){const r=new URLSearchParams(t.substr(1));return{hash:Fr(r)}}if(e&&e.includes(Pr)){const r=new URLSearchParams(e);return{search:Fr(r)}}return null},Nr=ve("deep_link"),ne={debug:(...t)=>{Nr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Nr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Yi=(t,e)=>{const{hash:r,search:n}=window.location;if(ne.debug({hash:r,search:n},"get deep link data from"),r||n){const i=Ji({hash:r,search:n});if(ne.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()}`,ne.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()}`,ne.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},Xi=(t,e,r)=>{const n=new Hi,i=n.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ne.debug(a)}t.deepLink={$store:new Ae(ie(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ne.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?.[At]: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")&&ne.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ne.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ne.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ne.trace("called handler"),u(a)}catch(d){console.error(d)}};Yi(t.deepLink.$store,s),r()},Zi=ve("bypass");class eo extends ui{$coreStore;deepLink;transport;bypassLogin;constructor(e,r,n){super(),this.$coreStore=e,this.deepLink=n,this.transport=r,this.bypassLogin=wi(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?.[At];Zi.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(s),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 Re().clear()};softLogout=()=>{const e=new Re;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=()=>{const e=new Re,r=e.getToken(),n=e.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(n),r)return this.saveUser(r,""),this.me().then(i=>{if(i?.id){const o=i.id;this.saveUser(r,o)}});if(n&&!r){const i=e.getSchema();i&&n&&this.login(i,n).catch(()=>{this.logout()})}};saveUser=(e,r)=>{this.transport.setAuth(e,r),this.$coreStore.getValues().userToken.setValue(e),new Re().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 Ge=new Re,to=(t,e,r)=>{t.auth=new eo(t.store,t.transport,t.deepLink),t.stores.status.listen(n=>{n===ce.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(n,i)=>{if(!(Ge.getSchema()===n&&Ge.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(n,i),Ge.setSchema(n),Ge.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),Ge.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),r()},Dr=ve("video_player"),it={debug:(...t)=>{Dr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Dr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},ro=(t,e,r)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=n=>{it.trace("adding video player controller"),t.videoPlayer.controllers.add(n)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=n=>{it.trace("removing video player controller"),t.videoPlayer.controllers.delete(n)},t.sdk.controlVideoPlayer=n=>{it.trace("controlling video player");for(const i of t.videoPlayer.controllers){it.trace("calling video player controller");try{i(n)}catch(o){console.error(o)}}},r()},no=(t,e,r)=>{const n={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),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(ce.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(ce.READY),{enabled:!!a}):(t.stores.status.setValue(ce.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(ce.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(ce.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(Je.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s,a)=>s?(await r.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes:{},dedupeTime:1e3*60*60*24,refetchInterval:0})},oo=(t,{web:e,mobile:r})=>{const{client:n}=t.createPromiseClient(Zn.LinksClient,{method:"generate"});return n.generate({web:e,mobile:r})},Rr=(t,e)=>{const r=new URLSearchParams(t);for(const[n,i]of Object.entries(e))r.append(n,i);return r.toString()},so=(t,e,r,n)=>{const i=ie({});return X.onMount(i,()=>io(t,[e,r]).subscribe(async({data:a,error:u,loading:d})=>{const c=u?"https://masters.com":a?.url,f=n.get()||"",h=e.get()||"",m=r.get()||"",b={[At]:f,[yn]:h,[gn]:m};if(!d&&c){i.setKey("loading",!0);let I=window.location.search,S=window.location.hash;I&&S||S?I=`?${Rr(I,b)}`:S=`#${Rr("",b)}`;const P=window.location.origin+window.location.pathname+I+S,V=await oo(t,{web:P,mobile:c});i.set({data:V.data?.link,loading:!1})}else i.setKey("loading",!0)})),{$store:i,fetch}};var x;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(x||(x={}));const ao=(t,e,r,n)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&r.add({type:ge.ONBOARDING,id:o,action:t.openFeature,persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:C.QuestionType.UNSET,onboarding:{...i,instantOpen:!n.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ot=(t,e,r,n,i,o)=>{try{const s=e.userId.get();if(!s)return;if(i.getOnboardingStatus({userId:s,organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})===x.Completed){t.set(x.Completed);for(const h of o)h();return}const u=e.moderation.getStore().value?.data,d=r.featureSettings.get().inplayGame;if(u===void 0||d===void 0)return;const c=u?.options?.onboardingEnabled,f=d?.titleCard?.optIn;c?f?t.set(x.Required):t.set(x.Optional):(f?t.set(x.Unavailable):t.set(x.Disabled),n.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(s){console.error(s)}},uo=(t,e,r,n)=>{let i=!1;const o=new hn,s=Q(x.Unset);s.subscribe(d=>{d!==x.Unset&&((d===x.Optional||d===x.Required)&&i===!1&&(ao(t,e,n,o),i=!0),d===x.Completed&&e.activeQuestionId.invalidate(),o.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const a=[];return ot(s,e,t,n,o,a),s.get()!==x.Completed&&(a.push(e.userId.listen(d=>{d&&ot(s,e,t,n,o,a)})),a.push(e.moderation.listen(d=>{d.data&&ot(s,e,t,n,o,a)})),a.push(t.featureSettings.listen(d=>{d&&ot(s,e,t,n,o,a)}))),{$store:s,submitInplay:async()=>{const d=e.slStreamId.get();if(d){await Gi(r,d),s.set(x.Completed),o.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:d},x.Completed),fe.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const c=e.getCurrentSessionId({prefix:"onboarding"});n.close(c)}}}},co=(t,e,r,n)=>{const i=ie(void 0),o=pn(n),s=async()=>{const u=t.get(),d=e.get(),c=r.getStore().get().data?.map(b=>b.slId);if(!c)return;const f={eventId:u,userId:d,usersIds:[...c,d]},h=await o(f),m=i.get()?.summary?.friendsRank;h.data?.attributes?.summary?.friendsRank&&m!==void 0&&(h.data.attributes.summary.friendsRank=m),i.set(h.data?.attributes)},a=()=>{s()};return X.onMount(i,()=>{const u=t.listen(s),d=r.listen(s),c=e.listen(s);return()=>{u(),d(),c()}}),{$store:i,invalidate:a}},lo=async(t,e,r,n,i)=>{const o=pn(i),s=t.get(),a=e.get(),u=r.getStore().get().data?.map(h=>h.slId)||[],d={eventId:s,userId:n,usersIds:[...u,a]};return(await o(d)).data?.attributes?.summary},fo=new Set([C.QuestionType.POLL,C.QuestionType.PREDICTION,C.QuestionType.TRIVIA]);class po extends fn{userSummary;feedList;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;constructor(e,r,n){super(e,r),this.background=new Mi(n),this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=new hn,this.feedList=this.background.feedList,this.friends=new pe(Fi(this.background.userId,n.transport),"gamification:friends"),this.currentUserId=this.background.userId,this.openedUser=Q(void 0),this.leaderboardId=new H(Q(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.onboardingStatus=uo(this,this.background,n.transport,n.notifications),this.notifications=n.notifications,this.transport=n.transport,this.closeFeature=()=>n.sdk.closeFeature(!0),this.openFeature=()=>n.sdk.openFeature(R.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=so(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),this.leaderboardList=zi(this.transport,this.background.slStreamId,this.background.userId,this.friends),this.connect(),this.cancels.add(this.userSummary.$store.listen((i,o)=>{o?.summary&&i?.summary&&!i.fromLeaderboard&&this.leaderboardList.invalidate()})),this.cancels.add(this.background.activeQuestionId.listen(this.showInApp)),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)),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()===Ee.ALLOWED}checkInteractiveFlag=()=>{const e=this.onboardingStatus.$store.get(),r=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,n=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===x.Completed,o=!r||i||n!==!0;this.background.interactiveAllowed.set(o?Ee.ALLOWED:Ee.DISALLOWED)};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===C.QuestionStatus.RESOLVED&&o===C.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),d=[...this.feedList.getValues().data||[]],c=d.findIndex(G=>G.id===s),f=d[c];let h=f?.attributes?.attributes?.value?.answerId;const m=Zt(s,this.transport),b=m.subscribe(()=>{});await m.get().promise;const I=m.get().data;b(),window.requestAnimationFrame(()=>{m.invalidate()}),h||(h=I?.answers.find(({youVoted:G})=>G)?.id);const S=a.find(({correct:G})=>G),P=h?a.find(({id:G})=>G===h):void 0,V=!!P?.correct;if(f&&d[c]?.attributes?.attributes.case==="question"){try{d[c].attributes.attributes.value.answerId=h,d[c].attributes.attributes.value.openForVoting=!1,h&&(d[c].attributes.attributes.value.status=V?rt.PickHistoryStatus.WON:rt.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(d)}if(!P||!S)return;this.openedQuestionId.get()?.questionId!==r.id&&this.notifications.add({type:ge.QUESTION_RESOLVED,action:()=>this.openQuestion(r.id,n),close:()=>this.closeQuestion(s),autoHideDuration:V?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:C.QuestionType.PREDICTION,question:{title:V?`Congratulations! You answered correctly! You won ${S.points} pts!`:`Better luck next time! Correct: ${S?.text}!`,votedAnswer:{title:P?.text,points:P?.points},correctAnswerTitle:S?.text,correct:!!V,predictionResult:i===C.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.status!==C.QuestionStatus.ACTIVE&&n.attributes.status!==C.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),fe.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")};submitAnswer=async(e,r)=>{const n=Zt(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){fe.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=n.get().data;if(i(),f){const h=f.answers.find(S=>S.correct===!0),m=f.answers.findIndex(S=>S.id===r),b=f.answers[m],I=f.answers.every(({percentageDecimal:S},P)=>S===o?.answers[P].percentageDecimal);a[u].attributes.attributes.value.answerId=r,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=b?.text||"",h&&(a[u].attributes.attributes.value.status=h.id===r?rt.PickHistoryStatus.WON:rt.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[m].correct=h?.id===r,f.answers[m].youVoted=!0,I&&f.answers.forEach(S=>{S.percentageDecimal=0}),h?.id===r&&(f.answers[m].pointsEarned=f.status===C.QuestionStatus.RESOLVED?0:h.points),n.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Qi(this.transport,{questionId:e,answerId:r}),s()}catch(a){if(a.message===We.ALREADY_VOTED){this.userSummary.invalidate();const u=n.subscribe(()=>{});n.invalidate(),u()}throw a}};openQuestion=(e,r)=>{if(!e)return()=>{};this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let n=r?.attributes?.type;return n||(n=(this.feedList.getStore().value?.data||[]).find(o=>o.id===e)?.attributes?.type),fe.emit("poll",{action:"opened",payload:{questionId:e,questionType:n,questionOpenedFrom:r?.openedFrom}}),this.background.openQuestion(e,r)};closeQuestion=e=>this.background.closeQuestion(e);openUser=async e=>{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 lo(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!==x.Unset&&e.data.question?.id!==void 0&&e.data.question.notification!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==C.SilenceSetting.ON&&e.data.question.status===C.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(fo.has(e.data.question.type))this.isInteractiveAllowed&&this.notifications.add({type:ge.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}}});else if(e.data.question.type===C.QuestionType.FACTOID){const n=e.data.question.options?.options.value,i={heading:e.data.question.notification.title,body:e.data.question.notification.body,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:ge.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:i}})}else if(e.data.question.type===C.QuestionType.TWEET){const n=e.data.question.options?.options.value,i={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};this.notifications.add({type:ge.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:i}})}}}}const ho={[R.SdkOverlayType.GAMES]:!0};class yo extends fn{constructor(e,r){super(e,r)}}const go=(t,e,r)=>t.type===R.SdkOverlayType.GAMES?new po(t,e,r):new yo(t,e),mo=(t,e,r)=>{t.features=new Map,t.sdk.featuresList=new H(Q(new Set),"features-list"),t.activeFeature=new H(Q(R.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.activeFeature.setValue(n)},t.sdk.closeFeature=(n=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(R.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=ue.ORGANIZATION)=>{if(n.type in ho&&!t.features.has(n.type)){const o=go(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,ue.ORGANIZATION)},t.stores.providerStreamId.listen(n=>{n||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const n=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===ue.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(ue.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{n(ue.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},r()};class vo{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 fe.listen(r)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:nt.InvitationCategory.GAMES,from:nt.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:nt.InvitationCategory.GAMES,from:e||nt.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 fe.listen(r)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:_r.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:_r.InteractionActionType.SCROLL})}}const ze={[C.QuestionType.UNSET]:v.TopicType.UNSET,[C.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[C.QuestionType.POLL]:v.TopicType.POLLS_POLL,[C.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[C.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[C.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[C.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};C.QuestionType.UNSET+"",Y.NotificationKind.UNSET,C.QuestionType.FACTOID+"",Y.NotificationKind.POLLS,C.QuestionType.POLL+"",Y.NotificationKind.POLLS,C.QuestionType.PREDICTION+"",Y.NotificationKind.POLLS,C.QuestionType.PROMOTION+"",Y.NotificationKind.POLLS,C.QuestionType.TRIVIA+"",Y.NotificationKind.POLLS,C.QuestionType.TWEET+"",Y.NotificationKind.POLLS;const So={[R.SdkOverlayType.UNSET]:v.Category.UNSET,[R.SdkOverlayType.INPLAY]:v.Category.INPLAY,[R.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[R.SdkOverlayType.STATISTICS]:v.Category.STATS,[R.SdkOverlayType.BETTING]:v.Category.BETTING,[R.SdkOverlayType.TWITTER]:v.Category.TWITTER,[R.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[R.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[R.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[R.SdkOverlayType.TICKETS]:v.Category.TICKETS,[R.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[R.SdkOverlayType.PROFILE]:v.Category.PROFILE,[R.SdkOverlayType.GAMES]:v.Category.POLLS,[R.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[R.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[R.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class wo{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}};return fe.listen(r)})}received=({questionId:e,questionType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:r?ze[r]:v.TopicType.UNSET},notificationKind:Y.NotificationKind.POLLS,notificationType:Y.NotificationType.IN_APP})};opened=({questionId:e,questionType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:r?ze[r]:v.TopicType.UNSET},notificationKind:Y.NotificationKind.POLLS,notificationType:Y.NotificationType.IN_APP})}}class To{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 fe.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?ze[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?ze[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?ze[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 Ao=({transport:t,$commonStore:e})=>{let r;const n=Q(!1),i=5e3,{client:o,queryKey:s}=t.createPromiseClient(an.AnalyticsService,{method:"send",params:[n]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const h=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...h,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(m){le.error(m,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{le.debug("mounted heartbeat"),r=a.subscribe(()=>{})},d=()=>{le.debug("enabled heartbeat"),n.set(!0),a.lc===0&&u()},c=()=>{le.debug("disabled heartbeat"),n.set(!1)};return{enable:d,disable:c,mount:u,unmount:()=>{le.debug("unmounted heartbeat"),a.off(),r?.(),r=void 0,c()}}},le=ve("analytics");class Eo{commonStore;notifications;polls;invitation;interactions;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ae(ie({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=Ao({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new wo(this),this.polls=new To(this),this.invitation=new vo(this),this.interactions=new bo(this);const{client:r}=e.analyticsTransport.createPromiseClient(an.AnalyticsService,{method:"send"});this.analyticsClient=r}connect=()=>{this.writeCommon("sessionId",Wt.nanoid()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,le.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,le.debug("analytics disconnected")};write=(e,r)=>{r&&this.analyticsClient.unary({message:{case:e,value:r}}).then(()=>{le.trace("send analytics success",e,r)}).catch(n=>{le.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",So[r]),r!==R.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Wt.nanoid()):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 Io=(t,e,r)=>{t.analytics=new Eo(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),r()};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Oo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fr={exports:{}},pr={exports:{}};function Co(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 _o=Co,Lo=_o;function mn(t,e,r){if(typeof t=="function"&&(r=e,e=t,t=null),r<1)throw new Error("fastqueue concurrency must be greater than 1");var n=Lo(ko),i=null,o=null,s=0,a=null,u={push:I,drain:z,saturated:z,pause:c,paused:!1,concurrency:r,running:d,resume:m,idle:b,length:f,getQueue:h,unshift:S,empty:z,kill:V,killAndDrain:G,error:W};return u;function d(){return s}function c(){u.paused=!0}function f(){for(var F=i,$=0;F;)F=F.next,$++;return $}function h(){for(var F=i,$=[];F;)$.push(F.value),F=F.next;return $}function m(){if(u.paused){u.paused=!1;for(var F=0;F<u.concurrency;F++)s++,P()}}function b(){return s===0&&u.length()===0}function I(F,$){var O=n.get();O.context=t,O.release=P,O.value=F,O.callback=$||z,O.errorHandler=a,s===u.concurrency||u.paused?o?(o.next=O,o=O):(i=O,o=O,u.saturated()):(s++,e.call(t,O.value,O.worked))}function S(F,$){var O=n.get();O.context=t,O.release=P,O.value=F,O.callback=$||z,O.errorHandler=a,s===u.concurrency||u.paused?i?(O.next=i,i=O):(i=O,o=O,u.saturated()):(s++,e.call(t,O.value,O.worked))}function P(F){F&&n.release(F);var $=i;$?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 V(){i=null,o=null,u.drain=z}function G(){i=null,o=null,u.drain(),u.drain=z}function W(F){a=F}}function z(){}function ko(){this.value=null,this.callback=z,this.next=null,this.release=z,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=z,t.errorHandler&&o(r,s),i.call(t.context,r,n),t.release(t)}}function Po(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(c,f){e.call(this,c).then(function(h){f(null,h)},f)}var i=mn(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(h,m){o(c,function(b,I){if(b){m(b);return}h(I)})});return f.catch(z),f}function u(c){var f=new Promise(function(h,m){s(c,function(b,I){if(b){m(b);return}h(I)})});return f.catch(z),f}function d(){if(i.idle())return new Promise(function(h){h()});var c=i.drain,f=new Promise(function(h){i.drain=function(){c(),h()}});return f}}pr.exports=mn;pr.exports.promise=Po;var vn=pr.exports,hr={exports:{}},Me=typeof Reflect=="object"?Reflect:null,$r=Me&&typeof Me.apply=="function"?Me.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},at;Me&&typeof Me.ownKeys=="function"?at=Me.ownKeys:Object.getOwnPropertySymbols?at=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:at=function(e){return Object.getOwnPropertyNames(e)};function Fo(t){console&&console.warn&&console.warn(t)}var bn=Number.isNaN||function(e){return e!==e};function N(){N.init.call(this)}hr.exports=N;hr.exports.once=$o;N.EventEmitter=N;N.prototype._events=void 0;N.prototype._eventsCount=0;N.prototype._maxListeners=void 0;var Vr=10;function Et(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(N,"defaultMaxListeners",{enumerable:!0,get:function(){return Vr},set:function(t){if(typeof t!="number"||t<0||bn(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Vr=t}});N.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};N.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||bn(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 Sn(t){return t._maxListeners===void 0?N.defaultMaxListeners:t._maxListeners}N.prototype.getMaxListeners=function(){return Sn(this)};N.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")$r(u,this,r);else for(var d=u.length,c=In(u,d),n=0;n<d;++n)$r(c[n],this,r);return!0};function wn(t,e,r,n){var i,o,s;if(Et(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=Sn(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,Fo(a)}return t}N.prototype.addListener=function(e,r){return wn(this,e,r,!1)};N.prototype.on=N.prototype.addListener;N.prototype.prependListener=function(e,r){return wn(this,e,r,!0)};function No(){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 Tn(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=No.bind(n);return i.listener=r,n.wrapFn=i,i}N.prototype.once=function(e,r){return Et(r),this.on(e,Tn(this,e,r)),this};N.prototype.prependOnceListener=function(e,r){return Et(r),this.prependListener(e,Tn(this,e,r)),this};N.prototype.removeListener=function(e,r){var n,i,o,s,a;if(Et(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():Do(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};N.prototype.off=N.prototype.removeListener;N.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 An(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?Ro(i):In(i,i.length)}N.prototype.listeners=function(e){return An(this,e,!0)};N.prototype.rawListeners=function(e){return An(this,e,!1)};N.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):En.call(t,e)};N.prototype.listenerCount=En;function En(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}N.prototype.eventNames=function(){return this._eventsCount>0?at(this._events):[]};function In(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Do(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ro(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function $o(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))}On(t,e,o,{once:!0}),e!=="error"&&Vo(t,i,{once:!0})})}function Vo(t,e,r){typeof t.on=="function"&&On(t,"error",e,r)}function On(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 Cn=hr.exports,It={},_n={},Ln=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},jo=Ln,Ot=function(){return jo()&&!!Symbol.toStringTag},Mo=Error,Uo=EvalError,qo=RangeError,xo=ReferenceError,kn=SyntaxError,Ct=TypeError,Bo=URIError,jr=typeof Symbol<"u"&&Symbol,Qo=Ln,Go=function(){return typeof jr!="function"||typeof Symbol!="function"||typeof jr("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Qo()},Ft={__proto__:null,foo:{}},Ko=Object,zo=function(){return{__proto__:Ft}.foo===Ft.foo&&!(Ft instanceof Ko)},Ho="Function.prototype.bind called on incompatible ",Wo=Object.prototype.toString,Jo=Math.max,Yo="[object Function]",Mr=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},Xo=function(e,r){for(var n=[],i=r||0,o=0;i<e.length;i+=1,o+=1)n[o]=e[i];return n},Zo=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r},es=function(e){var r=this;if(typeof r!="function"||Wo.apply(r)!==Yo)throw new TypeError(Ho+r);for(var n=Xo(arguments,1),i,o=function(){if(this instanceof i){var c=r.apply(this,Mr(n,arguments));return Object(c)===c?c:this}return r.apply(e,Mr(n,arguments))},s=Jo(0,r.length-n.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Zo(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=es,yr=Function.prototype.bind||ts,rs=Function.prototype.call,ns=Object.prototype.hasOwnProperty,is=yr,os=is.call(rs,ns),E,ss=Mo,as=Uo,us=qo,cs=xo,qe=kn,Ue=Ct,ls=Bo,Pn=Function,Nt=function(t){try{return Pn('"use strict"; return ('+t+").constructor;")()}catch{}},Ie=Object.getOwnPropertyDescriptor;if(Ie)try{Ie({},"")}catch{Ie=null}var Dt=function(){throw new Ue},ds=Ie?function(){try{return arguments.callee,Dt}catch{try{return Ie(arguments,"callee").get}catch{return Dt}}}():Dt,Fe=Go(),fs=zo(),U=Object.getPrototypeOf||(fs?function(t){return t.__proto__}:null),De={},ps=typeof Uint8Array>"u"||!U?E:U(Uint8Array),Oe={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?E:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?E:ArrayBuffer,"%ArrayIteratorPrototype%":Fe&&U?U([][Symbol.iterator]()):E,"%AsyncFromSyncIteratorPrototype%":E,"%AsyncFunction%":De,"%AsyncGenerator%":De,"%AsyncGeneratorFunction%":De,"%AsyncIteratorPrototype%":De,"%Atomics%":typeof Atomics>"u"?E:Atomics,"%BigInt%":typeof BigInt>"u"?E:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?E:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?E:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?E:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":ss,"%eval%":eval,"%EvalError%":as,"%Float32Array%":typeof Float32Array>"u"?E:Float32Array,"%Float64Array%":typeof Float64Array>"u"?E:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?E:FinalizationRegistry,"%Function%":Pn,"%GeneratorFunction%":De,"%Int8Array%":typeof Int8Array>"u"?E:Int8Array,"%Int16Array%":typeof Int16Array>"u"?E:Int16Array,"%Int32Array%":typeof Int32Array>"u"?E:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Fe&&U?U(U([][Symbol.iterator]())):E,"%JSON%":typeof JSON=="object"?JSON:E,"%Map%":typeof Map>"u"?E:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Fe||!U?E:U(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?E:Promise,"%Proxy%":typeof Proxy>"u"?E:Proxy,"%RangeError%":us,"%ReferenceError%":cs,"%Reflect%":typeof Reflect>"u"?E:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?E:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Fe||!U?E:U(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?E:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Fe&&U?U(""[Symbol.iterator]()):E,"%Symbol%":Fe?Symbol:E,"%SyntaxError%":qe,"%ThrowTypeError%":ds,"%TypedArray%":ps,"%TypeError%":Ue,"%Uint8Array%":typeof Uint8Array>"u"?E:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?E:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?E:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?E:Uint32Array,"%URIError%":ls,"%WeakMap%":typeof WeakMap>"u"?E:WeakMap,"%WeakRef%":typeof WeakRef>"u"?E:WeakRef,"%WeakSet%":typeof WeakSet>"u"?E:WeakSet};if(U)try{null.error}catch(t){var hs=U(U(t));Oe["%Error.prototype%"]=hs}var ys=function t(e){var r;if(e==="%AsyncFunction%")r=Nt("async function () {}");else if(e==="%GeneratorFunction%")r=Nt("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Nt("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&U&&(r=U(i.prototype))}return Oe[e]=r,r},Ur={__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"]},Ye=yr,ht=os,gs=Ye.call(Function.call,Array.prototype.concat),ms=Ye.call(Function.apply,Array.prototype.splice),qr=Ye.call(Function.call,String.prototype.replace),yt=Ye.call(Function.call,String.prototype.slice),vs=Ye.call(Function.call,RegExp.prototype.exec),bs=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ss=/\\(\\)?/g,ws=function(e){var r=yt(e,0,1),n=yt(e,-1);if(r==="%"&&n!=="%")throw new qe("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new qe("invalid intrinsic syntax, expected opening `%`");var i=[];return qr(e,bs,function(o,s,a,u){i[i.length]=a?qr(u,Ss,"$1"):s||o}),i},Ts=function(e,r){var n=e,i;if(ht(Ur,n)&&(i=Ur[n],n="%"+i[0]+"%"),ht(Oe,n)){var o=Oe[n];if(o===De&&(o=ys(n)),typeof o>"u"&&!r)throw new Ue("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new qe("intrinsic "+e+" does not exist!")},Xe=function(e,r){if(typeof e!="string"||e.length===0)throw new Ue("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Ue('"allowMissing" argument must be a boolean');if(vs(/^%?[^%]*%?$/,e)===null)throw new qe("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=ws(e),i=n.length>0?n[0]:"",o=Ts("%"+i+"%",r),s=o.name,a=o.value,u=!1,d=o.alias;d&&(i=d[0],ms(n,gs([0,1],d)));for(var c=1,f=!0;c<n.length;c+=1){var h=n[c],m=yt(h,0,1),b=yt(h,-1);if((m==='"'||m==="'"||m==="`"||b==='"'||b==="'"||b==="`")&&m!==b)throw new qe("property names with quotes must have matching quotes");if((h==="constructor"||!f)&&(u=!0),i+="."+h,s="%"+i+"%",ht(Oe,s))a=Oe[s];else if(a!=null){if(!(h in a)){if(!r)throw new Ue("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ie&&c+1>=n.length){var I=Ie(a,h);f=!!I,f&&"get"in I&&!("originalValue"in I.get)?a=I.get:a=a[h]}else f=ht(a,h),a=a[h];f&&!u&&(Oe[s]=a)}}return a},Fn={exports:{}},Rt,xr;function gr(){if(xr)return Rt;xr=1;var t=Xe,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Rt=e,Rt}var As=Xe,ut=As("%Object.getOwnPropertyDescriptor%",!0);if(ut)try{ut([],"length")}catch{ut=null}var _t=ut,Br=gr(),Es=kn,Ne=Ct,Qr=_t,Is=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Ne("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Ne("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Ne("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Ne("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Ne("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Ne("`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=!!Qr&&Qr(e,r);if(Br)Br(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 Es("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},er=gr(),Nn=function(){return!!er};Nn.hasArrayLengthDefineBug=function(){if(!er)return null;try{return er([],"length",{value:1}).length!==1}catch{return!0}};var Os=Nn,Cs=Xe,Gr=Is,_s=Os(),Kr=_t,zr=Ct,Ls=Cs("%Math.floor%"),ks=function(e,r){if(typeof e!="function")throw new zr("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Ls(r)!==r)throw new zr("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&Kr){var s=Kr(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!n)&&(_s?Gr(e,"length",r,!0,!0):Gr(e,"length",r)),e};(function(t){var e=yr,r=Xe,n=ks,i=Ct,o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||e.call(s,o),u=gr(),d=r("%Math.max%");t.exports=function(h){if(typeof h!="function")throw new i("a function is required");var m=a(e,s,arguments);return n(m,1+d(0,h.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(Fn);var mr=Fn.exports,Dn=Xe,Rn=mr,Ps=Rn(Dn("String.prototype.indexOf")),vr=function(e,r){var n=Dn(e,!!r);return typeof n=="function"&&Ps(e,".prototype.")>-1?Rn(n):n},Fs=Ot(),Ns=vr,tr=Ns("Object.prototype.toString"),Lt=function(e){return Fs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:tr(e)==="[object Arguments]"},$n=function(e){return Lt(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&tr(e)!=="[object Array]"&&tr(e.callee)==="[object Function]"},Ds=function(){return Lt(arguments)}();Lt.isLegacyArguments=$n;var Rs=Ds?Lt:$n,$s=Object.prototype.toString,Vs=Function.prototype.toString,js=/^\s*(?:function)?\*/,Vn=Ot(),$t=Object.getPrototypeOf,Ms=function(){if(!Vn)return!1;try{return Function("return function*() {}")()}catch{}},Vt,Us=function(e){if(typeof e!="function")return!1;if(js.test(Vs.call(e)))return!0;if(!Vn){var r=$s.call(e);return r==="[object GeneratorFunction]"}if(!$t)return!1;if(typeof Vt>"u"){var n=Ms();Vt=n?$t(n):!1}return $t(e)===Vt},jn=Function.prototype.toString,Ve=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,rr,ct;if(typeof Ve=="function"&&typeof Object.defineProperty=="function")try{rr=Object.defineProperty({},"length",{get:function(){throw ct}}),ct={},Ve(function(){throw 42},null,rr)}catch(t){t!==ct&&(Ve=null)}else Ve=null;var qs=/^\s*class\b/,nr=function(e){try{var r=jn.call(e);return qs.test(r)}catch{return!1}},jt=function(e){try{return nr(e)?!1:(jn.call(e),!0)}catch{return!1}},lt=Object.prototype.toString,xs="[object Object]",Bs="[object Function]",Qs="[object GeneratorFunction]",Gs="[object HTMLAllCollection]",Ks="[object HTML document.all class]",zs="[object HTMLCollection]",Hs=typeof Symbol=="function"&&!!Symbol.toStringTag,Ws=!(0 in[,]),ir=function(){return!1};if(typeof document=="object"){var Js=document.all;lt.call(Js)===lt.call(document.all)&&(ir=function(e){if((Ws||!e)&&(typeof e>"u"||typeof e=="object"))try{var r=lt.call(e);return(r===Gs||r===Ks||r===zs||r===xs)&&e("")==null}catch{}return!1})}var Ys=Ve?function(e){if(ir(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ve(e,null,rr)}catch(r){if(r!==ct)return!1}return!nr(e)&&jt(e)}:function(e){if(ir(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(Hs)return jt(e);if(nr(e))return!1;var r=lt.call(e);return r!==Bs&&r!==Qs&&!/^\[object HTML/.test(r)?!1:jt(e)},Xs=Ys,Zs=Object.prototype.toString,Mn=Object.prototype.hasOwnProperty,ea=function(e,r,n){for(var i=0,o=e.length;i<o;i++)Mn.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)},ra=function(e,r,n){for(var i in e)Mn.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},na=function(e,r,n){if(!Xs(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=n),Zs.call(e)==="[object Array]"?ea(e,r,i):typeof e=="string"?ta(e,r,i):ra(e,r,i)},Un=na,ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],Mt=ia,oa=typeof globalThis>"u"?dr:globalThis,qn=function(){for(var e=[],r=0;r<Mt.length;r++)typeof oa[Mt[r]]=="function"&&(e[e.length]=Mt[r]);return e},gt=Un,sa=qn,Hr=mr,br=vr,dt=_t,aa=br("Object.prototype.toString"),xn=Ot(),Wr=typeof globalThis>"u"?dr:globalThis,or=sa(),Sr=br("String.prototype.slice"),Ut=Object.getPrototypeOf,ua=br("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},mt={__proto__:null};xn&&dt&&Ut?gt(or,function(t){var e=new Wr[t];if(Symbol.toStringTag in e){var r=Ut(e),n=dt(r,Symbol.toStringTag);if(!n){var i=Ut(r);n=dt(i,Symbol.toStringTag)}mt["$"+t]=Hr(n.get)}}):gt(or,function(t){var e=new Wr[t],r=e.slice||e.set;r&&(mt["$"+t]=Hr(r))});var ca=function(e){var r=!1;return gt(mt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Sr(i,1))}catch{}}),r},la=function(e){var r=!1;return gt(mt,function(n,i){if(!r)try{n(e),r=Sr(i,1)}catch{}}),r},da=function(e){if(!e||typeof e!="object")return!1;if(!xn){var r=Sr(aa(e),8,-1);return ua(or,r)>-1?r:r!=="Object"?!1:la(e)}return dt?ca(e):null},vt=Un,fa=qn,Jr=mr,wr=vr,ft=_t,pa=wr("Object.prototype.toString"),Bn=Ot(),Yr=typeof globalThis>"u"?dr:globalThis,sr=fa(),Tr=wr("String.prototype.slice"),qt=Object.getPrototypeOf,ha=wr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},bt={__proto__:null};Bn&&ft&&qt?vt(sr,function(t){var e=new Yr[t];if(Symbol.toStringTag in e){var r=qt(e),n=ft(r,Symbol.toStringTag);if(!n){var i=qt(r);n=ft(i,Symbol.toStringTag)}bt["$"+t]=Jr(n.get)}}):vt(sr,function(t){var e=new Yr[t],r=e.slice||e.set;r&&(bt["$"+t]=Jr(r))});var ya=function(e){var r=!1;return vt(bt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Tr(i,1))}catch{}}),r},ga=function(e){var r=!1;return vt(bt,function(n,i){if(!r)try{n(e),r=Tr(i,1)}catch{}}),r},ma=function(e){if(!e||typeof e!="object")return!1;if(!Bn){var r=Tr(pa(e),8,-1);return ha(sr,r)>-1?r:r!=="Object"?!1:ga(e)}return ft?ya(e):null},va=ma,ba=function(e){return!!va(e)};(function(t){var e=Rs,r=Us,n=da,i=ba;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 h=o(BigInt.prototype.valueOf);if(a)var m=o(Symbol.prototype.valueOf);function b(y,Jn){if(typeof y!="object")return!1;try{return Jn(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=i;function I(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=I;function S(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||p(y)}t.isArrayBufferView=S;function P(y){return n(y)==="Uint8Array"}t.isUint8Array=P;function V(y){return n(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=V;function G(y){return n(y)==="Uint16Array"}t.isUint16Array=G;function W(y){return n(y)==="Uint32Array"}t.isUint32Array=W;function F(y){return n(y)==="Int8Array"}t.isInt8Array=F;function $(y){return n(y)==="Int16Array"}t.isInt16Array=$;function O(y){return n(y)==="Int32Array"}t.isInt32Array=O;function Z(y){return n(y)==="Float32Array"}t.isFloat32Array=Z;function ee(y){return n(y)==="Float64Array"}t.isFloat64Array=ee;function Ce(y){return n(y)==="BigInt64Array"}t.isBigInt64Array=Ce;function be(y){return n(y)==="BigUint64Array"}t.isBigUint64Array=be;function oe(y){return u(y)==="[object Map]"}oe.working=typeof Map<"u"&&oe(new Map);function kt(y){return typeof Map>"u"?!1:oe.working?oe(y):y instanceof Map}t.isMap=kt;function ye(y){return u(y)==="[object Set]"}ye.working=typeof Set<"u"&&ye(new Set);function Qe(y){return typeof Set>"u"?!1:ye.working?ye(y):y instanceof Set}t.isSet=Qe;function _e(y){return u(y)==="[object WeakMap]"}_e.working=typeof WeakMap<"u"&&_e(new WeakMap);function Pt(y){return typeof WeakMap>"u"?!1:_e.working?_e(y):y instanceof WeakMap}t.isWeakMap=Pt;function Le(y){return u(y)==="[object WeakSet]"}Le.working=typeof WeakSet<"u"&&Le(new WeakSet);function se(y){return Le(y)}t.isWeakSet=se;function ke(y){return u(y)==="[object ArrayBuffer]"}ke.working=typeof ArrayBuffer<"u"&&ke(new ArrayBuffer);function Ze(y){return typeof ArrayBuffer>"u"?!1:ke.working?ke(y):y instanceof ArrayBuffer}t.isArrayBuffer=Ze;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 p(y){return typeof DataView>"u"?!1:l.working?l(y):y instanceof DataView}t.isDataView=p;var g=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function w(y){return u(y)==="[object SharedArrayBuffer]"}function L(y){return typeof g>"u"?!1:(typeof w.working>"u"&&(w.working=w(new g)),w.working?w(y):y instanceof g)}t.isSharedArrayBuffer=L;function k(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=k;function A(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=A;function _(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=_;function D(y){return u(y)==="[object Generator]"}t.isGeneratorObject=D;function K(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=K;function Se(y){return b(y,d)}t.isNumberObject=Se;function et(y){return b(y,c)}t.isStringObject=et;function Pe(y){return b(y,f)}t.isBooleanObject=Pe;function tt(y){return s&&b(y,h)}t.isBigIntObject=tt;function Ir(y){return a&&b(y,m)}t.isSymbolObject=Ir;function Hn(y){return Se(y)||et(y)||Pe(y)||tt(y)||Ir(y)}t.isBoxedPrimitive=Hn;function Wn(y){return typeof Uint8Array<"u"&&(Ze(y)||L(y))}t.isAnyArrayBuffer=Wn,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})(_n);var Sa=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},ar={exports:{}};typeof Object.create=="function"?ar.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:ar.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 wa=ar.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(p){for(var g=Object.keys(p),w={},L=0;L<g.length;L++)w[g[L]]=Object.getOwnPropertyDescriptor(p,g[L]);return w},r=/%[sdj%]/g;t.format=function(l){if(!F(l)){for(var p=[],g=0;g<arguments.length;g++)p.push(s(arguments[g]));return p.join(" ")}for(var g=1,w=arguments,L=w.length,k=String(l).replace(r,function(_){if(_==="%%")return"%";if(g>=L)return _;switch(_){case"%s":return String(w[g++]);case"%d":return Number(w[g++]);case"%j":try{return JSON.stringify(w[g++])}catch{return"[Circular]"}default:return _}}),A=w[g];g<L;A=w[++g])V(A)||!ee(A)?k+=" "+A:k+=" "+s(A);return k},t.deprecate=function(l,p){if(typeof T<"u"&&T.noDeprecation===!0)return l;if(typeof T>"u")return function(){return t.deprecate(l,p).apply(this,arguments)};var g=!1;function w(){if(!g){if(T.throwDeprecation)throw new Error(p);T.traceDeprecation?console.trace(p):console.error(p),g=!0}return l.apply(this,arguments)}return w};var n={},i=/^$/;if(T.env.NODE_DEBUG){var o=T.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 p=T.pid;n[l]=function(){var g=t.format.apply(t,arguments);console.error("%s %d: %s",l,p,g)}}else n[l]=function(){};return n[l]};function s(l,p){var g={seen:[],stylize:u};return arguments.length>=3&&(g.depth=arguments[2]),arguments.length>=4&&(g.colors=arguments[3]),P(p)?g.showHidden=p:p&&t._extend(g,p),O(g.showHidden)&&(g.showHidden=!1),O(g.depth)&&(g.depth=2),O(g.colors)&&(g.colors=!1),O(g.customInspect)&&(g.customInspect=!0),g.colors&&(g.stylize=a),c(g,l,g.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,p){var g=s.styles[p];return g?"\x1B["+s.colors[g][0]+"m"+l+"\x1B["+s.colors[g][1]+"m":l}function u(l,p){return l}function d(l){var p={};return l.forEach(function(g,w){p[g]=!0}),p}function c(l,p,g){if(l.customInspect&&p&&oe(p.inspect)&&p.inspect!==t.inspect&&!(p.constructor&&p.constructor.prototype===p)){var w=p.inspect(g,l);return F(w)||(w=c(l,w,g)),w}var L=f(l,p);if(L)return L;var k=Object.keys(p),A=d(k);if(l.showHidden&&(k=Object.getOwnPropertyNames(p)),be(p)&&(k.indexOf("message")>=0||k.indexOf("description")>=0))return h(p);if(k.length===0){if(oe(p)){var _=p.name?": "+p.name:"";return l.stylize("[Function"+_+"]","special")}if(Z(p))return l.stylize(RegExp.prototype.toString.call(p),"regexp");if(Ce(p))return l.stylize(Date.prototype.toString.call(p),"date");if(be(p))return h(p)}var D="",K=!1,Se=["{","}"];if(S(p)&&(K=!0,Se=["[","]"]),oe(p)){var et=p.name?": "+p.name:"";D=" [Function"+et+"]"}if(Z(p)&&(D=" "+RegExp.prototype.toString.call(p)),Ce(p)&&(D=" "+Date.prototype.toUTCString.call(p)),be(p)&&(D=" "+h(p)),k.length===0&&(!K||p.length==0))return Se[0]+D+Se[1];if(g<0)return Z(p)?l.stylize(RegExp.prototype.toString.call(p),"regexp"):l.stylize("[Object]","special");l.seen.push(p);var Pe;return K?Pe=m(l,p,g,A,k):Pe=k.map(function(tt){return b(l,p,g,A,tt,K)}),l.seen.pop(),I(Pe,D,Se)}function f(l,p){if(O(p))return l.stylize("undefined","undefined");if(F(p)){var g="'"+JSON.stringify(p).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return l.stylize(g,"string")}if(W(p))return l.stylize(""+p,"number");if(P(p))return l.stylize(""+p,"boolean");if(V(p))return l.stylize("null","null")}function h(l){return"["+Error.prototype.toString.call(l)+"]"}function m(l,p,g,w,L){for(var k=[],A=0,_=p.length;A<_;++A)Le(p,String(A))?k.push(b(l,p,g,w,String(A),!0)):k.push("");return L.forEach(function(D){D.match(/^\d+$/)||k.push(b(l,p,g,w,D,!0))}),k}function b(l,p,g,w,L,k){var A,_,D;if(D=Object.getOwnPropertyDescriptor(p,L)||{value:p[L]},D.get?D.set?_=l.stylize("[Getter/Setter]","special"):_=l.stylize("[Getter]","special"):D.set&&(_=l.stylize("[Setter]","special")),Le(w,L)||(A="["+L+"]"),_||(l.seen.indexOf(D.value)<0?(V(g)?_=c(l,D.value,null):_=c(l,D.value,g-1),_.indexOf(`
|
|
2
|
+
`+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(J.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(J.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(J.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(J.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(J.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(J.Failed),this.state.setValue("error",e),this.reconnect();return}this.disconnect()}}}const hi=new Set([M.Code.Unknown,M.Code.Internal,M.Code.DeadlineExceeded,M.Code.ResourceExhausted,M.Code.FailedPrecondition,M.Code.Unavailable,M.Code.DataLoss]),Lr=ve("grpc:retry"),yi=t=>async e=>{const r=e.contextValues.get(Xt.retryAttempts),n=300,i=e.contextValues.get(Xt.retryDelay);if(e.stream||r===0)return t(e);Lr.trace({url:e.url,attempts:r,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Lr.trace({attempt:o,error:s},"retry attempt");const a=M.ConnectError.from(s);if(o>=r||!(a instanceof M.ConnectError)||!hi.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))}},Xt={retryAttempts:M.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:M.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},gi=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=Wt.nanoid();return localStorage.setItem("sl-device-id",e),e},mi=()=>navigator.userAgentData?.platform||navigator.platform;class kr{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 Ae(ie({"sl-device-id":gi(),"sl-device-os":mi()}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map;const[n,i,o]=Cr.nanoquery({dedupeTime:r?.dedupeTime,refetchInterval:r?.refetchInterval});this.nanoquery={createFetcherStore:n,createMutatorStore:i,utils:o},this.transport=Or.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors,useBinaryFormat:!0}),this.streamTransport=Or.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors,useBinaryFormat:!0})}addSubscription=(e,r,n)=>{const i=this.subscriptions.get(r);if(i)return i;const o=new pi(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]=Cr.nanoquery({dedupeTime:1e3*60*5,refetchInterval:1e3*60*5});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.createPromiseClient(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.createPromiseClient(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 h=Xt[f];c.set(h,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(fi()),this.opts?.retryable&&this.interceptors.push(yi)}}const vi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Xn.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""}}})},bi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.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})},Si=(t,e)=>{const{queryKey:r,client:n}=e.createPromiseClient(lr.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:()=>n.me({})})},wi=t=>{const{client:e,createRequestOptions:r}=t.createPromiseClient(lr.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})},Ti=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.get({})).data?.attributes})},Ai=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.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}})},Ei=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Je.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.getOrganizationAdvertising({})).data?.attributes})},Ii=(t,e,r)=>{t.transport=new kr(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0}),t.analyticsTransport=new kr(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()};class Tt{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()||"";this.storage.setItem(this.generateKey(e),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 ae;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(ae||(ae={}));class Re extends Tt{constructor(){super("user")}setSchema=e=>{this.write(ae.SCHEMA,e)};getSchema=()=>this.read(ae.SCHEMA);setToken=e=>{this.write(ae.TOKEN,e)};getToken=()=>this.read(ae.TOKEN);setExternalToken=e=>{this.write(ae.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(ae.EXTERNAL_TOKEN);removeToken=()=>{this.remove(ae.TOKEN)}}var ce;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(ce||(ce={}));const Oi=t=>{const e=new Re,r=new H(Q(e.getExternalToken()),"userKey"),n=new H(Q(e.getToken()),"userToken"),i=new pe(Si(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 pe(Ti(n.getStore(),t),"userSettings");return{userKey:r,userToken:n,user:i,userSettings:o}},Ci=t=>{const e=new H(Q(void 0),"providerStreamId"),r=new pe(vi(e.getStore(),t),"slStreamId",i=>i?.data),n=new pe(bi(r.getAtomStore(),t),"streamSettings");return r.getAtomStore().listen(i=>{(i===""||i===void 0)&&n.getStore().mutate(void 0)}),{providerStreamId:e,slStreamId:r,streamSettings:n}},_i=t=>{const e=new H(Q(void 0),"enabled"),r=new H(Q(ce.DISABLED),"status"),n=new pe(Ai(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new pe(Ei(n.getAtomStore(),t),"organizationAdvertising"),o=Oi(t),s=Ci(t);return{enabled:e,status:r,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:n,organizationAdvertising:i}};class Li extends wt{stores;constructor(e){const r=_i(e),n=ci(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 ki=(t,e,r)=>{t.store=new Li(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.storeUnsubscribe=()=>{t.store.unsubscribe()},r()},Pi=t=>{const{client:e}=t.createPromiseClient(sn.Leaderboard,{method:"list"});return r=>e.list(r)},pn=t=>{const{client:e}=t.createPromiseClient(sn.Leaderboard,{method:"summary"});return r=>e.summary(r)},Fi=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(lr.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.getFriends({})).data:[]})},Ni=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.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})},Di=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.Feed,{method:"syncQuestion",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.syncQuestion({filter:{eventId:s}})).data?.attributes:void 0,dedupeTime:1e3*60*10,refetchInterval:0})},Ri=(t,e)=>{const{client:r}=e.createStreamClient(me.Feed),n=X.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{n.set({eventId:o,feedId:""})}),e.addSubscription(r.subscription,n,{name:"feedSubscription"})},$i=(t,e)=>{const{client:r}=e.createStreamClient(me.Feed);return e.addSubscription(r.questionSubscription,{questionId:t},{name:"questionSubscription"})},Zt=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(me.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})},Vi=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(me.Feed,{method:"list",params:[t,e]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>a?(await n.list({eventId:a,filter:{types:u===Ee.ALLOWED?[]:[C.QuestionType.FACTOID,C.QuestionType.PROMOTION,C.QuestionType.TWEET],statuses:[C.QuestionStatus.ACTIVE,C.QuestionStatus.RESOLVED]}})).data:[],dedupeTime:0,refetchInterval:0})},ji=(t,e,r)=>{const n=X.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=X.batched(n,a=>a&&a.type==="question"?a.id:void 0),o=Zt(i,t);return{$store:n,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,d=(c,f)=>{if(!c||!f)return c||f||[];const h=[];for(let m=0;m<c.length;m++)h.push({...c[m],...f[m],correct:c[m].correct,youVoted:c[m].youVoted,pointsEarned:c[m].pointsEarned});return h};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:d(u?.answers,a?.answers)})}}};var Ee;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Ee||(Ee={}));class Mi{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;moderationId;moderation;feedSubscription;questionSubscription;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ve("gamification-background"),this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new H(Q(void 0),"moderationId").getStore(),this.interactiveAllowed=new H(Q(Ee.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new H(Q(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new pe(Ni(this.slStreamId,e.transport),"gamification:moderation"),this.feedList=new pe(Vi(this.slStreamId,this.interactiveAllowed,e.transport),"gamification:feedList"),this.activeQuestionId=Di(this.slStreamId,e.transport),this.openedQuestion=ji(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(r=>{this.log.debug({item:r},"received question"),r?.questionId?(this.questionSubscription=$i(r.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",n=>{this.openedQuestion.updateExtendedQuestion(n.data?.attributes?.question)}),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=Ri(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",r=>{const n=this.activeQuestionId.get().data?.question?.id,i=r.data?.attributes?.question;i&&(n&&i.status===C.QuestionStatus.RESOLVED&&i.id!==n||this.activeQuestionId.mutate(r.data?.attributes))})),this.cancels.add(this.feedSubscription.addListener("moderation update",r=>{window.requestAnimationFrame(()=>{r.data?.attributes?.question===void 0&&r.data?.attributes?.moderation&&this.moderation.invalidate()})})),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 r of this.cancels)r(),this.cancels.delete(r)})}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 Ui{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ve("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}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")},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 pt;(function(t){t.OPENED="opened"})(pt||(pt={}));class qi extends Tt{constructor(){super("notification")}setOpened=e=>{this.write(pt.OPENED,e,"true")};isOpened=e=>this.read(pt.OPENED,e);clearNotification=()=>{this.clear()}}var ge;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(ge||(ge={}));class xi{queue;storage;constructor(e={}){this.storage=new qi,this.queue=new Ui({concurrency:1,animationDelay:1600,...e})}add=e=>{if(!this.storage.isOpened(e.id)){if(e.data&&e.emitEvent){const n=e.action;e.action=(...i)=>{n&&n(...i),fe.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===ge.ONBOARDING)return n;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const Bi=(t,e,r)=>{t.notifications=new xi(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 We;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(We||(We={}));const Qi=async(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(me.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(We.ALREADY_VOTED):new Error(We.UNKNOWN)}},Gi=(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(me.Feed,{method:"submitInplay"}),i=n({retryAttempts:0});return r.submitInplay({data:{eventId:+e}},{contextValues:i})};var $e;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io"})($e||($e={}));class hn extends Tt{constructor(){super("gamification")}saveOnboardingStatus=({userId:e,eventId:r,organizationId:n},i)=>{this.write($e.ONBOARDING,n,e,r,i)};getOnboardingStatus=({userId:e,eventId:r,organizationId:n})=>this.read($e.ONBOARDING,n,e,r);setOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{const i=this.generateKey([$e.ONBOARDING_IO,n,e,r]);window.sessionStorage.setItem(i,"1")};getOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{const i=this.generateKey([$e.ONBOARDING_IO,n,e,r]);return window.sessionStorage.getItem(i)}}const Ki={pageSize:10},zi=(t,e,r,n,i)=>{let o=0;const s=Q({pageSize:i?.pageSize||Ki.pageSize,page:0}),a=ie({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Pi(t),d=async()=>{const h=e.get(),m=n.getStore().get().data?.map(b=>b.slId)||[];if(h&&m?.length){const b=r.get();b&&m.push(b),a.setKey("loading",!0),a.setKey("data",[]);const S=await u({eventId:h,usersIds:m});a.set({data:S.data.map((P,V)=>({...P.attributes,friendsRank:V+1})),hasMore:!1,key:Date.now(),loading:!1}),S.meta&&(o=Math.round(S.meta.count/S.meta.pageSize))}},c=()=>{d()},f=h=>{const m=s.get(),b=h||m.page+1;b<=o&&s.set({...m,page:b})};return X.onMount(a,()=>{const h=e.listen(d),m=n.listen(d);return()=>{h(),m()}}),{$store:a,fetchMore:f,invalidate:c}};class Hi extends Tt{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Pr="sldl",At="sldl_uid",yn="sldl_eid",gn="sldl_e_eid",Wi=new Set([At,yn,gn]),Fr=t=>{const e={},r={};for(const[n,i]of t)Wi.has(n)?e[n]=i:r[n]=i;return{result:e,remain:r}},Ji=({hash:t,search:e})=>{if(t&&t.includes(Pr)){const r=new URLSearchParams(t.substr(1));return{hash:Fr(r)}}if(e&&e.includes(Pr)){const r=new URLSearchParams(e);return{search:Fr(r)}}return null},Nr=ve("deep_link"),ne={debug:(...t)=>{Nr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Nr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Yi=(t,e)=>{const{hash:r,search:n}=window.location;if(ne.debug({hash:r,search:n},"get deep link data from"),r||n){const i=Ji({hash:r,search:n});if(ne.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()}`,ne.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()}`,ne.debug({updatedSearch:c},"update search")),window.history.replaceState(null,"",window.location.pathname+c+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},Xi=(t,e,r)=>{const n=new Hi,i=n.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ne.debug(a)}t.deepLink={$store:new Ae(ie(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ne.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?.[At]: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")&&ne.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ne.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ne.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ne.trace("called handler"),u(a)}catch(d){console.error(d)}};Yi(t.deepLink.$store,s),r()},Zi=ve("bypass");class eo extends ui{$coreStore;deepLink;transport;bypassLogin;constructor(e,r,n){super(),this.$coreStore=e,this.deepLink=n,this.transport=r,this.bypassLogin=wi(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?.[At];Zi.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(s),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 Re().clear()};softLogout=()=>{const e=new Re;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=()=>{const e=new Re,r=e.getToken(),n=e.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(n),r)return this.saveUser(r,""),this.me().then(i=>{if(i?.id){const o=i.id;this.saveUser(r,o)}});if(n&&!r){const i=e.getSchema();i&&n&&this.login(i,n).catch(()=>{this.logout()})}};saveUser=(e,r)=>{this.transport.setAuth(e,r),this.$coreStore.getValues().userToken.setValue(e),new Re().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 Ge=new Re,to=(t,e,r)=>{t.auth=new eo(t.store,t.transport,t.deepLink),t.stores.status.listen(n=>{n===ce.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(n,i)=>{if(!(Ge.getSchema()===n&&Ge.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(n,i),Ge.setSchema(n),Ge.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),Ge.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),r()},Dr=ve("video_player"),it={debug:(...t)=>{Dr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Dr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},ro=(t,e,r)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=n=>{it.trace("adding video player controller"),t.videoPlayer.controllers.add(n)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=n=>{it.trace("removing video player controller"),t.videoPlayer.controllers.delete(n)},t.sdk.controlVideoPlayer=n=>{it.trace("controlling video player");for(const i of t.videoPlayer.controllers){it.trace("calling video player controller");try{i(n)}catch(o){console.error(o)}}},r()},no=(t,e,r)=>{const n={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),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(ce.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(ce.READY),{enabled:!!a}):(t.stores.status.setValue(ce.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(ce.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(ce.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(Je.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s,a)=>s?(await r.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes:{},dedupeTime:1e3*60*60*24,refetchInterval:0})},oo=(t,{web:e,mobile:r})=>{const{client:n}=t.createPromiseClient(Zn.LinksClient,{method:"generate"});return n.generate({web:e,mobile:r})},Rr=(t,e)=>{const r=new URLSearchParams(t);for(const[n,i]of Object.entries(e))r.append(n,i);return r.toString()},so=(t,e,r,n)=>{const i=ie({});return X.onMount(i,()=>io(t,[e,r]).subscribe(async({data:a,error:u,loading:d})=>{const c=u?"https://masters.com":a?.url,f=n.get()||"",h=e.get()||"",m=r.get()||"",b={[At]:f,[yn]:h,[gn]:m};if(!d&&c){i.setKey("loading",!0);let I=window.location.search,S=window.location.hash;I&&S||S?I=`?${Rr(I,b)}`:S=`#${Rr("",b)}`;const P=window.location.origin+window.location.pathname+I+S,V=await oo(t,{web:P,mobile:c});i.set({data:V.data?.link,loading:!1})}else i.setKey("loading",!0)})),{$store:i,fetch}};var x;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(x||(x={}));const ao=(t,e,r,n)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&r.add({type:ge.ONBOARDING,id:o,action:t.openFeature,persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:C.QuestionType.UNSET,onboarding:{...i,instantOpen:!n.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})}}})},ot=(t,e,r,n,i,o)=>{try{const s=e.userId.get();if(!s)return;if(i.getOnboardingStatus({userId:s,organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""})===x.Completed){t.set(x.Completed);for(const h of o)h();return}const u=e.moderation.getStore().value?.data,d=r.featureSettings.get().inplayGame;if(u===void 0||d===void 0)return;const c=u?.options?.onboardingEnabled,f=d?.titleCard?.optIn;c?f?t.set(x.Required):t.set(x.Optional):(f?t.set(x.Unavailable):t.set(x.Disabled),n.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(s){console.error(s)}},uo=(t,e,r,n)=>{let i=!1;const o=new hn,s=Q(x.Unset);s.subscribe(d=>{d!==x.Unset&&((d===x.Optional||d===x.Required)&&i===!1&&(ao(t,e,n,o),i=!0),d===x.Completed&&e.activeQuestionId.invalidate(),o.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const a=[];return ot(s,e,t,n,o,a),s.get()!==x.Completed&&(a.push(e.userId.listen(d=>{d&&ot(s,e,t,n,o,a)})),a.push(e.moderation.listen(d=>{d.data&&ot(s,e,t,n,o,a)})),a.push(t.featureSettings.listen(d=>{d&&ot(s,e,t,n,o,a)}))),{$store:s,submitInplay:async()=>{const d=e.slStreamId.get();if(d){await Gi(r,d),s.set(x.Completed),o.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:d},x.Completed),fe.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const c=e.getCurrentSessionId({prefix:"onboarding"});n.close(c)}}}},co=(t,e,r,n)=>{const i=ie(void 0),o=pn(n),s=async()=>{const u=t.get(),d=e.get(),c=r.getStore().get().data?.map(m=>m.slId);if(!c)return;const f={eventId:u,userId:d,usersIds:[...c,d]},h=await o(f);i.set(h.data?.attributes)},a=()=>{s()};return X.onMount(i,()=>{const u=t.listen(s),d=r.listen(s),c=e.listen(s);return()=>{u(),d(),c()}}),{$store:i,invalidate:a}},lo=async(t,e,r,n,i)=>{const o=pn(i),s=t.get(),a=e.get(),u=r.getStore().get().data?.map(h=>h.slId)||[],d={eventId:s,userId:n,usersIds:[...u,a]};return(await o(d)).data?.attributes?.summary},fo=new Set([C.QuestionType.POLL,C.QuestionType.PREDICTION,C.QuestionType.TRIVIA]);class po extends fn{userSummary;feedList;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;constructor(e,r,n){super(e,r),this.background=new Mi(n),this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=new hn,this.feedList=this.background.feedList,this.friends=new pe(Fi(this.background.userId,n.transport),"gamification:friends"),this.currentUserId=this.background.userId,this.openedUser=Q(void 0),this.leaderboardId=new H(Q(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.onboardingStatus=uo(this,this.background,n.transport,n.notifications),this.notifications=n.notifications,this.transport=n.transport,this.closeFeature=()=>n.sdk.closeFeature(!0),this.openFeature=()=>n.sdk.openFeature(R.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=so(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),this.leaderboardList=zi(this.transport,this.background.slStreamId,this.background.userId,this.friends),this.connect(),this.cancels.add(this.userSummary.$store.listen((i,o)=>{o?.summary&&i?.summary&&this.leaderboardList.invalidate()})),this.cancels.add(this.background.activeQuestionId.listen(this.showInApp)),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)),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()===Ee.ALLOWED}checkInteractiveFlag=()=>{const e=this.onboardingStatus.$store.get(),r=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,n=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===x.Completed,o=!r||i||n!==!0;this.background.interactiveAllowed.set(o?Ee.ALLOWED:Ee.DISALLOWED)};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===C.QuestionStatus.RESOLVED&&o===C.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),d=[...this.feedList.getValues().data||[]],c=d.findIndex(G=>G.id===s),f=d[c];let h=f?.attributes?.attributes?.value?.answerId;const m=Zt(s,this.transport),b=m.subscribe(()=>{});await m.get().promise;const I=m.get().data;b(),window.requestAnimationFrame(()=>{m.invalidate()}),h||(h=I?.answers.find(({youVoted:G})=>G)?.id);const S=a.find(({correct:G})=>G),P=h?a.find(({id:G})=>G===h):void 0,V=!!P?.correct;if(f&&d[c]?.attributes?.attributes.case==="question"){try{d[c].attributes.attributes.value.answerId=h,d[c].attributes.attributes.value.openForVoting=!1,h&&(d[c].attributes.attributes.value.status=V?rt.PickHistoryStatus.WON:rt.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(d)}if(!P||!S)return;this.openedQuestionId.get()?.questionId!==r.id&&this.notifications.add({type:ge.QUESTION_RESOLVED,action:()=>this.openQuestion(r.id,n),close:()=>this.closeQuestion(s),autoHideDuration:V?15e3:12e3,id:u,emitEvent:!1,data:{questionId:s,questionType:C.QuestionType.PREDICTION,question:{title:V?`Congratulations! You answered correctly! You won ${S.points} pts!`:`Better luck next time! Correct: ${S?.text}!`,votedAnswer:{title:P?.text,points:P?.points},correctAnswerTitle:S?.text,correct:!!V,predictionResult:i===C.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.status!==C.QuestionStatus.ACTIVE&&n.attributes.status!==C.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),fe.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")};submitAnswer=async(e,r)=>{const n=Zt(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){fe.emit("poll",{action:"voted",payload:{questionId:e,questionType:c.questionType}});const f=n.get().data;if(i(),f){const h=f.answers.find(S=>S.correct===!0),m=f.answers.findIndex(S=>S.id===r),b=f.answers[m],I=f.answers.every(({percentageDecimal:S},P)=>S===o?.answers[P].percentageDecimal);a[u].attributes.attributes.value.answerId=r,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=b?.text||"",h&&(a[u].attributes.attributes.value.status=h.id===r?rt.PickHistoryStatus.WON:rt.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),f.answers[m].correct=h?.id===r,f.answers[m].youVoted=!0,I&&f.answers.forEach(S=>{S.percentageDecimal=0}),h?.id===r&&(f.answers[m].pointsEarned=f.status===C.QuestionStatus.RESOLVED?0:h.points),n.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Qi(this.transport,{questionId:e,answerId:r}),s()}catch(a){if(a.message===We.ALREADY_VOTED){this.userSummary.invalidate();const u=n.subscribe(()=>{});n.invalidate(),u()}throw a}};openQuestion=(e,r)=>{if(!e)return()=>{};this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let n=r?.attributes?.type;return n||(n=(this.feedList.getStore().value?.data||[]).find(o=>o.id===e)?.attributes?.type),fe.emit("poll",{action:"opened",payload:{questionId:e,questionType:n,questionOpenedFrom:r?.openedFrom}}),this.background.openQuestion(e,r)};closeQuestion=e=>this.background.closeQuestion(e);openUser=async e=>{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 lo(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!==x.Unset&&e.data.question?.id!==void 0&&e.data.question.notification!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==C.SilenceSetting.ON&&e.data.question.status===C.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(fo.has(e.data.question.type))this.isInteractiveAllowed&&this.notifications.add({type:ge.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}}});else if(e.data.question.type===C.QuestionType.FACTOID){const n=e.data.question.options?.options.value,i={heading:e.data.question.notification.title,body:e.data.question.notification.body,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:ge.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:i}})}else if(e.data.question.type===C.QuestionType.TWEET){const n=e.data.question.options?.options.value,i={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};this.notifications.add({type:ge.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:i}})}}}}const ho={[R.SdkOverlayType.GAMES]:!0};class yo extends fn{constructor(e,r){super(e,r)}}const go=(t,e,r)=>t.type===R.SdkOverlayType.GAMES?new po(t,e,r):new yo(t,e),mo=(t,e,r)=>{t.features=new Map,t.sdk.featuresList=new H(Q(new Set),"features-list"),t.activeFeature=new H(Q(R.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.activeFeature.setValue(n)},t.sdk.closeFeature=(n=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(R.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=ue.ORGANIZATION)=>{if(n.type in ho&&!t.features.has(n.type)){const o=go(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,ue.ORGANIZATION)},t.stores.providerStreamId.listen(n=>{n||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const n=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===ue.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(ue.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{n(ue.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},r()};class vo{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 fe.listen(r)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_ACCEPTED},category:nt.InvitationCategory.GAMES,from:nt.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INVITATION_SENT},category:nt.InvitationCategory.GAMES,from:e||nt.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 fe.listen(r)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:_r.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.INTERACTIONS},actionType:_r.InteractionActionType.SCROLL})}}const ze={[C.QuestionType.UNSET]:v.TopicType.UNSET,[C.QuestionType.FACTOID]:v.TopicType.POLLS_INSIGHT,[C.QuestionType.POLL]:v.TopicType.POLLS_POLL,[C.QuestionType.PREDICTION]:v.TopicType.POLLS_PREDICTION,[C.QuestionType.PROMOTION]:v.TopicType.POLLS_PROMOTION,[C.QuestionType.TRIVIA]:v.TopicType.POLLS_TRIVIA,[C.QuestionType.TWEET]:v.TopicType.POLLS_TWITTER};C.QuestionType.UNSET+"",Y.NotificationKind.UNSET,C.QuestionType.FACTOID+"",Y.NotificationKind.POLLS,C.QuestionType.POLL+"",Y.NotificationKind.POLLS,C.QuestionType.PREDICTION+"",Y.NotificationKind.POLLS,C.QuestionType.PROMOTION+"",Y.NotificationKind.POLLS,C.QuestionType.TRIVIA+"",Y.NotificationKind.POLLS,C.QuestionType.TWEET+"",Y.NotificationKind.POLLS;const So={[R.SdkOverlayType.UNSET]:v.Category.UNSET,[R.SdkOverlayType.INPLAY]:v.Category.INPLAY,[R.SdkOverlayType.MESSAGING]:v.Category.MESSAGING,[R.SdkOverlayType.STATISTICS]:v.Category.STATS,[R.SdkOverlayType.BETTING]:v.Category.BETTING,[R.SdkOverlayType.TWITTER]:v.Category.TWITTER,[R.SdkOverlayType.MERCHANDISE]:v.Category.MERCHANDISE,[R.SdkOverlayType.CONTESTS]:v.Category.CONTESTS,[R.SdkOverlayType.VOICE_CHAT]:v.Category.CALLING,[R.SdkOverlayType.TICKETS]:v.Category.TICKETS,[R.SdkOverlayType.WHOIS_WATCHING]:v.Category.WHOISWATCHING,[R.SdkOverlayType.PROFILE]:v.Category.PROFILE,[R.SdkOverlayType.GAMES]:v.Category.POLLS,[R.SdkOverlayType.GOLF_STATISTICS]:v.Category.STATS,[R.SdkOverlayType.HIGHLIGHTS]:v.Category.HIGHLIGHTS,[R.SdkOverlayType.PUBLIC_CHAT]:v.Category.PUBLIC_CHAT};class wo{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}};return fe.listen(r)})}received=({questionId:e,questionType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:r?ze[r]:v.TopicType.UNSET},notificationKind:Y.NotificationKind.POLLS,notificationType:Y.NotificationType.IN_APP})};opened=({questionId:e,questionType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:v.Kind.NOTIFICATION_OPENED,topicId:e,topicType:r?ze[r]:v.TopicType.UNSET},notificationKind:Y.NotificationKind.POLLS,notificationType:Y.NotificationType.IN_APP})}}class To{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 fe.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?ze[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?ze[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?ze[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 Ao=({transport:t,$commonStore:e})=>{let r;const n=Q(!1),i=5e3,{client:o,queryKey:s}=t.createPromiseClient(an.AnalyticsService,{method:"send",params:[n]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const h=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...h,kind:v.Kind.SESSION_HEARTBEAT}}}})}catch(m){le.error(m,"send heartbeat failed")}return Date.now()},refetchInterval:i}),u=()=>{le.debug("mounted heartbeat"),r=a.subscribe(()=>{})},d=()=>{le.debug("enabled heartbeat"),n.set(!0),a.lc===0&&u()},c=()=>{le.debug("disabled heartbeat"),n.set(!1)};return{enable:d,disable:c,mount:u,unmount:()=>{le.debug("unmounted heartbeat"),a.off(),r?.(),r=void 0,c()}}},le=ve("analytics");class Eo{commonStore;notifications;polls;invitation;interactions;heartbeat;analyticsClient;listeners;listenersCancels;connected=!1;constructor(e){this.listeners=new Set,this.listenersCancels=new Set,this.commonStore=new Ae(ie({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=Ao({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new wo(this),this.polls=new To(this),this.invitation=new vo(this),this.interactions=new bo(this);const{client:r}=e.analyticsTransport.createPromiseClient(an.AnalyticsService,{method:"send"});this.analyticsClient=r}connect=()=>{this.writeCommon("sessionId",Wt.nanoid()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,le.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,le.debug("analytics disconnected")};write=(e,r)=>{r&&this.analyticsClient.unary({message:{case:e,value:r}}).then(()=>{le.trace("send analytics success",e,r)}).catch(n=>{le.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",So[r]),r!==R.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",Wt.nanoid()):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 Io=(t,e,r)=>{t.analytics=new Eo(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),()=>{t.analytics.disconnect()})),r()};var dr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Oo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fr={exports:{}},pr={exports:{}};function Co(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 _o=Co,Lo=_o;function mn(t,e,r){if(typeof t=="function"&&(r=e,e=t,t=null),r<1)throw new Error("fastqueue concurrency must be greater than 1");var n=Lo(ko),i=null,o=null,s=0,a=null,u={push:I,drain:z,saturated:z,pause:c,paused:!1,concurrency:r,running:d,resume:m,idle:b,length:f,getQueue:h,unshift:S,empty:z,kill:V,killAndDrain:G,error:W};return u;function d(){return s}function c(){u.paused=!0}function f(){for(var F=i,$=0;F;)F=F.next,$++;return $}function h(){for(var F=i,$=[];F;)$.push(F.value),F=F.next;return $}function m(){if(u.paused){u.paused=!1;for(var F=0;F<u.concurrency;F++)s++,P()}}function b(){return s===0&&u.length()===0}function I(F,$){var O=n.get();O.context=t,O.release=P,O.value=F,O.callback=$||z,O.errorHandler=a,s===u.concurrency||u.paused?o?(o.next=O,o=O):(i=O,o=O,u.saturated()):(s++,e.call(t,O.value,O.worked))}function S(F,$){var O=n.get();O.context=t,O.release=P,O.value=F,O.callback=$||z,O.errorHandler=a,s===u.concurrency||u.paused?i?(O.next=i,i=O):(i=O,o=O,u.saturated()):(s++,e.call(t,O.value,O.worked))}function P(F){F&&n.release(F);var $=i;$?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 V(){i=null,o=null,u.drain=z}function G(){i=null,o=null,u.drain(),u.drain=z}function W(F){a=F}}function z(){}function ko(){this.value=null,this.callback=z,this.next=null,this.release=z,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=z,t.errorHandler&&o(r,s),i.call(t.context,r,n),t.release(t)}}function Po(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(c,f){e.call(this,c).then(function(h){f(null,h)},f)}var i=mn(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(h,m){o(c,function(b,I){if(b){m(b);return}h(I)})});return f.catch(z),f}function u(c){var f=new Promise(function(h,m){s(c,function(b,I){if(b){m(b);return}h(I)})});return f.catch(z),f}function d(){if(i.idle())return new Promise(function(h){h()});var c=i.drain,f=new Promise(function(h){i.drain=function(){c(),h()}});return f}}pr.exports=mn;pr.exports.promise=Po;var vn=pr.exports,hr={exports:{}},Me=typeof Reflect=="object"?Reflect:null,$r=Me&&typeof Me.apply=="function"?Me.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},at;Me&&typeof Me.ownKeys=="function"?at=Me.ownKeys:Object.getOwnPropertySymbols?at=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:at=function(e){return Object.getOwnPropertyNames(e)};function Fo(t){console&&console.warn&&console.warn(t)}var bn=Number.isNaN||function(e){return e!==e};function N(){N.init.call(this)}hr.exports=N;hr.exports.once=$o;N.EventEmitter=N;N.prototype._events=void 0;N.prototype._eventsCount=0;N.prototype._maxListeners=void 0;var Vr=10;function Et(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(N,"defaultMaxListeners",{enumerable:!0,get:function(){return Vr},set:function(t){if(typeof t!="number"||t<0||bn(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Vr=t}});N.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};N.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||bn(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 Sn(t){return t._maxListeners===void 0?N.defaultMaxListeners:t._maxListeners}N.prototype.getMaxListeners=function(){return Sn(this)};N.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")$r(u,this,r);else for(var d=u.length,c=In(u,d),n=0;n<d;++n)$r(c[n],this,r);return!0};function wn(t,e,r,n){var i,o,s;if(Et(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=Sn(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,Fo(a)}return t}N.prototype.addListener=function(e,r){return wn(this,e,r,!1)};N.prototype.on=N.prototype.addListener;N.prototype.prependListener=function(e,r){return wn(this,e,r,!0)};function No(){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 Tn(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=No.bind(n);return i.listener=r,n.wrapFn=i,i}N.prototype.once=function(e,r){return Et(r),this.on(e,Tn(this,e,r)),this};N.prototype.prependOnceListener=function(e,r){return Et(r),this.prependListener(e,Tn(this,e,r)),this};N.prototype.removeListener=function(e,r){var n,i,o,s,a;if(Et(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():Do(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};N.prototype.off=N.prototype.removeListener;N.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 An(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?Ro(i):In(i,i.length)}N.prototype.listeners=function(e){return An(this,e,!0)};N.prototype.rawListeners=function(e){return An(this,e,!1)};N.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):En.call(t,e)};N.prototype.listenerCount=En;function En(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}N.prototype.eventNames=function(){return this._eventsCount>0?at(this._events):[]};function In(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Do(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ro(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function $o(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))}On(t,e,o,{once:!0}),e!=="error"&&Vo(t,i,{once:!0})})}function Vo(t,e,r){typeof t.on=="function"&&On(t,"error",e,r)}function On(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 Cn=hr.exports,It={},_n={},Ln=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},jo=Ln,Ot=function(){return jo()&&!!Symbol.toStringTag},Mo=Error,Uo=EvalError,qo=RangeError,xo=ReferenceError,kn=SyntaxError,Ct=TypeError,Bo=URIError,jr=typeof Symbol<"u"&&Symbol,Qo=Ln,Go=function(){return typeof jr!="function"||typeof Symbol!="function"||typeof jr("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:Qo()},Ft={__proto__:null,foo:{}},Ko=Object,zo=function(){return{__proto__:Ft}.foo===Ft.foo&&!(Ft instanceof Ko)},Ho="Function.prototype.bind called on incompatible ",Wo=Object.prototype.toString,Jo=Math.max,Yo="[object Function]",Mr=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},Xo=function(e,r){for(var n=[],i=r||0,o=0;i<e.length;i+=1,o+=1)n[o]=e[i];return n},Zo=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r},es=function(e){var r=this;if(typeof r!="function"||Wo.apply(r)!==Yo)throw new TypeError(Ho+r);for(var n=Xo(arguments,1),i,o=function(){if(this instanceof i){var c=r.apply(this,Mr(n,arguments));return Object(c)===c?c:this}return r.apply(e,Mr(n,arguments))},s=Jo(0,r.length-n.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+Zo(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=es,yr=Function.prototype.bind||ts,rs=Function.prototype.call,ns=Object.prototype.hasOwnProperty,is=yr,os=is.call(rs,ns),E,ss=Mo,as=Uo,us=qo,cs=xo,qe=kn,Ue=Ct,ls=Bo,Pn=Function,Nt=function(t){try{return Pn('"use strict"; return ('+t+").constructor;")()}catch{}},Ie=Object.getOwnPropertyDescriptor;if(Ie)try{Ie({},"")}catch{Ie=null}var Dt=function(){throw new Ue},ds=Ie?function(){try{return arguments.callee,Dt}catch{try{return Ie(arguments,"callee").get}catch{return Dt}}}():Dt,Fe=Go(),fs=zo(),U=Object.getPrototypeOf||(fs?function(t){return t.__proto__}:null),De={},ps=typeof Uint8Array>"u"||!U?E:U(Uint8Array),Oe={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?E:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?E:ArrayBuffer,"%ArrayIteratorPrototype%":Fe&&U?U([][Symbol.iterator]()):E,"%AsyncFromSyncIteratorPrototype%":E,"%AsyncFunction%":De,"%AsyncGenerator%":De,"%AsyncGeneratorFunction%":De,"%AsyncIteratorPrototype%":De,"%Atomics%":typeof Atomics>"u"?E:Atomics,"%BigInt%":typeof BigInt>"u"?E:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?E:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?E:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?E:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":ss,"%eval%":eval,"%EvalError%":as,"%Float32Array%":typeof Float32Array>"u"?E:Float32Array,"%Float64Array%":typeof Float64Array>"u"?E:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?E:FinalizationRegistry,"%Function%":Pn,"%GeneratorFunction%":De,"%Int8Array%":typeof Int8Array>"u"?E:Int8Array,"%Int16Array%":typeof Int16Array>"u"?E:Int16Array,"%Int32Array%":typeof Int32Array>"u"?E:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Fe&&U?U(U([][Symbol.iterator]())):E,"%JSON%":typeof JSON=="object"?JSON:E,"%Map%":typeof Map>"u"?E:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Fe||!U?E:U(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?E:Promise,"%Proxy%":typeof Proxy>"u"?E:Proxy,"%RangeError%":us,"%ReferenceError%":cs,"%Reflect%":typeof Reflect>"u"?E:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?E:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Fe||!U?E:U(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?E:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Fe&&U?U(""[Symbol.iterator]()):E,"%Symbol%":Fe?Symbol:E,"%SyntaxError%":qe,"%ThrowTypeError%":ds,"%TypedArray%":ps,"%TypeError%":Ue,"%Uint8Array%":typeof Uint8Array>"u"?E:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?E:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?E:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?E:Uint32Array,"%URIError%":ls,"%WeakMap%":typeof WeakMap>"u"?E:WeakMap,"%WeakRef%":typeof WeakRef>"u"?E:WeakRef,"%WeakSet%":typeof WeakSet>"u"?E:WeakSet};if(U)try{null.error}catch(t){var hs=U(U(t));Oe["%Error.prototype%"]=hs}var ys=function t(e){var r;if(e==="%AsyncFunction%")r=Nt("async function () {}");else if(e==="%GeneratorFunction%")r=Nt("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Nt("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&U&&(r=U(i.prototype))}return Oe[e]=r,r},Ur={__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"]},Ye=yr,ht=os,gs=Ye.call(Function.call,Array.prototype.concat),ms=Ye.call(Function.apply,Array.prototype.splice),qr=Ye.call(Function.call,String.prototype.replace),yt=Ye.call(Function.call,String.prototype.slice),vs=Ye.call(Function.call,RegExp.prototype.exec),bs=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ss=/\\(\\)?/g,ws=function(e){var r=yt(e,0,1),n=yt(e,-1);if(r==="%"&&n!=="%")throw new qe("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new qe("invalid intrinsic syntax, expected opening `%`");var i=[];return qr(e,bs,function(o,s,a,u){i[i.length]=a?qr(u,Ss,"$1"):s||o}),i},Ts=function(e,r){var n=e,i;if(ht(Ur,n)&&(i=Ur[n],n="%"+i[0]+"%"),ht(Oe,n)){var o=Oe[n];if(o===De&&(o=ys(n)),typeof o>"u"&&!r)throw new Ue("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new qe("intrinsic "+e+" does not exist!")},Xe=function(e,r){if(typeof e!="string"||e.length===0)throw new Ue("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Ue('"allowMissing" argument must be a boolean');if(vs(/^%?[^%]*%?$/,e)===null)throw new qe("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=ws(e),i=n.length>0?n[0]:"",o=Ts("%"+i+"%",r),s=o.name,a=o.value,u=!1,d=o.alias;d&&(i=d[0],ms(n,gs([0,1],d)));for(var c=1,f=!0;c<n.length;c+=1){var h=n[c],m=yt(h,0,1),b=yt(h,-1);if((m==='"'||m==="'"||m==="`"||b==='"'||b==="'"||b==="`")&&m!==b)throw new qe("property names with quotes must have matching quotes");if((h==="constructor"||!f)&&(u=!0),i+="."+h,s="%"+i+"%",ht(Oe,s))a=Oe[s];else if(a!=null){if(!(h in a)){if(!r)throw new Ue("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ie&&c+1>=n.length){var I=Ie(a,h);f=!!I,f&&"get"in I&&!("originalValue"in I.get)?a=I.get:a=a[h]}else f=ht(a,h),a=a[h];f&&!u&&(Oe[s]=a)}}return a},Fn={exports:{}},Rt,xr;function gr(){if(xr)return Rt;xr=1;var t=Xe,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Rt=e,Rt}var As=Xe,ut=As("%Object.getOwnPropertyDescriptor%",!0);if(ut)try{ut([],"length")}catch{ut=null}var _t=ut,Br=gr(),Es=kn,Ne=Ct,Qr=_t,Is=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Ne("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Ne("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Ne("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Ne("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Ne("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Ne("`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=!!Qr&&Qr(e,r);if(Br)Br(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 Es("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},er=gr(),Nn=function(){return!!er};Nn.hasArrayLengthDefineBug=function(){if(!er)return null;try{return er([],"length",{value:1}).length!==1}catch{return!0}};var Os=Nn,Cs=Xe,Gr=Is,_s=Os(),Kr=_t,zr=Ct,Ls=Cs("%Math.floor%"),ks=function(e,r){if(typeof e!="function")throw new zr("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||Ls(r)!==r)throw new zr("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&Kr){var s=Kr(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!n)&&(_s?Gr(e,"length",r,!0,!0):Gr(e,"length",r)),e};(function(t){var e=yr,r=Xe,n=ks,i=Ct,o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||e.call(s,o),u=gr(),d=r("%Math.max%");t.exports=function(h){if(typeof h!="function")throw new i("a function is required");var m=a(e,s,arguments);return n(m,1+d(0,h.length-(arguments.length-1)),!0)};var c=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:c}):t.exports.apply=c})(Fn);var mr=Fn.exports,Dn=Xe,Rn=mr,Ps=Rn(Dn("String.prototype.indexOf")),vr=function(e,r){var n=Dn(e,!!r);return typeof n=="function"&&Ps(e,".prototype.")>-1?Rn(n):n},Fs=Ot(),Ns=vr,tr=Ns("Object.prototype.toString"),Lt=function(e){return Fs&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:tr(e)==="[object Arguments]"},$n=function(e){return Lt(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&tr(e)!=="[object Array]"&&tr(e.callee)==="[object Function]"},Ds=function(){return Lt(arguments)}();Lt.isLegacyArguments=$n;var Rs=Ds?Lt:$n,$s=Object.prototype.toString,Vs=Function.prototype.toString,js=/^\s*(?:function)?\*/,Vn=Ot(),$t=Object.getPrototypeOf,Ms=function(){if(!Vn)return!1;try{return Function("return function*() {}")()}catch{}},Vt,Us=function(e){if(typeof e!="function")return!1;if(js.test(Vs.call(e)))return!0;if(!Vn){var r=$s.call(e);return r==="[object GeneratorFunction]"}if(!$t)return!1;if(typeof Vt>"u"){var n=Ms();Vt=n?$t(n):!1}return $t(e)===Vt},jn=Function.prototype.toString,Ve=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,rr,ct;if(typeof Ve=="function"&&typeof Object.defineProperty=="function")try{rr=Object.defineProperty({},"length",{get:function(){throw ct}}),ct={},Ve(function(){throw 42},null,rr)}catch(t){t!==ct&&(Ve=null)}else Ve=null;var qs=/^\s*class\b/,nr=function(e){try{var r=jn.call(e);return qs.test(r)}catch{return!1}},jt=function(e){try{return nr(e)?!1:(jn.call(e),!0)}catch{return!1}},lt=Object.prototype.toString,xs="[object Object]",Bs="[object Function]",Qs="[object GeneratorFunction]",Gs="[object HTMLAllCollection]",Ks="[object HTML document.all class]",zs="[object HTMLCollection]",Hs=typeof Symbol=="function"&&!!Symbol.toStringTag,Ws=!(0 in[,]),ir=function(){return!1};if(typeof document=="object"){var Js=document.all;lt.call(Js)===lt.call(document.all)&&(ir=function(e){if((Ws||!e)&&(typeof e>"u"||typeof e=="object"))try{var r=lt.call(e);return(r===Gs||r===Ks||r===zs||r===xs)&&e("")==null}catch{}return!1})}var Ys=Ve?function(e){if(ir(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ve(e,null,rr)}catch(r){if(r!==ct)return!1}return!nr(e)&&jt(e)}:function(e){if(ir(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(Hs)return jt(e);if(nr(e))return!1;var r=lt.call(e);return r!==Bs&&r!==Qs&&!/^\[object HTML/.test(r)?!1:jt(e)},Xs=Ys,Zs=Object.prototype.toString,Mn=Object.prototype.hasOwnProperty,ea=function(e,r,n){for(var i=0,o=e.length;i<o;i++)Mn.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)},ra=function(e,r,n){for(var i in e)Mn.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},na=function(e,r,n){if(!Xs(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=n),Zs.call(e)==="[object Array]"?ea(e,r,i):typeof e=="string"?ta(e,r,i):ra(e,r,i)},Un=na,ia=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],Mt=ia,oa=typeof globalThis>"u"?dr:globalThis,qn=function(){for(var e=[],r=0;r<Mt.length;r++)typeof oa[Mt[r]]=="function"&&(e[e.length]=Mt[r]);return e},gt=Un,sa=qn,Hr=mr,br=vr,dt=_t,aa=br("Object.prototype.toString"),xn=Ot(),Wr=typeof globalThis>"u"?dr:globalThis,or=sa(),Sr=br("String.prototype.slice"),Ut=Object.getPrototypeOf,ua=br("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},mt={__proto__:null};xn&&dt&&Ut?gt(or,function(t){var e=new Wr[t];if(Symbol.toStringTag in e){var r=Ut(e),n=dt(r,Symbol.toStringTag);if(!n){var i=Ut(r);n=dt(i,Symbol.toStringTag)}mt["$"+t]=Hr(n.get)}}):gt(or,function(t){var e=new Wr[t],r=e.slice||e.set;r&&(mt["$"+t]=Hr(r))});var ca=function(e){var r=!1;return gt(mt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Sr(i,1))}catch{}}),r},la=function(e){var r=!1;return gt(mt,function(n,i){if(!r)try{n(e),r=Sr(i,1)}catch{}}),r},da=function(e){if(!e||typeof e!="object")return!1;if(!xn){var r=Sr(aa(e),8,-1);return ua(or,r)>-1?r:r!=="Object"?!1:la(e)}return dt?ca(e):null},vt=Un,fa=qn,Jr=mr,wr=vr,ft=_t,pa=wr("Object.prototype.toString"),Bn=Ot(),Yr=typeof globalThis>"u"?dr:globalThis,sr=fa(),Tr=wr("String.prototype.slice"),qt=Object.getPrototypeOf,ha=wr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},bt={__proto__:null};Bn&&ft&&qt?vt(sr,function(t){var e=new Yr[t];if(Symbol.toStringTag in e){var r=qt(e),n=ft(r,Symbol.toStringTag);if(!n){var i=qt(r);n=ft(i,Symbol.toStringTag)}bt["$"+t]=Jr(n.get)}}):vt(sr,function(t){var e=new Yr[t],r=e.slice||e.set;r&&(bt["$"+t]=Jr(r))});var ya=function(e){var r=!1;return vt(bt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Tr(i,1))}catch{}}),r},ga=function(e){var r=!1;return vt(bt,function(n,i){if(!r)try{n(e),r=Tr(i,1)}catch{}}),r},ma=function(e){if(!e||typeof e!="object")return!1;if(!Bn){var r=Tr(pa(e),8,-1);return ha(sr,r)>-1?r:r!=="Object"?!1:ga(e)}return ft?ya(e):null},va=ma,ba=function(e){return!!va(e)};(function(t){var e=Rs,r=Us,n=da,i=ba;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 h=o(BigInt.prototype.valueOf);if(a)var m=o(Symbol.prototype.valueOf);function b(y,Jn){if(typeof y!="object")return!1;try{return Jn(y),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=i;function I(y){return typeof Promise<"u"&&y instanceof Promise||y!==null&&typeof y=="object"&&typeof y.then=="function"&&typeof y.catch=="function"}t.isPromise=I;function S(y){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(y):i(y)||p(y)}t.isArrayBufferView=S;function P(y){return n(y)==="Uint8Array"}t.isUint8Array=P;function V(y){return n(y)==="Uint8ClampedArray"}t.isUint8ClampedArray=V;function G(y){return n(y)==="Uint16Array"}t.isUint16Array=G;function W(y){return n(y)==="Uint32Array"}t.isUint32Array=W;function F(y){return n(y)==="Int8Array"}t.isInt8Array=F;function $(y){return n(y)==="Int16Array"}t.isInt16Array=$;function O(y){return n(y)==="Int32Array"}t.isInt32Array=O;function Z(y){return n(y)==="Float32Array"}t.isFloat32Array=Z;function ee(y){return n(y)==="Float64Array"}t.isFloat64Array=ee;function Ce(y){return n(y)==="BigInt64Array"}t.isBigInt64Array=Ce;function be(y){return n(y)==="BigUint64Array"}t.isBigUint64Array=be;function oe(y){return u(y)==="[object Map]"}oe.working=typeof Map<"u"&&oe(new Map);function kt(y){return typeof Map>"u"?!1:oe.working?oe(y):y instanceof Map}t.isMap=kt;function ye(y){return u(y)==="[object Set]"}ye.working=typeof Set<"u"&&ye(new Set);function Qe(y){return typeof Set>"u"?!1:ye.working?ye(y):y instanceof Set}t.isSet=Qe;function _e(y){return u(y)==="[object WeakMap]"}_e.working=typeof WeakMap<"u"&&_e(new WeakMap);function Pt(y){return typeof WeakMap>"u"?!1:_e.working?_e(y):y instanceof WeakMap}t.isWeakMap=Pt;function Le(y){return u(y)==="[object WeakSet]"}Le.working=typeof WeakSet<"u"&&Le(new WeakSet);function se(y){return Le(y)}t.isWeakSet=se;function ke(y){return u(y)==="[object ArrayBuffer]"}ke.working=typeof ArrayBuffer<"u"&&ke(new ArrayBuffer);function Ze(y){return typeof ArrayBuffer>"u"?!1:ke.working?ke(y):y instanceof ArrayBuffer}t.isArrayBuffer=Ze;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 p(y){return typeof DataView>"u"?!1:l.working?l(y):y instanceof DataView}t.isDataView=p;var g=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function w(y){return u(y)==="[object SharedArrayBuffer]"}function L(y){return typeof g>"u"?!1:(typeof w.working>"u"&&(w.working=w(new g)),w.working?w(y):y instanceof g)}t.isSharedArrayBuffer=L;function k(y){return u(y)==="[object AsyncFunction]"}t.isAsyncFunction=k;function A(y){return u(y)==="[object Map Iterator]"}t.isMapIterator=A;function _(y){return u(y)==="[object Set Iterator]"}t.isSetIterator=_;function D(y){return u(y)==="[object Generator]"}t.isGeneratorObject=D;function K(y){return u(y)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=K;function Se(y){return b(y,d)}t.isNumberObject=Se;function et(y){return b(y,c)}t.isStringObject=et;function Pe(y){return b(y,f)}t.isBooleanObject=Pe;function tt(y){return s&&b(y,h)}t.isBigIntObject=tt;function Ir(y){return a&&b(y,m)}t.isSymbolObject=Ir;function Hn(y){return Se(y)||et(y)||Pe(y)||tt(y)||Ir(y)}t.isBoxedPrimitive=Hn;function Wn(y){return typeof Uint8Array<"u"&&(Ze(y)||L(y))}t.isAnyArrayBuffer=Wn,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(y){Object.defineProperty(t,y,{enumerable:!1,value:function(){throw new Error(y+" is not supported in userland")}})})})(_n);var Sa=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},ar={exports:{}};typeof Object.create=="function"?ar.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:ar.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 wa=ar.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(p){for(var g=Object.keys(p),w={},L=0;L<g.length;L++)w[g[L]]=Object.getOwnPropertyDescriptor(p,g[L]);return w},r=/%[sdj%]/g;t.format=function(l){if(!F(l)){for(var p=[],g=0;g<arguments.length;g++)p.push(s(arguments[g]));return p.join(" ")}for(var g=1,w=arguments,L=w.length,k=String(l).replace(r,function(_){if(_==="%%")return"%";if(g>=L)return _;switch(_){case"%s":return String(w[g++]);case"%d":return Number(w[g++]);case"%j":try{return JSON.stringify(w[g++])}catch{return"[Circular]"}default:return _}}),A=w[g];g<L;A=w[++g])V(A)||!ee(A)?k+=" "+A:k+=" "+s(A);return k},t.deprecate=function(l,p){if(typeof T<"u"&&T.noDeprecation===!0)return l;if(typeof T>"u")return function(){return t.deprecate(l,p).apply(this,arguments)};var g=!1;function w(){if(!g){if(T.throwDeprecation)throw new Error(p);T.traceDeprecation?console.trace(p):console.error(p),g=!0}return l.apply(this,arguments)}return w};var n={},i=/^$/;if(T.env.NODE_DEBUG){var o=T.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 p=T.pid;n[l]=function(){var g=t.format.apply(t,arguments);console.error("%s %d: %s",l,p,g)}}else n[l]=function(){};return n[l]};function s(l,p){var g={seen:[],stylize:u};return arguments.length>=3&&(g.depth=arguments[2]),arguments.length>=4&&(g.colors=arguments[3]),P(p)?g.showHidden=p:p&&t._extend(g,p),O(g.showHidden)&&(g.showHidden=!1),O(g.depth)&&(g.depth=2),O(g.colors)&&(g.colors=!1),O(g.customInspect)&&(g.customInspect=!0),g.colors&&(g.stylize=a),c(g,l,g.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,p){var g=s.styles[p];return g?"\x1B["+s.colors[g][0]+"m"+l+"\x1B["+s.colors[g][1]+"m":l}function u(l,p){return l}function d(l){var p={};return l.forEach(function(g,w){p[g]=!0}),p}function c(l,p,g){if(l.customInspect&&p&&oe(p.inspect)&&p.inspect!==t.inspect&&!(p.constructor&&p.constructor.prototype===p)){var w=p.inspect(g,l);return F(w)||(w=c(l,w,g)),w}var L=f(l,p);if(L)return L;var k=Object.keys(p),A=d(k);if(l.showHidden&&(k=Object.getOwnPropertyNames(p)),be(p)&&(k.indexOf("message")>=0||k.indexOf("description")>=0))return h(p);if(k.length===0){if(oe(p)){var _=p.name?": "+p.name:"";return l.stylize("[Function"+_+"]","special")}if(Z(p))return l.stylize(RegExp.prototype.toString.call(p),"regexp");if(Ce(p))return l.stylize(Date.prototype.toString.call(p),"date");if(be(p))return h(p)}var D="",K=!1,Se=["{","}"];if(S(p)&&(K=!0,Se=["[","]"]),oe(p)){var et=p.name?": "+p.name:"";D=" [Function"+et+"]"}if(Z(p)&&(D=" "+RegExp.prototype.toString.call(p)),Ce(p)&&(D=" "+Date.prototype.toUTCString.call(p)),be(p)&&(D=" "+h(p)),k.length===0&&(!K||p.length==0))return Se[0]+D+Se[1];if(g<0)return Z(p)?l.stylize(RegExp.prototype.toString.call(p),"regexp"):l.stylize("[Object]","special");l.seen.push(p);var Pe;return K?Pe=m(l,p,g,A,k):Pe=k.map(function(tt){return b(l,p,g,A,tt,K)}),l.seen.pop(),I(Pe,D,Se)}function f(l,p){if(O(p))return l.stylize("undefined","undefined");if(F(p)){var g="'"+JSON.stringify(p).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return l.stylize(g,"string")}if(W(p))return l.stylize(""+p,"number");if(P(p))return l.stylize(""+p,"boolean");if(V(p))return l.stylize("null","null")}function h(l){return"["+Error.prototype.toString.call(l)+"]"}function m(l,p,g,w,L){for(var k=[],A=0,_=p.length;A<_;++A)Le(p,String(A))?k.push(b(l,p,g,w,String(A),!0)):k.push("");return L.forEach(function(D){D.match(/^\d+$/)||k.push(b(l,p,g,w,D,!0))}),k}function b(l,p,g,w,L,k){var A,_,D;if(D=Object.getOwnPropertyDescriptor(p,L)||{value:p[L]},D.get?D.set?_=l.stylize("[Getter/Setter]","special"):_=l.stylize("[Getter]","special"):D.set&&(_=l.stylize("[Setter]","special")),Le(w,L)||(A="["+L+"]"),_||(l.seen.indexOf(D.value)<0?(V(g)?_=c(l,D.value,null):_=c(l,D.value,g-1),_.indexOf(`
|
|
3
3
|
`)>-1&&(k?_=_.split(`
|
|
4
4
|
`).map(function(K){return" "+K}).join(`
|
|
5
5
|
`).slice(2):_=`
|
package/lib/es/index.js
CHANGED
|
@@ -1600,15 +1600,15 @@ const Io = (t, e, r, n) => {
|
|
|
1600
1600
|
} };
|
|
1601
1601
|
}, Oo = (t, e, r, n) => {
|
|
1602
1602
|
const i = ie(void 0), o = Tn(n), s = async () => {
|
|
1603
|
-
const u = t.get(), d = e.get(), c = r.getStore().get().data?.map((
|
|
1603
|
+
const u = t.get(), d = e.get(), c = r.getStore().get().data?.map((m) => m.slId);
|
|
1604
1604
|
if (!c)
|
|
1605
1605
|
return;
|
|
1606
1606
|
const f = {
|
|
1607
1607
|
eventId: u,
|
|
1608
1608
|
userId: d,
|
|
1609
1609
|
usersIds: [...c, d]
|
|
1610
|
-
}, p = await o(f)
|
|
1611
|
-
|
|
1610
|
+
}, p = await o(f);
|
|
1611
|
+
i.set(p.data?.attributes);
|
|
1612
1612
|
}, a = () => {
|
|
1613
1613
|
s();
|
|
1614
1614
|
};
|
|
@@ -1661,7 +1661,7 @@ class _o extends In {
|
|
|
1661
1661
|
cancels = /* @__PURE__ */ new Set();
|
|
1662
1662
|
constructor(e, r, n) {
|
|
1663
1663
|
super(e, r), this.background = new to(n), this.feedSubscription = this.background.feedSubscription, this.activeQuestionId = this.background.activeQuestionId, this.openedQuestionId = this.background.openedQuestionId, this.storage = new On(), this.feedList = this.background.feedList, this.friends = new ye(Hi(this.background.userId, n.transport), "gamification:friends"), this.currentUserId = this.background.userId, this.openedUser = B(void 0), this.leaderboardId = new W(B(this.settings.getValue("pinnedLeaderboardId")), "pinnedLeaderboardId").getStore(), this.onboardingStatus = To(this, this.background, n.transport, n.notifications), this.notifications = n.notifications, this.transport = n.transport, this.closeFeature = () => n.sdk.closeFeature(!0), this.openFeature = () => n.sdk.openFeature(N.GAMES), this.openedQuestion = this.background.openedQuestion, this.deepLink = Eo(this.transport, this.background.slStreamId, n.stores.providerStreamId.getStore(), this.background.userId), this.userSummary = Oo(this.background.slStreamId, this.background.userId, this.friends, this.transport), this.leaderboardList = co(this.transport, this.background.slStreamId, this.background.userId, this.friends), this.connect(), this.cancels.add(this.userSummary.$store.listen((i, o) => {
|
|
1664
|
-
o?.summary && i?.summary &&
|
|
1664
|
+
o?.summary && i?.summary && this.leaderboardList.invalidate();
|
|
1665
1665
|
})), this.cancels.add(this.background.activeQuestionId.listen(this.showInApp)), 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)), n.sdk.onMount({ name: "gamification", clear: !0 }, () => () => {
|
|
1666
1666
|
for (const i of this.cancels)
|
|
1667
1667
|
i(), this.cancels.delete(i);
|
package/package.json
CHANGED
|
@@ -24,18 +24,18 @@
|
|
|
24
24
|
"devDependencies": {
|
|
25
25
|
"avvio": "^8.2.1",
|
|
26
26
|
"tslib": "^2.6.2",
|
|
27
|
-
"@streamlayer/feature-gamification": "^0.41.
|
|
28
|
-
"@streamlayer/sdk-web-analytics": "^0.2.
|
|
29
|
-
"@streamlayer/sdk-web-api": "^0.25.1",
|
|
27
|
+
"@streamlayer/feature-gamification": "^0.41.2",
|
|
28
|
+
"@streamlayer/sdk-web-analytics": "^0.2.2",
|
|
30
29
|
"@streamlayer/sdk-web-core": "^0.23.1",
|
|
31
|
-
"@streamlayer/sdk-web-
|
|
30
|
+
"@streamlayer/sdk-web-api": "^0.25.1",
|
|
31
|
+
"@streamlayer/sdk-web-features": "^0.11.30",
|
|
32
32
|
"@streamlayer/sdk-web-interfaces": "^0.22.1",
|
|
33
33
|
"@streamlayer/sdk-web-logger": "^0.5.21",
|
|
34
34
|
"@streamlayer/sdk-web-notifications": "^0.16.1",
|
|
35
35
|
"@streamlayer/sdk-web-storage": "^0.4.8",
|
|
36
36
|
"@streamlayer/sdk-web-types": "^0.23.3"
|
|
37
37
|
},
|
|
38
|
-
"version": "0.33.
|
|
38
|
+
"version": "0.33.6",
|
|
39
39
|
"type": "module",
|
|
40
40
|
"main": "./src/index.js",
|
|
41
41
|
"typings": "./src/index.d.ts"
|