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