@streamlayer/sdk-web 1.17.2 → 1.17.3
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 +6 -6
- package/lib/es/index.js +177 -153
- package/package.json +13 -13
package/lib/cjs/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qi=require("pino"),v=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),z=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),M=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),dt=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),X=require("nanostores"),$e=require("uuid"),j=require("@connectrpc/connect"),Br=require("@connectrpc/connect-web"),Mr=require("@nanostores/query"),Vn=require("@streamlayer/sl-eslib/sports/events/events_pb"),ot=require("@streamlayer/sl-eslib/sdkSettings/client/client_pb"),Ar=require("@streamlayer/sl-eslib/users/users_pb"),xn=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb"),$i=require("@streamlayer/sl-eslib/shortLinks/linksClient_pb"),qr=require("@streamlayer/sl-eslib/polymarket/sportsClient_pb"),g=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),Bn=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_pb"),$r=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),ne=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function ji(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Mn={exports:{}},Q=Mn.exports={},ue,ce;function sr(){throw new Error("setTimeout has not been defined")}function ar(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?ue=setTimeout:ue=sr}catch{ue=sr}try{typeof clearTimeout=="function"?ce=clearTimeout:ce=ar}catch{ce=ar}})();function qn(t){if(ue===setTimeout)return setTimeout(t,0);if((ue===sr||!ue)&&setTimeout)return ue=setTimeout,setTimeout(t,0);try{return ue(t,0)}catch{try{return ue.call(null,t,0)}catch{return ue.call(this,t,0)}}}function Qi(t){if(ce===clearTimeout)return clearTimeout(t);if((ce===ar||!ce)&&clearTimeout)return ce=clearTimeout,clearTimeout(t);try{return ce(t)}catch{try{return ce.call(null,t)}catch{return ce.call(this,t)}}}var be=[],Ke=!1,ke,mt=-1;function Gi(){!Ke||!ke||(Ke=!1,ke.length?be=ke.concat(be):mt=-1,be.length&&$n())}function $n(){if(!Ke){var t=qn(Gi);Ke=!0;for(var e=be.length;e;){for(ke=be,be=[];++mt<e;)ke&&ke[mt].run();mt=-1,e=be.length}ke=null,Ke=!1,Qi(t)}}Q.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];be.push(new jn(t,e)),be.length===1&&!Ke&&qn($n)};function jn(t,e){this.fun=t,this.array=e}jn.prototype.run=function(){this.fun.apply(null,this.array)};Q.title="browser";Q.browser=!0;Q.env={};Q.argv=[];Q.version="";Q.versions={};function Te(){}Q.on=Te;Q.addListener=Te;Q.once=Te;Q.off=Te;Q.removeListener=Te;Q.removeAllListeners=Te;Q.emit=Te;Q.prependListener=Te;Q.prependOnceListener=Te;Q.listeners=function(t){return[]};Q.binding=function(t){throw new Error("process.binding is not supported")};Q.cwd=function(){return"/"};Q.chdir=function(t){throw new Error("process.chdir is not supported")};Q.umask=function(){return 0};var Ki=Mn.exports;const C=ji(Ki),Wi=qi.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),Z=(t,e)=>Wi.child({name:t},e);class Hi extends Event{slEventBus;constructor(e,r){super(e),this.slEventBus=r}}const zi=Z("event-bus");class Yi{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,r)=>{const n=new Hi(this.name,{...r,type:e});zi.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 Ji{}var ve;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(ve||(ve={}));window.slStore=Object.create(null);class Rt{store;name;constructor(e,r){this.store=e,this.name=r}getStore(){return this.store}}const Xi=t=>{const e=Object.keys(t);return X.computed(e.map(r=>t[r].getStore()),(...r)=>Object.fromEntries(e.map((n,i)=>[n,r[i]])))};class Ne extends Rt{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 J=t=>X.map(t);var me;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(me||(me={}));const Zi={[M.SdkOverlayType.BETTING]:"betting",[M.SdkOverlayType.GAMES]:"games",[M.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[M.SdkOverlayType.TWITTER]:"twitter"};var we;(function(t){t.Ready="ready",t.Suspended="suspended"})(we||(we={}));const eo=new Set(["equals","clone","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","getType"]);class Qn{status;listeners=new Set;constructor(){this.status=X.atom(we.Suspended)}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(we.Ready)};disable=()=>{this.status.set(we.Suspended)};fireEvent(e){for(const r of this.listeners.values())try{r.onEvent(e)}catch(n){console.error(n)}}}class Gn{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...r},n){this.settingsKey=Zi[r.type],this.status=X.atom(we.Suspended),this.config=new Ne(J(r),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ne(J(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ne(J({}),`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(we.Ready)};disable=()=>{this.status.set(we.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)!eo.has(o)&&i[o]&&this.settings.setValue(o,i[o])}}};update=(e,r)=>{this.source===me.STREAM&&r===me.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 te extends Rt{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 G=t=>X.atom(t);class ie extends Rt{atomStore;constructor(e,r,n){super(e,`api:${r}`),this.atomStore=X.atom(),n&&e.subscribe(i=>{const o=this.atomStore.get(),s=n(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;getValue=()=>new Promise((e,r)=>window.requestAnimationFrame(async()=>{try{const n=this.getStore();if(n.value===void 0)throw new Error("no store");if(!n.key){e(void 0);return}await n.fetch(),e(n.get().data)}catch(n){r(n)}}));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 V=new Yi;async function*to(t,e){for await(const r of e){t.response.message=r,t.received_at=Date.now(),t.id=Date.now();const n={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(n),yield r}}const ro=()=>t=>async e=>{const r={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};try{window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:r})}catch(n){console.log("devtools error",n)}try{const n=await t(e);if(r.received_at=Date.now(),r.response.header=Object.fromEntries(n.header.entries()),r.response.trailer=Object.fromEntries(n.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...r,stream:!0}};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}return{...n,message:to(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};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}}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};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}throw n}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Kn(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class Xe{delimiter=":";prefix;storage;constructor(e="main",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){Kn(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 re;(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"})(re||(re={}));const jr=Z("grpc:stream");class no{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,r,n,i){const o={status:re.Init,ts:new Date,log:[]};this.state=new Ne(J(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 te(G(null),`subscription:${i.name}:store`)),"subscribe"in n&&typeof n.subscribe=="function"&&(this.paramsListener=n.subscribe(s=>{this.state.getValue("status")===re.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(re.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const r=this.state.getStore().get().log,n=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(r.push(n),this.state.setValue("log",r),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?jr.trace({name:this.options.name,attempt:this.attempt},"received data"):jr.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
-
`+n)}catch(i){Kn(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(re.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 j.ConnectError&&n.code!=j.Code.Canceled&&this.onStreamError(n)}})(),this.updateState(re.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(re.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(re.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(re.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 j.ConnectError&&e.code!==j.Code.Canceled){this.updateState(re.Failed),this.state.setValue("error",e),e.code===j.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const io=new Set([j.Code.Unknown,j.Code.Internal,j.Code.DeadlineExceeded,j.Code.ResourceExhausted,j.Code.FailedPrecondition,j.Code.Unavailable,j.Code.DataLoss]),Qr=Z("grpc:retry"),oo=t=>async e=>{const r=e.contextValues.get(ur.retryAttempts),n=300,i=e.contextValues.get(ur.retryDelay);if(e.stream||r===0)return t(e);Qr.trace({url:e.url,attempts:r,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Qr.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=j.ConnectError.from(s);if(o>=r||!(a instanceof j.ConnectError)||!io.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*n),c=Math.round(u*(1+Math.random())/2);await new Promise(l=>setTimeout(l,c))}},ur={retryAttempts:j.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:j.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},so=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=$e.v4();return localStorage.setItem("sl-device-id",e),e},ao=()=>navigator.userAgentData?.platform||navigator.platform,uo=t=>t?"webOS":navigator.userAgentData&&navigator.userAgentData.mobile||"ontouchstart"in window||navigator.maxTouchPoints>0?"mobile-web":"desktop-web";class Gr{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;storeCache;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,r){this.host=e,this.opts=r,this.$headers=new Ne(J({"sl-device-id":so(),"sl-device-os":ao(),"sl-platform":uo(r?.webOS)}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map,this.storeCache=new Map;const[n,i,o]=Mr.nanoquery({dedupeTime:r?.dedupeTime,revalidateInterval:r?.refetchInterval});this.nanoquery={createFetcherStore:n,createMutatorStore:i,utils:o},this.transport=Br.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Br.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,r,n)=>{const i=this.subscriptions.get(r);if(i)return i;const o=new no(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]=Mr.nanoquery({dedupeTime:this.opts?.dedupeTime,revalidateInterval: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=j.createClient(e,this.transport);return this.clients.set(r,n),n};getStreamClient=e=>{const r=`stream-${e.typeName}`;if(this.clients.has(r))return this.clients.get(r);const n=j.createClient(e,this.streamTransport);return this.clients.set(r,n),n};createPromiseClient=(e,{params:r=[],method:n})=>{const i=this.getClient(e),o=n.toString(),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:c=>{const l=j.createContextValues();for(const d in c){const p=ur[d];l.set(p,c[d])}return l},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),window.localStorage.getItem("SL_GRPC_DEVTOOLS")==="true"?this.interceptors.push(ro()):console.warn("SL GRPC DevTools is disabled. To enable, set SL_GRPC_DEVTOOLS to true in localStorage."),this.opts?.retryable&&this.interceptors.push(oo)}}const co=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Vn.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""}}})},lo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.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})},po=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Vn.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.summary({id:s})).data?.attributes:void 0})},fo=(t,e)=>{const{queryKey:r,client:n}=e.createPromiseClient(Ar.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{if(!e.getHeader("authorization"))return{data:void 0};const{data:o}=await n.me({});return{data:o}}})},ho=t=>{const{client:e,createRequestOptions:r}=t.createPromiseClient(Ar.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})},mo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.get({})).data?.attributes})},go=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.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}})},yo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.getOrganizationAdvertising({})).data?.attributes})},bo=(t,e,r)=>{t.transport=new Gr(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0,webOS:e.webOS}),t.analyticsTransport=new Gr(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 he;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(he||(he={}));class je extends Xe{constructor(){super("user")}setSchema=e=>{this.write(he.SCHEMA,e)};getSchema=()=>this.read(he.SCHEMA);setToken=e=>{this.write(he.TOKEN,e)};getToken=()=>this.read(he.TOKEN);setExternalToken=e=>{this.write(he.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(he.EXTERNAL_TOKEN);removeToken=()=>{this.remove(he.TOKEN)}}var ge;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(ge||(ge={}));const vo=t=>{const e=new je,r=new te(G(e.getExternalToken()),"userKey"),n=new te(G(e.getToken()),"userToken"),i=new ie(fo(n.getStore(),t),"user",({data:s,error:a,loading:u},c)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:c}),o=new ie(mo(n.getStore(),t),"userSettings");return{userKey:r,userToken:n,user:i,userSettings:o}},To=t=>{const e=new te(G(void 0),"providerStreamId"),r=new ie(co(e.getStore(),t),"slStreamId",o=>o?.data),n=new ie(lo(r.getAtomStore(),t),"streamSettings"),i=new ie(po(r.getAtomStore(),t),"streamSettings");return r.getAtomStore().listen(o=>{(o===""||o===void 0)&&(n.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:r,streamSettings:n,streamSummary:i}},So=t=>{const e=new te(G(void 0),"enabled"),r=new te(G(ge.DISABLED),"status"),n=new ie(go(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new ie(yo(n.getAtomStore(),t),"organizationAdvertising"),o=vo(t),s=To(t);return{enabled:e,status:r,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:n,organizationAdvertising:i}};class Ao extends Rt{stores;constructor(e){const r=So(e),n=Xi(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 wo=(t,e,r)=>{t.store=new Ao(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([n,i])=>[n,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},r()},Eo=t=>{const{client:e}=t.createPromiseClient(xn.Leaderboard,{method:"list"});return r=>e.list(r)},Wn=t=>{const{client:e}=t.createPromiseClient(xn.Leaderboard,{method:"summary"});return r=>e.summary(r)},Io=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ar.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[]}}})},Oo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(z.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>(await r.get({eventId:s})).data?.attributes,revalidateInterval:0,dedupeTime:1e3*60*60})},ko=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(z.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const c=await n.syncQuestion({filter:{eventId:a}});if(c.data?.attributes?.question?.type!==v.QuestionType.PROMOTION)return c.data?.attributes},dedupeTime:1e3*60*10,revalidateInterval:0})},No=async(t,e)=>{const{client:r}=e.createPromiseClient(z.Feed,{method:"item",params:[t]});return(await r.item({id:t})).data},Co=(t,e)=>{const{client:r}=e.createStreamClient(z.Feed),n=X.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{n.set({eventId:o,feedId:""})}),e.addSubscription(r.subscription,n,{name:"feedSubscription"})},Lo=(t,e)=>{const{client:r}=e.createStreamClient(z.Feed);return e.addSubscription(r.questionSubscription,{questionId:t},{name:"questionSubscription"})},Hn=async(t,e)=>{const{client:r}=e.createPromiseClient(z.Feed,{method:"questionByUser",params:[t]});return(await r.questionByUser({questionId:t})).data?.attributes?.question},gt=(t,e)=>{const{client:r,queryKey:n,queryKeyStr:i}=e.createPromiseClient(z.Feed,{method:"questionByUser",params:[t]});let o=i;if(typeof t!="object"?o+=t:o+="atom",e.storeCache.has(o))return e.storeCache.get(o);{const s=e.nanoquery.createFetcherStore(n,{fetcher:async(a,u,c)=>(await r.questionByUser({questionId:c})).data?.attributes?.question,dedupeTime:1/0,revalidateInterval:0});return e.storeCache.set(o,s),s}},zn=async(t,e)=>{if(!t)return;const{client:r}=e.createPromiseClient(z.Feed,{method:"getQuestion",params:[t]}),n=await r.getQuestion({id:t});if(!n.data?.attributes)return;const{options:i,notification:o,...s}=n.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},Po=(t,e,r,n,i,o,s)=>{const{client:a,queryKey:u}=s.createPromiseClient(z.Feed,{method:"list",params:[t,e,o?"true":""]});return s.nanoquery.createFetcherStore(u,{fetcher:async(c,l,d,p,m)=>{if(!d||m)return[];const T=await a.list({eventId:d,filter:{types:p===Ae.ALLOWED?[]:[v.QuestionType.FACTOID,v.QuestionType.PROMOTION,v.QuestionType.TWEET],statuses:[v.QuestionStatus.ACTIVE,v.QuestionStatus.RESOLVED]}}),y={eventId:d,userId:r.get(),organizationId:n.get()};for(const E of T.data)i.isQuestionReceived(y,E.id)||(V.emit("poll",{action:"received",payload:{isAd:E.attributes?.adUnit==v.AdUnit.UNSET,questionId:E.id,questionType:E.attributes?.type}}),i.saveQuestionReceived(y,E.id));return T.data},dedupeTime:1/0,revalidateInterval:0})},Ro=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(z.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await r.list({eventId:s,filter:{types:[v.QuestionType.PROMOTION],statuses:[v.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return zn(u.id,e)},dedupeTime:1/0,revalidateInterval:0})},_o=(t,e,r,n,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(z.Feed,{method:"betPack",params:[t,e,r]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,c,l,d)=>{if(!c||!l||!d)return{timestamp:Date.now(),data:null};const p=await o.betPack({eventId:c,types:[v.QuestionType.PREDICTION],statuses:[v.QuestionStatus.ACTIVE,v.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?{timestamp:Date.now(),data:null}:{timestamp:Date.now(),data:p.data?.reduce((m,T)=>{const y=T?.attributes?.question;if(!y?.id)return m;const E={eventId:c,userId:l,organizationId:d};return n.isQuestionReceived(E,y.id)||(V.emit("poll",{action:"received",payload:{isAd:y?.adUnit==v.AdUnit.UNSET,questionId:y.id,questionType:y.type}}),n.saveQuestionReceived(E,y.id)),y.answers=y.answers.sort((O,w)=>O.id>w.id?1:-1),{...m,[y.id]:y}},{})}},dedupeTime:1/0,revalidateInterval:0})},Do=(t,e,r)=>{const n=X.batched([e,r],()=>{const a=e.get();if(!a)return;const u=r.get().data?.find(l=>l.id===a?.questionId),c=a?.question?.openedFrom;return u?(u.openedFrom=c,u):a.question}),i=X.batched(n,a=>a&&a.type==="question"?a.id:void 0),o=gt(i,t);return{$store:n,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,c=(l,d)=>{if(!l||!d)return(l||d||[]).sort((y,E)=>y.id>E.id?1:-1);const p=l.sort((y,E)=>y.id>E.id?1:-1),m=d.sort((y,E)=>y.id>E.id?1:-1),T=[];for(let y=0;y<p.length;y++)T.push({...p[y],...m[y],correct:p[y].correct,youVoted:p[y].youVoted,pointsEarned:p[y].pointsEarned});return T};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:c(u?.answers,a?.answers)})}}};var Qe;(function(t){t.SHOWED="showed",t.EVENT="ev"})(Qe||(Qe={}));class Fo extends Xe{constructor(){super("advertisement")}setShowed=e=>{this.write(Qe.SHOWED,e,"true")};isViewed=e=>this.read(Qe.SHOWED,e);fireEvent=(e,r)=>{this.write(Qe.EVENT,r,e,"true")};isEventFired=(e,r)=>this.read(Qe.EVENT,r,e)==="true"}const Uo=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:n,notification:i,...o}=e,s=n?.options.case==="promotion"?n.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},pt=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,Vo=({gamOptions:t,gamBaseUrl:e})=>{const r=`${e}?`,n=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")n.push(`${o}=${pt(s)}`);else if(Array.isArray(s))n.push(`${o}=${s.map(pt).join(",")}`);else{const a=Object.entries(s).map(([u,c])=>Array.isArray(c)?`${u}=${c.map(pt).join(",")}`:typeof c=="string"?`${u}=${pt(c)}`:`${u}=${c}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");n.push(`${o}=${a}`)}}return r+n.join("&")},Ve=t=>(t?.promotion?.type===v.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===v.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,xo=(t,e,r)=>{let n=!1;const i=r.transport,o=Z("advertisement"),s=new Fo,a=(w,I)=>{s.fireEvent(w,I)},u=(w,I)=>s.isEventFired(w,I),c=J({}),l=Ro(t,i),d=w=>{const I=c.get(),L=I.data?.question.id,k=I.data?.promotion?.type;if(!L)return;c.get()?.isOpened||(c.setKey("isOpened",!0),V.emit("advertisement",{action:"opened",payload:{id:L,type:k,hasBanner:Ve(I.data),openedFrom:w?.fromNotification?"notification":"auto"}})),w?.fromNotification&&(c.setKey("hasNotification",!1),V.emit("advertisement",{action:"notification-opened",payload:{id:L,type:k,hasBanner:Ve(I.data)}}))},p=()=>{const w=c.get(),I=w.data?.question.id,L=w.data?.promotion?.type,k=c.get()?.isOpened;I&&!k&&(o.debug({id:I},"markAsViewed: %o"),s.setShowed(I),c.setKey("isOpened",!0),V.emit("advertisement",{action:"viewed",payload:{id:I,type:L,hasBanner:Ve(w.data)}}))},m=(w,I)=>{I?c.set({loading:!1,error:void 0,data:I,hasNotification:I?.notification?.enabled===v.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>T(I.question.id),togglePause:L=>y(I.question.id,L),toggleMute:L=>E(I.question.id,L),isViewed:!!s.isViewed(I.question.id),fireEvent:L=>a(w,L),isEventFired:L=>u(w,L)}):(c.setKey("loading",!0),zn(w,i).then(L=>c.set({loading:!1,error:void 0,data:L,hasNotification:L?.notification?.enabled===v.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>T(L?.question.id),togglePause:k=>y(L?.question.id,k),toggleMute:k=>E(L?.question.id,k),isViewed:L&&!!s.isViewed(L.question.id),fireEvent:k=>a(w,k),isEventFired:k=>u(w,k)})).catch(L=>c.set({loading:!1,error:L,data:void 0,fireEvent:()=>{},isEventFired:()=>!1})))};c.subscribe((w,I)=>{if(!(w.data?.id===I?.data?.id&&w.isPaused!==I?.isPaused)){if(w.data?.promotion?.type===v.PromotionType.EXTERNAL_AD&&!w?.externalAd&&w.data.promotion.adCampaigns?.desktopWebSettings){const L=Vo(w.data.promotion.adCampaigns.desktopWebSettings);c.setKey("externalAd",{type:"gam",url:L})}w.data?.promotion&&!w.isOpened&&(V.emit("advertisement",{action:"received",payload:{id:w.data.question.id,type:w.data.promotion.type,hasNotification:!!w.hasNotification,hasBanner:Ve(w.data),isViewed:!!s.isViewed(w.data.question.id)},skipAnalytics:w.data.question.id===I?.data?.question.id}),w.data.question.id!==I?.data?.question.id&&!s.isViewed(w.data.question.id)&&V.emit("advertisement",{action:"notification-received",payload:{id:w.data.question.id,type:w.data.promotion.type,hasNotification:!0,hasBanner:Ve(w.data),isViewed:!1}})),!w?.data&&I?.data&&V.emit("advertisement",{action:"closed",payload:{id:I.data.question.id,type:I.data.promotion?.type,hasNotification:!!I.hasNotification,hasBanner:Ve(I.data),isViewed:!!s.isViewed(I.data.question.id)}})}});const T=w=>{(!w||c.get()?.data?.question.id===w)&&c.set({})},y=(w,I)=>{c.get()?.data?.question.id===w&&c.setKey("isPaused",I)},E=(w,I)=>{c.get()?.data?.question.id===w&&c.setKey("isMuted",I)};return{connect:()=>{n||(n=!0,l.subscribe((w,I)=>{w.data&&(!I?.data||w.data.id!==I.data.id)&&m(w.data.question.id,w.data)}),e.addListener("promotion",w=>{const I=Uo(w);if(I){if(I.question.status===v.QuestionStatus.RESOLVED){T(I.question.id),o.debug({promotion:I},"resolved: %o");return}if(I.question.status===v.QuestionStatus.ACTIVE){o.debug({promotion:I},"active: %o"),m(I.question.id,I);return}o.debug({promotion:I},"skip: %o")}}))},hide:T,show:m,open:d,markAsViewed:p,$store:c}};var ae;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.QUESTION_RECEIVED="q-received",t.QUESTION_OPENED="q-opened"})(ae||(ae={}));class Bo extends Xe{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,r)=>{this.write(...e,r)};readValue=e=>this.read(...e)}class Mo extends Xe{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new Bo}saveQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.QUESTION_RECEIVED,n,e,r,i,"1")};isQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(ae.QUESTION_RECEIVED,n,e,r,i);saveQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.QUESTION_OPENED,n,e,r,i,"1")};isQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(ae.QUESTION_OPENED,n,e,r,i);saveOnboardingStatus=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.ONBOARDING,n,e,r,i)};getOnboardingStatus=({userId:e,eventId:r,organizationId:n})=>this.read(ae.ONBOARDING,n,e,r);setOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{this.sessionStorage.writeValue([ae.ONBOARDING_IO,n,e,r],"1")};getOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>this.sessionStorage.readValue([ae.ONBOARDING_IO,n,e,r])}var Ae;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Ae||(Ae={}));class qo{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=Z("gamification-background"),this.storage=new Mo,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new te(G(void 0),"moderationId").getStore(),this.interactiveAllowed=new te(G(Ae.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new te(G(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new ie(Oo(this.slStreamId,e.transport),"gamification:moderation");const r=!!e.sdk.options.get().betPack;this.feedList=new ie(Po(this.slStreamId,this.interactiveAllowed,this.userId,this.organizationId,this.storage,r,e.transport),"gamification:feedList"),this.betPack=new ie(_o(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=ko(this.slStreamId,r,e.transport),this.openedQuestion=Do(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(n=>{this.log.debug({item:n},"received question"),n?.questionId?(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0),this.questionSubscription=Lo(n.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",i=>{const o=i.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(o),this.betPack&&o?.type===v.QuestionType.PREDICTION&&(o.status===v.QuestionStatus.ACTIVE||o.status===v.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data?.data||{},a=s?.[o.id];if(a){const u=[],c=a.answers.sort((d,p)=>d.id>p.id?1:-1),l=o.answers.sort((d,p)=>d.id>p.id?1:-1);for(let d=0;d<c.length;d++)u.push({...c[d],...l[d],correct:c[d].correct,youVoted:c[d].youVoted,pointsEarned:c[d].pointsEarned});this.betPack.getStore().mutate({timestamp:Date.now(),data:{...s,[o.id]:{...a,status:o.status,marketClosed:o.marketClosed,activatedAt:o.activatedAt,answerSetAt:o.answerSetAt,answers:u}}})}}}),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=Co(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async n=>{const i=n.data?.attributes?.question;if(this.betPack&&i?.type===v.QuestionType.PREDICTION&&(i.status===v.QuestionStatus.ACTIVE||i.status===v.QuestionStatus.RESOLVED)){const o=this.betPack.getValues().data?.data||{},s=o?.[i.id];if(s)this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:{...s,status:i.status,marketClosed:i.marketClosed,activatedAt:i.activatedAt,answerSetAt:i.answerSetAt}}});else if(!s&&Object.keys(o).length<5){const a=await Hn(i.id,this.transport);this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:a}})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",n=>{const i=this.activeQuestionId.get().data?.question?.id,o=n.data?.attributes?.question;if(!(!o||o.type===v.QuestionType.PROMOTION)){if(o.status===v.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(n.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",n=>{window.requestAnimationFrame(()=>{n.data?.attributes?.question===void 0&&n.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((n,i)=>{n.data?.feedItem&&n.data?.feedItem?.id!==i?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:n.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:n.data.feedItem.id})),hasNotification:!0,type:n.data.feedItem.type}),!n.data?.feedItem&&i?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:i.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:i.data.feedItem.id})),hasNotification:!0,type:i.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const n of this.cancels)n(),this.cancels.delete(n)}),r||(this.advertisement=xo(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 $o{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=Z("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=G(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}V.emit("notification",{action:"received",payload:{type:r.type,questionId:r.data.questionId,questionType:r.data.questionType}});const n=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(r.id,r),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:r.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},r.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},r.delay||0);this.timeouts.set(e,n),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:r=!0}={})=>{const n=new Map(this.notificationsList.get()),i=n.get(e);if(i){const o=!(this.waitingQueue.size>=this.options.concurrency)&&r;i.hiding=o,this.notificationsList.set(n);const s=()=>{const a=new Map(this.notificationsList.get());a.delete(e),this.notificationsList.set(a);const u=this.timeouts.get(e);u!==void 0&&(clearTimeout(u),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&V.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})};if(o){const a=setTimeout(s,this.options.animationDelay||0);this.timeouts.set(e,a)}else s()}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 Et;(function(t){t.OPENED="opened"})(Et||(Et={}));class jo extends Xe{constructor(){super("notification")}setOpened=e=>{this.write(Et.OPENED,e,"true")};isOpened=e=>this.read(Et.OPENED,e);clearNotification=()=>{this.clear()}}class Qo{queue;storage;constructor(e={}){this.storage=new jo,this.queue=new $o({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),V.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)};update=(e,r)=>{const n=this.queue.notificationsList.get()?.get(e);r(n)};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 Go=(t,e,r)=>{t.notifications=new Qo(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 ze;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(ze||(ze={}));const Kr=async(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(z.Feed,{method:"submitAnswer"}),i=n({retryAttempts:0});try{return await r.submitAnswer({data:e},{contextValues:i})}catch(o){throw j.ConnectError.from(o)?.code===j.Code.AlreadyExists?new Error(ze.ALREADY_VOTED):new Error(ze.UNKNOWN)}},Yn=(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(z.Feed,{method:"submitInplay"}),i=n({retryAttempts:0});return r.submitInplay({data:{eventId:+e}},{contextValues:i})},Ko={pageSize:10},Wo=(t,e,r,n,i)=>{let o=0;const s=G({pageSize:Ko.pageSize,page:0}),a=J({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Eo(t),c=async()=>{const p=e.get(),m=n?.getStore().get().data?.map(T=>T.slId)||[];if(p&&m?.length){const T=r.get();T&&m.push(T),a.setKey("loading",!0),a.setKey("data",[]);const E=await u({eventId:p,usersIds:m,leaderboardId:""});a.set({data:E.data.map((O,w)=>({...O.attributes,friendsRank:w+1})),hasMore:!1,key:Date.now(),loading:!1}),E.meta&&(o=Math.round(E.meta.count/E.meta.pageSize))}},l=()=>{c()},d=p=>{const m=s.get(),T=p||m.page+1;T<=o&&s.set({...m,page:T})};return X.onMount(a,()=>{const p=e.listen(c),m=n?.listen(c);return()=>{p(),m?.()}}),{$store:a,fetchMore:d,invalidate:l}};class Ho extends Xe{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Wr="sldl",_t="sldl_uid",Jn="sldl_eid",Xn="sldl_e_eid",zo=new Set([_t,Jn,Xn]),Hr=t=>{const e={},r={};for(const[n,i]of t)zo.has(n)?e[n]=i:r[n]=i;return{result:e,remain:r}},Yo=({hash:t,search:e})=>{if(t&&t.includes(Wr)){const r=new URLSearchParams(t.substr(1));return{hash:Hr(r)}}if(e&&e.includes(Wr)){const r=new URLSearchParams(e);return{search:Hr(r)}}return null},zr=Z("deep_link"),le={debug:(...t)=>{zr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{zr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Jo=(t,e)=>{const{hash:r,search:n}=window.location;if(le.debug({hash:r,search:n},"get deep link data from"),r||n){const i=Yo({hash:r,search:n});if(le.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 c=Object.keys(u).length!==0;if(o){let l="";c&&(l=`#${new URLSearchParams(u).toString()}`,le.debug({updatedHash:l},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+l)}if(s){let l="";c&&(l=`?${new URLSearchParams(u).toString()}`,le.debug({updatedSearch:l},"update search")),window.history.replaceState(null,"",window.location.pathname+l+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},Xo=(t,e,r)=>{const n=new Ho,i=n.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){le.debug(a)}t.deepLink={$store:new Ne(J(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{le.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[_t]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),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")&&le.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{le.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),le.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{le.trace("called handler"),u(a)}catch(c){console.error(c)}};Jo(t.deepLink.$store,s),r()},Zo=Z("bypass");class es extends Ji{$coreStore;deepLink;transport;bypassLogin;constructor(e,r,n){super(),this.$coreStore=e,this.deepLink=n,this.transport=r,this.bypassLogin=ho(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?.[_t];Zo.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 je().clear()};softLogout=()=>{const e=new je;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const r=new je,n=r.getToken(),i=r.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),n)return this.saveUser(n,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(n,s)}return o});if(i&&!n&&!e){const o=r.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,r)=>{this.transport.setAuth(e,r),this.$coreStore.getValues().userToken.setValue(e),new je().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 tt=new je,ts=(t,e,r)=>{t.auth=new es(t.store,t.transport,t.deepLink),t.stores.status.listen(n=>{n===ge.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(n,i)=>{if(!(tt.getSchema()===n&&tt.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(n,i),tt.setSchema(n),tt.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),tt.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),r()},Yr=Z("video_player"),ft={debug:(...t)=>{Yr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Yr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},rs=(t,e,r)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=n=>{ft.trace("adding video player controller"),t.videoPlayer.controllers.add(n)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=n=>{ft.trace("removing video player controller"),t.videoPlayer.controllers.delete(n)},t.sdk.controlVideoPlayer=n=>{ft.trace("controlling video player");for(const i of t.videoPlayer.controllers){ft.trace("calling video player controller");try{i(n)}catch(o){console.error(o)}}},r()},ns={[v.QuestionType.FACTOID]:"insight",[v.QuestionType.POLL]:"poll",[v.QuestionType.TRIVIA]:"trivia",[v.QuestionType.PREDICTION]:"prediction",[v.QuestionType.TWEET]:"tweet"},xe=t=>t===v.PromotionType.INGAME_IAB11||t===v.PromotionType.INGAME_IAB21||t===v.PromotionType.NFL_SHOP_OVERLAY||t===v.PromotionType.SHOP_OVERLAY,is=(t,e,r)=>{t.sdk.uiState=J({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appBanner:!1,appSidebar:!1,appNotification:!1,app:!1})},enableExposedPauseAd:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),exposedPauseAd:!0})},disableExposedPauseAd:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),exposedPauseAd:!1})}},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const n=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.enableAppNotification(),t.ui.onContentActivate){const s=o.type||i&&ns[i]||"question";t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="exposedPauseAd")switch(a.slEventBus.action){case"enabled":t.ui.enableExposedPauseAd();break;case"disabled":t.ui.disableExposedPauseAd();break}if(a.slEventBus?.type==="app")switch(a.slEventBus.action){case"open":t.ui.enableApp();break;case"close":t.ui.disableApp();break}if(a.slEventBus?.type==="poll"){const u=a.slEventBus.action,{hasBanner:c}=a.slEventBus.payload;switch(u){case"onboardingOpen":t.sdk.uiState.set({app:!0});break;case"opened":t.sdk.uiState.set({...t.sdk.uiState.get(),appBanner:c,appSidebar:!0});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),appBanner:!1,appSidebar:!1});break}}if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===ve.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:c,hasBanner:l,id:d,isViewed:p,type:m}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:m===v.PromotionType.EXTERNAL_AD,promotionBanner:l,promotionNotification:!1,promotionOverlay:xe(m),promotionSidebar:!xe(m)});break;case"received":if(t.sdk.closeFeature(),n({stage:"activate",id:d,hasNotification:c,hasBanner:l,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:l,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:xe(m),promotionSidebar:!xe(m),promotionExternalAd:m===v.PromotionType.EXTERNAL_AD});break}c?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:l,promotionOverlay:xe(m),promotionSidebar:!xe(m),promotionExternalAd:m===v.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),n({stage:"deactivate",id:d,hasNotification:c,hasBanner:l,isViewed:p});break}}},o=V.listen(i),s=t.activeFeature.subscribe(a=>{a||t.ui.disableApp()});return()=>{o(),s()}}),r()},os=(t,e,r)=>{const n={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=J(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const c=o.get(s);c&&c(),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(ge.INITIALIZATION);try{const a=await t.stores.organizationSettings.getValue();return a?(t.stores.status.setValue(ge.READY),{enabled:!!a}):(t.stores.status.setValue(ge.FAILED),{err:"failed"})}catch(a){return t.stores.enabled.setValue(),t.stores.status.setValue(ge.FAILED),{err:`${a}`}}},t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(ge.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=(s,a)=>{a?t.stores.slStreamId.getStore().set({loading:!1,data:s}):t.stores.providerStreamId.setValue(s)},r()},ss=(t,e)=>{const{client:r,queryKey:n}=t.createPromiseClient(ot.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,revalidateInterval:0})},as=(t,{web:e,mobile:r})=>{const{client:n}=t.createPromiseClient($i.LinksClient,{method:"generate"});return n.generate({web:e,mobile:r})},Jr=(t,e)=>{const r=new URLSearchParams(t);for(const[n,i]of Object.entries(e))r.append(n,i);return r.toString()},us=(t,e,r,n)=>{const i=J({});return X.onMount(i,()=>ss(t,[e,r]).subscribe(async({data:a,loading:u})=>{const c=a===void 0&&u===!1?"https://streamlayer.io":a?.url,l=n.get()||"",d=e.get()||"",p=r.get()||"",m={[_t]:l,[Jn]:d,[Xn]:p};if(!u&&c){i.setKey("loading",!0);let T=window.location.search,y=window.location.hash;T&&y||y?T=`?${Jr(T,m)}`:y=`#${Jr("",m)}`;const E=window.location.origin+window.location.pathname+T+y;try{const O=await as(t,{web:E,mobile:c});i.set({data:O.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 $;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})($||($={}));const cs=(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,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:v.QuestionType.UNSET,onboarding:{...i,instantOpen:!n.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),markIstantOpen:()=>{n.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),r.update(o,s=>{s?.data?.onboarding&&(s.data.onboarding.instantOpen=!0)})}}}})},ht=(t,e,r,n,i,o,s,a)=>{try{const u=e.userId.get(),c=e.organizationId.get(),l=e.slStreamId.get();if(!u||!c||!l)return;const d=i.getOnboardingStatus({userId:u,organizationId:c,eventId:l});if(d===$.Completed||a?.skipOnboarding){t.set($.Completed);for(const E of o)E();a?.skipOnboarding&&d!==$.Completed&&(i.saveOnboardingStatus({organizationId:c,userId:u,eventId:l},$.Completed),Yn(s,l));return}const p=e.moderation.getStore().value?.data,m=r.featureSettings.get().inplayGame;if(p===void 0||m===void 0)return;const T=p?.options?.onboardingEnabled,y=m?.titleCard?.optIn;T?y?t.set($.Required):t.set($.Optional):(y?t.set($.Unavailable):t.set($.Disabled),n.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},Xr=(t,e,r,n,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=G($.Unset);a.subscribe(l=>{l!==$.Unset&&(l===$.Optional||l===$.Required?o===!1&&(cs(t,e,n,s),o=!0):t.onboardingProcessed.set(!0),l===$.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==$.Completed&&(u.push(e.userId.listen(l=>{l&&ht(a,e,t,n,s,u,r,i)})),u.push(e.moderation.listen(l=>{l.data&&ht(a,e,t,n,s,u,r,i)})),u.push(t.featureSettings.listen(l=>{l&&ht(a,e,t,n,s,u,r,i)}))),ht(a,e,t,n,s,u,r,i),{$store:a,submitInplay:async()=>{const l=e.slStreamId.get();if(l){await Yn(r,l),a.set($.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:l},$.Completed),V.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const d=e.getCurrentSessionId({prefix:"onboarding"});n.close(d)}}}},ls=(t,e,r,n)=>{const i=J(void 0),o=Wn(n),s=async()=>{const u=t.get(),c=e.get(),l=r?r.getStore().get().data?.map(m=>m.slId):[];if(!l||!u||!c)return;const d={eventId:u,userId:c,leaderboardId:"",usersIds:[...l,c]},p=await o(d);i.set(p.data?.attributes)},a=()=>{s()};return X.onMount(i,()=>{a();const u=t.listen(s),c=r?.listen(s),l=e.listen(s);return()=>{u(),c?.(),l()}}),{$store:i,invalidate:a}},ds=async(t,e,r,n,i)=>{const o=Wn(i),s=t.get(),a=e.get(),u=r?.getStore().get().data?.map(p=>p.slId)||[],c={eventId:s,userId:n,leaderboardId:"",usersIds:[...u,a]};return(await o(c)).data?.attributes?.summary},Zr=new Set([v.QuestionType.POLL,v.QuestionType.PREDICTION,v.QuestionType.TRIVIA]);class ps extends Gn{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,r,n){if(super(e,r),this.background=new qo(n),this.advertisement=this.background.advertisement,this.onQuestionActivate=n.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=G(!n.sdk.withAuth),this.leaderboardId=new te(G(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=n.notifications,this.transport=n.transport,this.closeFeature=(i=!0)=>n.sdk.closeFeature(i),this.openFeature=()=>n.sdk.openFeature(M.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=us(this.transport,this.background.slStreamId,n.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=ls(this.background.slStreamId,this.background.userId,this.friends,this.transport),!n.sdk.options.get().hideFriends){this.friends=new ie(Io(this.background.userId,n.transport),"gamification:friends"),this.openedUser=G(void 0);const i=this.leaderboardList=Wo(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.skipOnboarding=!!n.sdk.options.get().skipOnboarding,this.onboardingStatus=Xr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding}),n.sdk.options.get().skipOnboarding||(this.onboardingStatus=Xr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding})),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==$.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=G(!1),this.cancels.add(n.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{n.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),n.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Ae.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Ae.ALLOWED);else{const e=this.onboardingStatus.$store.get(),r=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,n=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===$.Completed,o=!r||i||n!==!0;this.background.interactiveAllowed.set(o?Ae.ALLOWED:Ae.DISALLOWED)}};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const r=e.data?.attributes?.question,n=e.data?.attributes?.feedItem;if(!r||!n?.attributes)return;const{status:i,type:o,id:s,answers:a}=r;if(i===v.QuestionStatus.RESOLVED&&o===v.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),c=[...this.feedList.getValues().data||[]],l=c.findIndex(I=>I.id===s),d=c[l];let p=d?.attributes?.attributes?.value?.answerId;const m=gt(s,this.transport),T=m.subscribe(()=>{});await m.fetch();let y=m.get().data;y||(y=await Hn(s,this.transport),m.mutate(y)),T(),window.requestAnimationFrame(()=>{m.invalidate()}),p||(p=y?.answers.find(({youVoted:I})=>I)?.id);const E=a.find(({correct:I})=>I),O=p?a.find(({id:I})=>I===p):void 0,w=!!O?.correct;if(d&&c[l]?.attributes?.attributes.case==="question"){try{c[l].attributes.attributes.value.answerId=p,c[l].attributes.attributes.value.openForVoting=!1,p&&(c[l].attributes.attributes.value.status=w?z.PickHistoryStatus.WON:z.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(c)}if(!O||!E)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:w?15e3:14e3,id:u,emitEvent:!1,data:{questionId:s,questionType:v.QuestionType.PREDICTION,question:{title:w?`Congratulations! You answered correctly! You won ${E.points} pts!`:`Better luck next time! Correct: ${E?.text}!`,votedAnswer:{title:O?.text,points:O?.points},correctAnswerTitle:E?.text,correct:!!w,predictionResult:!0,questionTitle:r?.subject},inApp:{notification:r.notification,appearance:r.appearance,sponsorship:r.sponsorship,adUnit:r?.adUnit,sponsorLogo:r.promotion?.sponsor?.logo}}}),this.userSummary.invalidate()}})),X.onStart(this.feedList.getStore(),()=>{this.cancels.add(this.feedList.subscribe(()=>{}))}),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!==v.QuestionStatus.ACTIVE&&n.attributes.status!==v.QuestionStatus.RESOLVED)&&!(!this.isInteractiveAllowed&&Zr.has(n.attributes.type)&&n?.attributes?.adUnit!==v.AdUnit.STANDART)){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===!1?!1:n.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),V.emit("poll",{action:"received",payload:{isAd:n.attributes?.adUnit==v.AdUnit.UNSET,questionId:n.id,questionType:n.attributes?.type}})),this.feedList.getStore().mutate(r)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,r)=>{if(!this.betPack)return;try{await Kr(this.transport,{questionId:e,answerId:r})}catch(o){if(o.message===ze.ALREADY_VOTED){const s=gt(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const n={...this.betPack.getValues().data?.data},i=n?.[e];i&&(V.emit("poll",{action:"voted",payload:{questionId:e,isAd:i?.adUnit==v.AdUnit.UNSET,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===r?{...o,youVoted:!0}:o),this.betPack.getStore().mutate({data:n,timestamp:Date.now()}))};submitAnswer=async(e,r)=>{const n=gt(e,this.transport),i=n.subscribe(()=>{}),o={...n.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(d=>d.id===e),c=a[u],l=c?.attributes?.attributes.case==="question"&&c.attributes.attributes.value;if(l){V.emit("poll",{action:"voted",payload:{isAd:c.attributes?.adUnit==v.AdUnit.UNSET,questionId:e,questionType:l.questionType}});const d=n.get().data;if(i(),d){const p=d.answers.find(E=>E.correct===!0),m=d.answers.findIndex(E=>E.id===r),T=d.answers[m],y=d.answers.every(({percentageDecimal:E},O)=>E===o?.answers[O].percentageDecimal);a[u].attributes.attributes.value.answerId=r,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=T?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===r?z.PickHistoryStatus.WON:z.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),d.answers[m].correct=p?.id===r,d.answers[m].youVoted=!0,y&&d.answers.forEach(E=>{E.percentageDecimal=0}),p?.id===r&&(d.answers[m].pointsEarned=d.status===v.QuestionStatus.RESOLVED?0:p.points),n.mutate({...d})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Kr(this.transport,{questionId:e,answerId:r}),s()}catch(a){if(a.message===ze.ALREADY_VOTED){this.userSummary.invalidate();const u=n.subscribe(()=>{});n.invalidate(),u()}throw a}};openQuestion=(e,r)=>{if(!e)return()=>{};const n=r?.openedFrom==="bet-pack";this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=r?.attributes?.type,o=r?.attributes?.adUnit===v.AdUnit.STANDART&&!!r?.attributes?.adPromotion?.banner?.imageUrl;if(!i&&!n){const u=(this.feedList.getStore().value?.data||[]).find(c=>c.id===e)?.attributes;i=u?.type,o=u?.adUnit===v.AdUnit.STANDART&&!!u?.adPromotion?.banner?.imageUrl}const s={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return V.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,isAd:r?.attributes?.adUnit==v.AdUnit.UNSET,questionOpenedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom,hasBanner:o}}),this.storage.isQuestionOpened(s,e)||(V.emit("poll",{action:"viewed",payload:{questionId:e,questionType:i,isAd:r?.attributes?.adUnit==v.AdUnit.UNSET,questionOpenedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}}),this.storage.saveQuestionOpened(s,e)),n||this.openFeature(),this.background.openQuestion(e,r?{...r,openedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}:void 0)};getFeedItem=e=>No(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&(this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),V.emit("poll",{action:"closed",payload:{questionId:e}})),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const r=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!r){this.openedUser?.set(r);return}if(r.summaryLoaded){this.openedUser?.set(r);return}const n={...r};try{const i=await ds(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)};openOnboarding=()=>{this.openFeature(),V.emit("poll",{action:"onboardingOpen",payload:{}})};showInApp=e=>{const r=this.onboardingStatus.$store.get(),n=e?.data?.question?.adUnit===v.AdUnit.STANDART;if(e&&e.data&&(n||r&&r!==$.Unset)&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==v.SilenceSetting.ON&&e.data.question.status===v.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Zr.has(e.data.question.type))(this.isInteractiveAllowed||n)&&e.data.question.notification!==void 0&&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},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship,adUnit:e.data.question?.adUnit,sponsorLogo:e.data.question.promotion?.sponsor?.logo}}});else if(e.data.question.type===v.QuestionType.FACTOID){const i=e.data.question.options?.options.value,o=e.data.question.notification?.useContentTexts===v.NotificationUseContentTexts.ENABLED?e.data.question.subject:e.data.question.notification?.title||"",s=e.data.question.notification?.useContentTexts===v.NotificationUseContentTexts.ENABLED?i.body:e.data.question.notification?.body,a={heading:o,body:s,imageMode:i?.imageMode,image:i?.image,video:{id:i?.video?.id||"",url:i?.video?.url||"",thumbnailUrl:i?.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:a,inApp:{useMediaFromContent:i?.useAsNotification===v.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship,adUnit:e.data.question?.adUnit,sponsorLogo:e.data.question.promotion?.sponsor?.logo,isVideo:i?.mode===v.FactoidMediaMode.VIDEO}}})}else if(e.data.question.type===v.QuestionType.TWEET&&e.data.question.notification!==void 0){const i=e.data.question.options?.options.value,o={image:"",video:""};if(i.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const a=i.tweetMeta.tweet.meta.extendedEntities.media;if(a){const u=a.find(({type:c})=>c==="photo")||a[0];o.image=u.mediaUrlHttps,u.type==="video"&&(o.video=u.url)}}const s={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:i?.tweetMeta?.account||"",accountVerified:!!i?.tweetMeta?.accountVerified,tweet:i?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:o};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:s,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const fs={[M.SdkOverlayType.GAMES]:!0};class hs extends Gn{constructor(e,r){super(e,r)}}const ms=(t,e,r)=>t.type===M.SdkOverlayType.GAMES?new ps(t,e,r):new hs(t,e),gs=(t,e,r)=>{t.features=new Map,t.sdk.featuresList=new te(G(new Set),"features-list"),t.activeFeature=new te(G(M.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=n=>t.features.get(n),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=n=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(n)})},t.sdk.closeFeature=(n=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(M.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=me.ORGANIZATION)=>{if(n.type in fs&&!t.features.has(n.type)){const o=ms(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,me.ORGANIZATION)},t.stores.providerStreamId.listen(n=>{n||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const n=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===me.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(me.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{n(me.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},r()},ys=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(qr.PolymarketSportsClient,{method:"getMarketWithSeries",params:[t,e]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(u)try{return(await n.getMarketWithSeries({eventId:a,timeframe:qr.Timeframe.TIMEFRAME_ALL})).event}catch{return}}})},bs=t=>{const e=t.stores.slStreamId.getAtomStore(),r=t.stores.user.getAtomStore();return ys(e,r,t.transport)};class vs extends Qn{marketWithSeries;log;constructor(e){super(),this.log=Z("polymarket"),this.marketWithSeries=bs(e)}connect=()=>{this.log.debug("connect")};disconnect=()=>{this.marketWithSeries.off(),this.log.debug("disconnect")}}const Ts=(t,e,r)=>{t.sdk.polymarket=new vs(t),t.sdk.onMount({name:"polymarket"},()=>(t.sdk.polymarket.connect(),()=>{t.sdk.polymarket.disconnect()})),r()};function wr(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:t.id||null,adId:t.adId||null,sequence:t.sequence||null,apiFramework:t.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}const Ss=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function en(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const n=[],i=ei(t);!e.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(e.ERRORCODE)||(e.ERRORCODE=900),e.CACHEBUSTING=ni(Math.round(1e8*Math.random())),e.TIMESTAMP=new Date().toISOString(),e.RANDOM=e.random=e.CACHEBUSTING;for(const o in e)e[o]=ri(e[o]);for(const o in i){const s=i[o];typeof s=="string"&&n.push(Zn(s,e))}return n}function Zn(t,e){const r=(t=tn(t,e)).match(/[^[\]]+(?=])/g);if(!r)return t;let n=r.filter(i=>Ss.indexOf(i)>-1);return n.length===0?t:(n=n.reduce((i,o)=>(i[o]=-1,i),{}),tn(t,n))}function tn(t,e){let r=t;for(const n in e){const i=e[n];r=r.replace(new RegExp("(?:\\[|%%)(".concat(n,")(?:\\]|%%)"),"g"),i)}return r}function ei(t){return Array.isArray(t)?t.map(e=>e&&e.hasOwnProperty("url")?e.url:e):t}function rn(t){return/^(https?:\/\/|\/\/)/.test(t)}function nn(t,e){for(let r=0;r<e.length;r++)if(ti(e[r],t))return!0;return!1}function ti(t,e){if(t&&e){const r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertyNames(e);return r.length===n.length&&t.id===e.id&&t.url===e.url}return!1}function ri(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>"%".concat(e.charCodeAt(0).toString(16)))}function ni(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:8;return t.toString().padStart(e,"0")}const Pe={track:function(t,e,r){en(t,e,r).forEach(n=>{typeof window<"u"&&window!==null&&(new Image().src=n)})},resolveURLTemplates:en,extractURLsFromTemplates:ei,filterUrlTemplates:function(t){return t.reduce((e,r)=>{const n=r.url||r;return rn(n)?e.validUrls.push(n):e.invalidUrls.push(n),e},{validUrls:[],invalidUrls:[]})},containsTemplateObject:nn,isTemplateObjectEqual:ti,encodeURIComponentRFC3986:ri,replaceUrlMacros:Zn,isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},flatten:function t(e){return e.reduce((r,n)=>r.concat(Array.isArray(n)?t(n):n),[])},joinArrayOfUniqueTemplateObjs:function(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];const r=Array.isArray(t)?t:[],n=Array.isArray(e)?e:[];return r.concat(n).reduce((i,o)=>(nn(o,i)||i.push(o),i),[])},isValidTimeValue:function(t){return Number.isFinite(t)&&t>=-2},addLeadingZeros:ni,isValidUrl:rn,isBrowserEnvironment:function(){return typeof window<"u"},formatMacrosValues:function(t){return typeof t!="object"?t:JSON.stringify(t)}};function on(t){return["true","TRUE","True","1"].includes(t)}function As(t){if(t==null)return-1;if(Pe.isNumeric(t))return parseInt(t);const e=t.split(":");if(e.length!==3)return-1;const r=e[2].split(".");let n=parseInt(r[0]);r.length===2&&(n+=parseFloat("0.".concat(r[1])));const i=parseInt(60*e[1]),o=parseInt(60*e[0]*60);return isNaN(o)||isNaN(i)||isNaN(n)||i>3600||n>60?-1:o+i+n}const f={childByName:function(t,e){return Array.from(t.childNodes).find(r=>r.nodeName===e)},childrenByName:function(t,e){return Array.from(t.childNodes).filter(r=>r.nodeName===e)},resolveVastAdTagURI:function(t,e){if(!e)return t;if(t.startsWith("//")){const{protocol:r}=location;return"".concat(r).concat(t)}if(!t.includes("://")){const r=e.slice(0,e.lastIndexOf("/"));return"".concat(r,"/").concat(t)}return t},parseBoolean:on,parseNodeText:function(t){return t&&(t.textContent||t.text||"").trim()},copyNodeAttribute:function(t,e,r){const n=e.getAttribute(t);n&&r.setAttribute(t,n)},parseAttributes:function(t){return Array.from(t.attributes).reduce((e,r)=>(e[r.nodeName]=r.nodeValue,e),{})},parseDuration:As,getStandAloneAds:function(){return(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).filter(t=>!parseInt(t.sequence,10))},getSortedAdPods:function(){return(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).filter(t=>parseInt(t.sequence,10)).sort((t,e)=>t.sequence-e.sequence)},assignAttributes:function(t,e){t&&Array.from(t).forEach(r=>{let{nodeName:n,nodeValue:i}=r;if(n&&i&&e.hasOwnProperty(n)){let o=i;typeof e[n]=="boolean"&&(o=on(o)),e[n]=o}})},mergeWrapperAdData:function(t,e){var r;t.errorURLTemplates=e.errorURLTemplates.concat(t.errorURLTemplates),t.impressionURLTemplates=e.impressionURLTemplates.concat(t.impressionURLTemplates),t.extensions=e.extensions.concat(t.extensions),e.viewableImpression.length>0&&(t.viewableImpression=[...t.viewableImpression,...e.viewableImpression]),t.followAdditionalWrappers=e.followAdditionalWrappers,t.allowMultipleAds=e.allowMultipleAds,t.fallbackOnNoAd=e.fallbackOnNoAd;const n=(e.creatives||[]).filter(a=>a&&a.type==="companion"),i=n.reduce((a,u)=>((u.variations||[]).forEach(c=>{(c.companionClickTrackingURLTemplates||[]).forEach(l=>{Pe.containsTemplateObject(l,a)||a.push(l)})}),a),[]);t.creatives=n.concat(t.creatives);const o=e.videoClickTrackingURLTemplates&&e.videoClickTrackingURLTemplates.length,s=e.videoCustomClickURLTemplates&&e.videoCustomClickURLTemplates.length;if(t.creatives.forEach(a=>{if(e.trackingEvents&&e.trackingEvents[a.type])for(const u in e.trackingEvents[a.type]){const c=e.trackingEvents[a.type][u];Array.isArray(a.trackingEvents[u])||(a.trackingEvents[u]=[]),a.trackingEvents[u]=a.trackingEvents[u].concat(c)}a.type==="linear"&&(o&&(a.videoClickTrackingURLTemplates=a.videoClickTrackingURLTemplates.concat(e.videoClickTrackingURLTemplates)),s&&(a.videoCustomClickURLTemplates=a.videoCustomClickURLTemplates.concat(e.videoCustomClickURLTemplates)),!e.videoClickThroughURLTemplate||a.videoClickThroughURLTemplate!==null&&a.videoClickThroughURLTemplate!==void 0||(a.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate)),a.type==="companion"&&i.length&&(a.variations||[]).forEach(u=>{u.companionClickTrackingURLTemplates=Pe.joinArrayOfUniqueTemplateObjs(u.companionClickTrackingURLTemplates,i)})}),e.adVerifications&&(t.adVerifications=t.adVerifications.concat(e.adVerifications)),e.blockedAdCategories&&(t.blockedAdCategories=t.blockedAdCategories.concat(e.blockedAdCategories)),(r=e.creatives)!==null&&r!==void 0&&r.length){const a=e.creatives.filter(u=>{var c;return((c=u.icons)===null||c===void 0?void 0:c.length)&&!u.mediaFiles.length});a.length&&(t.creatives=t.creatives.concat(a))}}};function ws(t,e){const r=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=wr(n);return{id:i,adId:o,sequence:s,apiFramework:a,type:"companion",required:null,variations:[]}}(e);return r.required=t.getAttribute("required")||null,r.variations=f.childrenByName(t,"Companion").map(n=>{const i=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:a.id||null,adType:"companionAd",width:a.width||0,height:a.height||0,assetWidth:a.assetWidth||null,assetHeight:a.assetHeight||null,expandedWidth:a.expandedWidth||null,expandedHeight:a.expandedHeight||null,apiFramework:a.apiFramework||null,adSlotId:a.adSlotId||null,pxratio:a.pxratio||"1",renderingMode:a.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(f.parseAttributes(n));i.htmlResources=f.childrenByName(n,"HTMLResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat(c):a},[]),i.iframeResources=f.childrenByName(n,"IFrameResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat(c):a},[]),i.staticResources=f.childrenByName(n,"StaticResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat({url:c,creativeType:u.getAttribute("creativeType")||null}):a},[]),i.altText=f.parseNodeText(f.childByName(n,"AltText"))||null;const o=f.childByName(n,"TrackingEvents");o&&f.childrenByName(o,"Tracking").forEach(a=>{const u=a.getAttribute("event"),c=f.parseNodeText(a);u&&c&&(Array.isArray(i.trackingEvents[u])||(i.trackingEvents[u]=[]),i.trackingEvents[u].push(c))}),i.companionClickTrackingURLTemplates=f.childrenByName(n,"CompanionClickTracking").map(a=>({id:a.getAttribute("id")||null,url:f.parseNodeText(a)})),i.companionClickThroughURLTemplate=f.parseNodeText(f.childByName(n,"CompanionClickThrough"))||null;const s=f.childByName(n,"AdParameters");return s&&(i.adParameters={value:f.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),i}),r}function Es(t,e){let r;const n=function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:c,adId:l,sequence:d,apiFramework:p}=wr(u);return{id:c,adId:l,sequence:d,apiFramework:p,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(e);n.duration=f.parseDuration(f.parseNodeText(f.childByName(t,"Duration")));const i=t.getAttribute("skipoffset");if(i==null)n.skipDelay=null;else if(i.charAt(i.length-1)==="%"&&n.duration!==-1){const u=parseInt(i,10);n.skipDelay=n.duration*(u/100)}else n.skipDelay=f.parseDuration(i);const o=f.childByName(t,"VideoClicks");if(o){const u=f.childByName(o,"ClickThrough");n.videoClickThroughURLTemplate=u?{id:u.getAttribute("id")||null,url:f.parseNodeText(u)}:null,f.childrenByName(o,"ClickTracking").forEach(c=>{n.videoClickTrackingURLTemplates.push({id:c.getAttribute("id")||null,url:f.parseNodeText(c)})}),f.childrenByName(o,"CustomClick").forEach(c=>{n.videoCustomClickURLTemplates.push({id:c.getAttribute("id")||null,url:f.parseNodeText(c)})})}const s=f.childByName(t,"AdParameters");s&&(n.adParameters={value:f.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),f.childrenByName(t,"TrackingEvents").forEach(u=>{f.childrenByName(u,"Tracking").forEach(c=>{let l=c.getAttribute("event");const d=f.parseNodeText(c);if(l&&d){if(l==="progress"){if(r=c.getAttribute("offset"),!r)return;l=r.charAt(r.length-1)==="%"?"progress-".concat(r):"progress-".concat(f.parseDuration(r))}Array.isArray(n.trackingEvents[l])||(n.trackingEvents[l]=[]),n.trackingEvents[l].push(d)}})}),f.childrenByName(t,"MediaFiles").forEach(u=>{f.childrenByName(u,"MediaFile").forEach(m=>{n.mediaFiles.push(function(T){const y={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};y.id=T.getAttribute("id"),y.fileURL=f.parseNodeText(T),y.deliveryType=T.getAttribute("delivery"),y.codec=T.getAttribute("codec"),y.mimeType=T.getAttribute("type"),y.mediaType=T.getAttribute("mediaType")||"2D",y.apiFramework=T.getAttribute("apiFramework"),y.fileSize=parseInt(T.getAttribute("fileSize")||0),y.bitrate=parseInt(T.getAttribute("bitrate")||0),y.minBitrate=parseInt(T.getAttribute("minBitrate")||0),y.maxBitrate=parseInt(T.getAttribute("maxBitrate")||0),y.width=parseInt(T.getAttribute("width")||0),y.height=parseInt(T.getAttribute("height")||0);const E=T.getAttribute("scalable");E&&typeof E=="string"&&(y.scalable=f.parseBoolean(E));const O=T.getAttribute("maintainAspectRatio");return O&&typeof O=="string"&&(y.maintainAspectRatio=f.parseBoolean(O)),y}(m))});const c=f.childByName(u,"InteractiveCreativeFile");c&&(n.interactiveCreativeFile=function(m){const T=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:y.type||null,apiFramework:y.apiFramework||null,variableDuration:f.parseBoolean(y.variableDuration),fileURL:null}}(f.parseAttributes(m));return T.fileURL=f.parseNodeText(m),T}(c));const l=f.childByName(u,"ClosedCaptionFiles");l&&f.childrenByName(l,"ClosedCaptionFile").forEach(m=>{const T=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:y.type||null,language:y.language||null,fileURL:null}}(f.parseAttributes(m));T.fileURL=f.parseNodeText(m),n.closedCaptionFiles.push(T)});const d=f.childByName(u,"Mezzanine"),p=function(m,T){const y={};let E=!1;return T.forEach(O=>{m&&m.getAttribute(O)?y[O]=m.getAttribute(O):E=!0}),E?null:y}(d,["delivery","type","width","height"]);if(p){const m={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};m.id=d.getAttribute("id"),m.fileURL=f.parseNodeText(d),m.delivery=p.delivery,m.codec=d.getAttribute("codec"),m.type=p.type,m.width=parseInt(p.width,10),m.height=parseInt(p.height,10),m.fileSize=parseInt(d.getAttribute("fileSize"),10),m.mediaType=d.getAttribute("mediaType")||"2D",n.mezzanine=m}});const a=f.childByName(t,"Icons");return a&&f.childrenByName(a,"Icon").forEach(u=>{n.icons.push(function(c){const l={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[],altText:null,hoverText:null};l.program=c.getAttribute("program"),l.height=parseInt(c.getAttribute("height")||0),l.width=parseInt(c.getAttribute("width")||0),l.xPosition=function(p){return["left","right"].indexOf(p)!==-1?p:parseInt(p||0)}(c.getAttribute("xPosition")),l.yPosition=function(p){return["top","bottom"].indexOf(p)!==-1?p:parseInt(p||0)}(c.getAttribute("yPosition")),l.apiFramework=c.getAttribute("apiFramework"),l.pxratio=c.getAttribute("pxratio")||"1",l.offset=f.parseDuration(c.getAttribute("offset")),l.duration=f.parseDuration(c.getAttribute("duration")),l.altText=c.getAttribute("altText"),l.hoverText=c.getAttribute("hoverText"),f.childrenByName(c,"HTMLResource").forEach(p=>{l.type=p.getAttribute("creativeType")||"text/html",l.htmlResource=f.parseNodeText(p)}),f.childrenByName(c,"IFrameResource").forEach(p=>{l.type=p.getAttribute("creativeType")||0,l.iframeResource=f.parseNodeText(p)}),f.childrenByName(c,"StaticResource").forEach(p=>{l.type=p.getAttribute("creativeType")||0,l.staticResource=f.parseNodeText(p)});const d=f.childByName(c,"IconClicks");if(d){l.iconClickThroughURLTemplate=f.parseNodeText(f.childByName(d,"IconClickThrough")),f.childrenByName(d,"IconClickTracking").forEach(m=>{l.iconClickTrackingURLTemplates.push({id:m.getAttribute("id")||null,url:f.parseNodeText(m)})});const p=f.childByName(d,"IconClickFallbackImages");p&&f.childrenByName(p,"IconClickFallbackImage").forEach(m=>{l.iconClickFallbackImages.push({url:f.parseNodeText(m)||null,width:m.getAttribute("width")||null,height:m.getAttribute("height")||null})})}return l.iconViewTrackingURLTemplate=f.parseNodeText(f.childByName(c,"IconViewTracking")),l}(u))}),n}function Is(t,e){const r=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=wr(n);return{id:i,adId:o,sequence:s,apiFramework:a,type:"nonlinear",variations:[],trackingEvents:{}}}(e);return f.childrenByName(t,"TrackingEvents").forEach(n=>{let i,o;f.childrenByName(n,"Tracking").forEach(s=>{i=s.getAttribute("event"),o=f.parseNodeText(s),i&&o&&(Array.isArray(r.trackingEvents[i])||(r.trackingEvents[i]=[]),r.trackingEvents[i].push(o))})}),f.childrenByName(t,"NonLinear").forEach(n=>{const i={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};i.id=n.getAttribute("id")||null,i.width=n.getAttribute("width"),i.height=n.getAttribute("height"),i.expandedWidth=n.getAttribute("expandedWidth"),i.expandedHeight=n.getAttribute("expandedHeight"),i.scalable=f.parseBoolean(n.getAttribute("scalable")),i.maintainAspectRatio=f.parseBoolean(n.getAttribute("maintainAspectRatio")),i.minSuggestedDuration=f.parseDuration(n.getAttribute("minSuggestedDuration")),i.apiFramework=n.getAttribute("apiFramework"),f.childrenByName(n,"HTMLResource").forEach(s=>{i.type=s.getAttribute("creativeType")||"text/html",i.htmlResource=f.parseNodeText(s)}),f.childrenByName(n,"IFrameResource").forEach(s=>{i.type=s.getAttribute("creativeType")||0,i.iframeResource=f.parseNodeText(s)}),f.childrenByName(n,"StaticResource").forEach(s=>{i.type=s.getAttribute("creativeType")||0,i.staticResource=f.parseNodeText(s)});const o=f.childByName(n,"AdParameters");o&&(i.adParameters={value:f.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),i.nonlinearClickThroughURLTemplate=f.parseNodeText(f.childByName(n,"NonLinearClickThrough")),f.childrenByName(n,"NonLinearClickTracking").forEach(s=>{i.nonlinearClickTrackingURLTemplates.push({id:s.getAttribute("id")||null,url:f.parseNodeText(s)})}),r.variations.push(i)}),r}function sn(t){const e=[];return t.forEach(r=>{const n=ii(r);n&&e.push(n)}),e}function ii(t){if(t.nodeName==="#comment")return null;const e={name:null,value:null,attributes:{},children:[]},r=t.attributes,n=t.childNodes;if(e.name=t.nodeName,t.attributes){for(const o in r)if(r.hasOwnProperty(o)){const s=r[o];s.nodeName&&s.nodeValue&&(e.attributes[s.nodeName]=s.nodeValue)}}for(const o in n)if(n.hasOwnProperty(o)){const s=ii(n[o]);s&&e.children.push(s)}if(e.children.length===0||e.children.length===1&&["#cdata-section","#text"].indexOf(e.children[0].name)>=0){const o=f.parseNodeText(t);o!==""&&(e.value=o),e.children=[]}return(i=e).value===null&&Object.keys(i.attributes).length===0&&i.children.length===0?null:e;var i}function Os(t){return t.getAttribute("AdID")||t.getAttribute("adID")||t.getAttribute("adId")||null}const yt={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function an(t,e){if(!yt[t.nodeName]||!yt[t.nodeName].attributes)return;const r=yt[t.nodeName].attributes.filter(n=>!t.getAttribute(n));r.length>0&&it({name:t.nodeName,parentName:t.parentNode.nodeName,attributes:r},e)}function un(t,e,r){const n=yt[t.nodeName],i=!r&&t.nodeName!=="Wrapper";if(!(!n||i)){if(n.subElements){const o=n.subElements.filter(s=>!f.childByName(t,s));o.length>0&&it({name:t.nodeName,parentName:t.parentNode.nodeName,subElements:o},e)}!r||!n.oneOfinLineResources||n.oneOfinLineResources.some(o=>f.childByName(t,o))||it({name:t.nodeName,parentName:t.parentNode.nodeName,oneOfResources:n.oneOfinLineResources},e)}}function cn(t){return t.children&&t.children.length!==0}function it(t,e){let{name:r,parentName:n,attributes:i,subElements:o,oneOfResources:s}=t,a="Element '".concat(r,"'");a+=i?" missing required attribute(s) '".concat(i.join(", "),"' "):o?" missing required sub element(s) '".concat(o.join(", "),"' "):s?" must provide one of the following '".concat(s.join(", "),"' "):" is empty",e("VAST-warning",{message:a,parentElement:n,specVersion:4.1})}const ks={verifyRequiredValues:function t(e,r,n){if(e&&e.nodeName)if(e.nodeName==="InLine"&&(n=!0),an(e,r),cn(e)){un(e,r,n);for(let i=0;i<e.children.length;i++)t(e.children[i],r,n)}else f.parseNodeText(e).length===0&&it({name:e.nodeName,parentName:e.parentNode.nodeName},r)},hasSubElements:cn,emitMissingValueWarning:it,verifyRequiredAttributes:an,verifyRequiredSubElements:un};function Ns(t,e){let{allowMultipleAds:r,followAdditionalWrappers:n}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=Array.from(t.childNodes).filter(o=>{const s=o.nodeName.toLowerCase();return s==="inline"||n!==!1&&s==="wrapper"});for(const o of i){if(f.copyNodeAttribute("id",t,o),f.copyNodeAttribute("sequence",t,o),f.copyNodeAttribute("adType",t,o),o.nodeName==="Wrapper")return{ad:Ls(o,e),type:"WRAPPER"};if(o.nodeName==="InLine")return{ad:Cs(o,e,{allowMultipleAds:r}),type:"INLINE"};const s=o.nodeName.toLowerCase();e("VAST-warning",{message:"<".concat(o.nodeName,s==="inline"?"> must be written <InLine>":"> must be written <Wrapper>"),wrongNode:o})}}function Cs(t,e){let{allowMultipleAds:r}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r===!1&&t.getAttribute("sequence")?null:oi(t,e)}function oi(t,e){let r=[];e&&ks.verifyRequiredValues(t,e);const n=Array.from(t.childNodes),i=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:o.id||null,sequence:o.sequence||null,adType:o.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(f.parseAttributes(t));return n.forEach(o=>{switch(o.nodeName){case"Error":i.errorURLTemplates.push(f.parseNodeText(o));break;case"Impression":i.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:f.parseNodeText(o)});break;case"Creatives":i.creatives=function(s){const a=[];return s.forEach(u=>{const c={id:u.getAttribute("id")||null,adId:Os(u),sequence:u.getAttribute("sequence")||null,apiFramework:u.getAttribute("apiFramework")||null},l=[];let d;f.childrenByName(u,"UniversalAdId").forEach(m=>{const T={idRegistry:m.getAttribute("idRegistry")||"unknown",value:f.parseNodeText(m)};l.push(T)});const p=f.childByName(u,"CreativeExtensions");p&&(d=sn(f.childrenByName(p,"CreativeExtension")));for(const m in u.childNodes){const T=u.childNodes[m];let y;switch(T.nodeName){case"Linear":y=Es(T,c);break;case"NonLinearAds":y=Is(T,c);break;case"CompanionAds":y=ws(T,c)}y&&(l&&(y.universalAdIds=l),d&&(y.creativeExtensions=d),a.push(y))}}),a}(f.childrenByName(o,"Creative"));break;case"Extensions":{const s=f.childrenByName(o,"Extension");i.extensions=sn(s),i.adVerifications.length||(r=function(a){let u=null,c=[];return a.some(l=>u=f.childByName(l,"AdVerifications")),u&&(c=ln(f.childrenByName(u,"Verification"))),c}(s));break}case"AdVerifications":i.adVerifications=ln(f.childrenByName(o,"Verification"));break;case"AdSystem":i.system={value:f.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":i.title=f.parseNodeText(o);break;case"AdServingId":i.adServingId=f.parseNodeText(o);break;case"Category":i.categories.push({authority:o.getAttribute("authority")||null,value:f.parseNodeText(o)});break;case"Expires":i.expires=parseInt(f.parseNodeText(o),10);break;case"ViewableImpression":i.viewableImpression.push(function(s){const a=(u,c)=>{const l=f.parseNodeText(c);return l&&u.push(l),u};return{id:s.getAttribute("id")||null,viewable:f.childrenByName(s,"Viewable").reduce(a,[]),notViewable:f.childrenByName(s,"NotViewable").reduce(a,[]),viewUndetermined:f.childrenByName(s,"ViewUndetermined").reduce(a,[])}}(o));break;case"Description":i.description=f.parseNodeText(o);break;case"Advertiser":i.advertiser={id:o.getAttribute("id")||null,value:f.parseNodeText(o)};break;case"Pricing":i.pricing={value:f.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":i.survey={value:f.parseNodeText(o),type:o.getAttribute("type")||null};break;case"BlockedAdCategories":i.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:f.parseNodeText(o)})}}),r.length&&(i.adVerifications=i.adVerifications.concat(r)),i}function Ls(t,e){const r=oi(t,e),n=t.getAttribute("followAdditionalWrappers"),i=t.getAttribute("allowMultipleAds"),o=t.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!n||f.parseBoolean(n),r.allowMultipleAds=!!i&&f.parseBoolean(i),r.fallbackOnNoAd=o?f.parseBoolean(o):null;let s=f.childByName(t,"VASTAdTagURI");if(s?r.nextWrapperURL=f.parseNodeText(s):(s=f.childByName(t,"VASTAdTagURL"),s&&(r.nextWrapperURL=f.parseNodeText(f.childByName(s,"URL")))),r.creatives.forEach(a=>{if(["linear","nonlinear"].includes(a.type)){if(a.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[a.type]||(r.trackingEvents[a.type]={});for(const u in a.trackingEvents){const c=a.trackingEvents[u];Array.isArray(r.trackingEvents[a.type][u])||(r.trackingEvents[a.type][u]=[]),c.forEach(l=>{r.trackingEvents[a.type][u].push(l)})}}a.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),a.videoClickTrackingURLTemplates.forEach(u=>{r.videoClickTrackingURLTemplates.push(u)})),a.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=a.videoClickThroughURLTemplate),a.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),a.videoCustomClickURLTemplates.forEach(u=>{r.videoCustomClickURLTemplates.push(u)}))}}),r.nextWrapperURL)return r}function ln(t){const e=[];return t.forEach(r=>{const n={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(r.childNodes);f.assignAttributes(r.attributes,n),i.forEach(s=>{let{nodeName:a,textContent:u,attributes:c}=s;switch(a){case"JavaScriptResource":case"ExecutableResource":n.resource=u.trim(),f.assignAttributes(c,n);break;case"VerificationParameters":n.parameters=u.trim()}});const o=f.childByName(r,"TrackingEvents");o&&f.childrenByName(o,"Tracking").forEach(s=>{const a=s.getAttribute("event"),u=f.parseNodeText(s);a&&u&&(Array.isArray(n.trackingEvents[a])||(n.trackingEvents[a]=[]),n.trackingEvents[a].push(u))}),e.push(n)}),e}class Ps{constructor(){this._handlers=[]}on(e,r){if(typeof r!="function")throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof r));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:r}),this}once(e,r){return this.on(e,function(n,i,o){const s={fired:!1,wrapFn:void 0};function a(){s.fired||(n.off(i,s.wrapFn),s.fired=!0,o.bind(n)(...arguments))}return s.wrapFn=a,a}(this,e,r))}off(e,r){return this._handlers=this._handlers.filter(n=>n.event!==e||n.handler!==r),this}emit(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];let o=!1;return this._handlers.forEach(s=>{s.event==="*"&&(o=!0,s.handler(e,...n)),s.event===e&&(o=!0,s.handler(...n))}),o}removeAllListeners(e){return e?(this._handlers=this._handlers.filter(r=>r.event!==e),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter(r=>r.event===e).length}listeners(e){return this._handlers.reduce((r,n)=>(n.event===e&&r.push(n.handler),r),[])}eventNames(){return this._handlers.map(e=>e.event)}}let dn=0,cr=0;const si=(t,e)=>{!t||!e||t<=0||e<=0||(cr=(cr*dn+8*t/e)/++dn)},Rs={ERRORCODE:900,extensions:[]},pn="VAST response version not supported";class _s extends Ps{constructor(){let{fetcher:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.maxWrapperDepth=null,this.rootErrorURLTemplates=[],this.errorURLTemplates=[],this.remainingAds=[],this.parsingOptions={},this.fetcher=e||null,this.keepFailedAdPod=!1}trackVastError(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;o<n;o++)i[o-2]=arguments[o];this.emit("VAST-error",Object.assign({},Rs,r,...i)),Pe.track(e,r)}getErrorURLTemplates(){return this.rootErrorURLTemplates.concat(this.errorURLTemplates)}getEstimatedBitrate(){return cr}initParsingStatus(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.keepFailedAdPod=e.keepFailedAdPod||!1,this.rootURL="",this.resetParsingStatus(),si(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(this.remainingAds.length===0)return Promise.reject(new Error("No more ads are available for the given VAST"));const r=e?this.remainingAds:[this.remainingAds.shift()];return this.errorURLTemplates=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then(n=>this.buildVASTResponse(n))}parseVAST(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then(n=>this.buildVASTResponse(n))}buildVASTResponse(e){const r=function(n){let{ads:i,errorURLTemplates:o,version:s}=n;return{ads:i||[],errorURLTemplates:o||[],version:s||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(r),r}parseVastXml(e,r){let{isRootVAST:n=!1,url:i=null,wrapperDepth:o=0,allowMultipleAds:s,followAdditionalWrappers:a}=r;if(!e||!e.documentElement||e.documentElement.nodeName!=="VAST"){var u;this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:o});const p=(e==null||(u=e.documentElement)===null||u===void 0?void 0:u.nodeName)==="VideoAdServingTemplate";throw new Error(p?pn:"Invalid VAST XMLDocument")}const c=[],l=e.documentElement.childNodes,d=e.documentElement.getAttribute("version");n&&d&&(this.vastVersion=d);for(const p in l){const m=l[p];if(m.nodeName==="Error"){const T=f.parseNodeText(m);n?this.rootErrorURLTemplates.push(T):this.errorURLTemplates.push(T)}else if(m.nodeName==="Ad"){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(s===!1&&c.length>1)break;const T=Ns(m,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:a});T.ad?(c.push(T.ad),this.emit("VAST-ad-parsed",{type:T.type,url:i,wrapperDepth:o,adIndex:c.length-1,vastVersion:d})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}parse(e){let{url:r=null,resolveAll:n=!0,wrapperSequence:i=null,previousUrl:o=null,wrapperDepth:s=0,isRootVAST:a=!1,followAdditionalWrappers:u,allowMultipleAds:c}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&a&&(c=!0);try{l=this.parseVastXml(e,{isRootVAST:a,url:r,wrapperDepth:s,allowMultipleAds:c,followAdditionalWrappers:u})}catch(d){return Promise.reject(d)}if(l.length===1&&i!=null&&(l[0].sequence=i),n===!1){const d=f.getSortedAdPods(l),p=f.getStandAloneAds(l);d.length?l=d:p.length&&(l=[p.shift()]),this.remainingAds=p}return this.resolveAds(l,{wrapperDepth:s,previousUrl:o,url:r})}resolveAds(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],{wrapperDepth:r,previousUrl:n,url:i}=arguments.length>1?arguments[1]:void 0;const o=[];return n=i,e.forEach(s=>{const a=this.resolveWrappers(s,r,n);o.push(a)}),Promise.all(o).then(s=>Pe.flatten(s))}resolveWrappers(e,r,n){const i={...e};return new Promise(o=>{var s;if(r++,!i.nextWrapperURL)return delete i.nextWrapperURL,o(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,o(i);if(r>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,o(i);i.nextWrapperURL=f.resolveVastAdTagURI(i.nextWrapperURL,n);const a=(s=this.parsingOptions.allowMultipleAds)!==null&&s!==void 0?s:i.allowMultipleAds,u=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then(c=>this.parse(c,{url:i.nextWrapperURL,previousUrl:n,wrapperSequence:u,wrapperDepth:r,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:a}).then(l=>{if(delete i.nextWrapperURL,l.length===0)return i.creatives=[],o(i);l.forEach(d=>{d&&f.mergeWrapperAdData(d,i)}),o(l)})).catch(c=>{i.errorCode=c.message===pn?102:301,i.errorMessage=c.message,o(i)})})}completeWrapperResolving(e){if(e.ads.length===0)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let r=e.ads.length-1;r>=0;r--){const n=e.ads[r],i=!n.creatives.some(o=>{var s,a;return((s=o.mediaFiles)===null||s===void 0?void 0:s.length)>0||((a=o.variations)===null||a===void 0?void 0:a.length)>0});!n.errorCode&&!i||n.VASTAdTagURI||(this.trackVastError(n.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:n.errorCode||303},{ERRORMESSAGE:n.errorMessage||""},{extensions:n.extensions},{system:n.system}),this.keepFailedAdPod&&n.sequence?n.hasFailed=!0:e.ads.splice(r,1))}}}let fe=null;const Ds={data:{},length:0,getItem(t){return this.data[t]},setItem(t,e){this.data[t]=e,this.length=Object.keys(this.data).length},removeItem(t){delete this.data[t],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class Fs{constructor(){this.storage=this.initStorage()}initStorage(){if(fe)return fe;try{fe=typeof window<"u"&&window!==null?window.localStorage||window.sessionStorage:null}catch{fe=null}return fe&&!this.isStorageDisabled(fe)||(fe=Ds,fe.clear()),fe}isStorageDisabled(e){const r="__VASTStorage__";try{if(e.setItem(r,r),e.getItem(r)!==r)return e.removeItem(r),!0}catch{return!0}return e.removeItem(r),!1}getItem(e){return this.storage.getItem(e)}setItem(e,r){return this.storage.setItem(e,r)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const lr=12e4,Us={get:async function(t,e){try{const r=new AbortController,n=setTimeout(()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(e.timeout||lr," ms (408)"))},e.timeout||lr),i=await fetch(t,{...e,signal:r.signal,credentials:e.withCredentials?"include":"omit"}).finally(()=>{clearTimeout(n)}),o=function(s){return Pe.isBrowserEnvironment()&&window.location.protocol==="https:"&&s.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":s.status===200&&s.ok?null:"URLHandler: ".concat(s.statusText," (").concat(s.status,")")}(i);return o?{error:new Error(o),statusCode:i.status}:async function(s){const a=await s.text();let u;return u=Pe.isBrowserEnvironment()?new DOMParser:new(await Promise.resolve().then(()=>require("../index-a0VyCTSb.cjs")).then(c=>c.index)).DOMParser,{xml:u.parseFromString(a,"text/xml"),details:{byteLength:a.length,statusCode:s.status,rawXml:a}}}(i)}catch(r){return{error:r,statusCode:r.name==="AbortError"?408:null}}}};class Vs{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||Us,this.fetchingOptions={...e.fetchOptions,timeout:e.timeout||lr,withCredentials:!!e.withCredentials}}addURLTemplateFilter(e){typeof e=="function"&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var r;let{url:n,maxWrapperDepth:i,emitter:o,wrapperDepth:s=0,previousUrl:a=null,wrapperAd:u=null}=e;const c=Date.now();this.URLTemplateFilters.forEach(p=>{n=p(n)}),o("VAST-resolving",{url:n,previousUrl:a,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:u});const l=await this.urlHandler.get(n,this.fetchingOptions),d=Math.round(Date.now()-c);if(o("VAST-resolved",{url:n,previousUrl:a,wrapperDepth:s,error:l?.error||null,duration:d,statusCode:l?.statusCode||null,...l?.details}),si(l==null||(r=l.details)===null||r===void 0?void 0:r.byteLength,d),l.error)throw new Error(l.error);return l.xml}}class xs{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Fs;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=r,this.fetcher=new Vs,this.vastParser=new _s({fetcher:this.fetcher}),this.storage=n,this.lastSuccessfulAd===void 0&&(this.lastSuccessfulAd=0),this.totalCalls===void 0&&(this.totalCalls=0),this.totalCallsTimeout===void 0&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.fetcher.setOptions(r),this.vastParser.parseVAST(e,r)}get(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=Date.now();return r.hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout<n?(this.totalCalls=1,this.totalCallsTimeout=n+36e5):this.totalCalls++,new Promise((i,o)=>{if(this.cappingFreeLunch>=this.totalCalls)return o(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=n-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s<this.cappingMinimumTimeInterval)return o(new Error("VAST call canceled – (".concat(this.cappingMinimumTimeInterval,")ms minimum interval reached")));this.vastParser.initParsingStatus(r),this.fetcher.setOptions(r),this.vastParser.rootURL=e,this.fetcher.fetchVAST({url:e,emitter:this.vastParser.emit.bind(this.vastParser),maxWrapperDepth:this.vastParser.maxWrapperDepth}).then(a=>(r.previousUrl=e,r.isRootVAST=!0,r.url=e,this.vastParser.parse(a,r).then(u=>{const c=this.vastParser.buildVASTResponse(u);i(c)}))).catch(a=>o(a))})}}const Bs=new xs,$t=Z("ui:gam-static"),fn=t=>new Promise((e,r)=>{const n=new Image;n.onload=()=>e(t),n.onerror=()=>r(),n.src=t}),Ms=t=>(e,r,n)=>t.transport.nanoquery.createFetcherStore([e,r],{dedupeTime:n.prefetch?n.refetchInterval:1/0,revalidateInterval:n.refetchInterval>0?n.refetchInterval:0,fetcher:async i=>{if(!i||typeof i!="string")throw new Error("no_valid_ad");V.emit("exposedPauseAd",{action:"load",payload:{}});try{const s=(await Bs.get(i)).ads.find(a=>a.creatives.length>0);if(s){const a=s.id||"";$t.debug(s,"validAd");const u=s.creatives.find(p=>p.type==="nonlinear");if(u){const p=u.adId||u.id||a;$t.debug(u,"nonlinear");const m=u.variations?.[0]?.staticResource,T=u.variations?.[0]?.nonlinearClickThroughURLTemplate;if(m)return await fn(m),V.emit("exposedPauseAd",{action:"loaded",payload:{id:p,parentId:a}}),{id:p,parentId:a,url:i,imageSrc:m,adUrl:T}}const c=s.creatives.find(p=>p.type==="companion");$t.debug(c,"companion");const l=c?.variations?.[0]?.staticResources?.[0]?.url,d=c?.variations?.[0]?.companionClickThroughURLTemplate;if(l){const p=c.adId||c.id||a;return await fn(l),V.emit("exposedPauseAd",{action:"loaded",payload:{id:p,parentId:a}}),{id:p,parentId:a,url:i,imageSrc:l,adUrl:d}}}throw new Error("no_valid_ad")}catch(o){throw console.error(o,"err"),new Error("no_valid_ad")}}});class qs extends Qn{getExternalPauseAd;externalPauseAdStores=new Map;externalPauseAdEnabled=new Map;log;constructor(e){super(),this.log=Z("advertisement");const r=Ms(e);this.getExternalPauseAd=(n,i)=>{if(this.externalPauseAdStores.has(n)){const a=this.externalPauseAdEnabled.get(n),u=this.externalPauseAdStores.get(n),c=a.get()===!1&&i.$enabled===!0;return a.set(i.$enabled),c&&window.requestAnimationFrame(()=>{u.revalidate()}),[u,n]}const o=G(i.$enabled),s=r(n,o,i);return this.externalPauseAdEnabled.set(n,o),this.externalPauseAdStores.set(n,s),[s,n]}}connect=()=>{this.log.debug("connect")};disconnect=()=>{this.log.debug("disconnect"),this.externalPauseAdStores.forEach(e=>{e.off()}),this.externalPauseAdEnabled.forEach(e=>{e.off()}),this.externalPauseAdEnabled.clear(),this.externalPauseAdStores.clear()}}const $s=(t,e,r)=>{t.sdk.advertisement=new qs(t),t.sdk.onMount({name:"advertisement"},()=>(t.sdk.advertisement.connect(),()=>{t.sdk.advertisement.disconnect()})),r()};class js{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 V.listen(r)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.INVITATION_ACCEPTED},category:dt.InvitationCategory.GAMES,from:dt.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.INVITATION_SENT},category:dt.InvitationCategory.GAMES,from:e||dt.InvitationFrom.UNSET})}}class Qs{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 V.listen(r)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.INTERACTIONS},actionType:$r.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.INTERACTIONS},actionType:$r.InteractionActionType.SCROLL})}}const Gs={[v.PromotionType.UNSET]:g.TopicSubType.UNSET,[v.PromotionType.INGAME_IAB21]:g.TopicSubType.PROMOTION_INGAME_IAB21,[v.PromotionType.INGAME_IAB21_SIDEBAR]:g.TopicSubType.PROMOTION_INGAME_IAB21,[v.PromotionType.INGAME_IAB11_LBAR]:g.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[v.PromotionType.INGAME_IAB11]:g.TopicSubType.PROMOTION_INGAME_IAB11,[v.PromotionType.INGAME_IAB11_SIDEBAR]:g.TopicSubType.PROMOTION_INGAME_IAB11,[v.PromotionType.INGAME_IAB21_LBAR]:g.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[v.PromotionType.INGAME_IAB61]:g.TopicSubType.PROMOTION_INGAME_IAB61,[v.PromotionType.INGAME_IAB61_SIDEBAR]:g.TopicSubType.PROMOTION_INGAME_IAB61,[v.PromotionType.EXTERNAL_AD]:g.TopicSubType.PROMOTION_GAM,[v.PromotionType.VIDEO_SIDE_BY_SIDE]:g.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[v.PromotionType.PICTURE_IN_PICTURE]:g.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[v.PromotionType.LOWER_THIRD]:g.TopicSubType.PROMOTION_LOWER_THIRD,[v.PromotionType.SHOP_LBAR]:g.TopicSubType.PROMOTION_SHOP_LBAR,[v.PromotionType.SHOP_OVERLAY]:g.TopicSubType.PROMOTION_SHOP_OVERLAY,[v.PromotionType.SHOP_SIDEBAR]:g.TopicSubType.PROMOTION_SHOP_SIDEBAR,[v.PromotionType.NFL_SHOP_LBAR]:g.TopicSubType.PROMOTION_SHOP_LBAR,[v.PromotionType.NFL_SHOP_OVERLAY]:g.TopicSubType.PROMOTION_SHOP_OVERLAY,[v.PromotionType.NFL_SHOP_SIDEBAR]:g.TopicSubType.PROMOTION_SHOP_SIDEBAR,[v.PromotionType.STATS]:g.TopicSubType.UNSET,[v.PromotionType.STANDARD]:g.TopicSubType.UNSET,[v.PromotionType.SHOP]:g.TopicSubType.UNSET,[v.PromotionType.NFL_SHOP]:g.TopicSubType.UNSET},dr=t=>t?Gs[t]:g.TopicSubType.UNSET,Ks={25:g.Kind.AD_VIDEO_Q25,50:g.Kind.AD_VIDEO_Q50,75:g.Kind.AD_VIDEO_Q75};class Ws{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(!n.slEventBus?.skipAnalytics){if(n.slEventBus?.type==="exposedPauseAd"){const i=n.slEventBus.payload;switch(n.slEventBus.action){case"enabled":this.exposedPauseAdEnabled(i);break;case"disabled":this.exposedPauseAdDisabled(i);break;case"closed":this.exposedPauseAdClosed(i);break;case"load":this.exposedPauseAdLoad(i,!1);break;case"loaded":this.exposedPauseAdLoad(i,!0);break;case"rendered":this.exposedPauseAdOpened(i);break}}if(n.slEventBus?.type==="advertisement"){const i=n.slEventBus.payload,o=dr(i.type);switch(n.slEventBus.action){case"videoPlay":this.videoPlay(i,{topicSubType:o});break;case"videoEnd":this.videoEnd(i,{topicSubType:o});break;case"videoRendered":this.videoRendered(i,{topicSubType:o});break;case"buttonSelect":this.buttonSelect(i,{topicSubType:o});break;case"bannerSelect":this.bannerSelect(i,{topicSubType:o});break;case"bannerShown":this.bannerShown(i,{topicSubType:o});break;case"received":this.received(i,{topicSubType:o});break;case"opened":this.opened(i,{topicSubType:o});break;case"viewed":this.viewed(i,{topicSubType:o});break;case"videoMuted":case"videoUnmuted":this.videoMuted(i,{topicSubType:o,muted:n.slEventBus.action==="videoMuted"});break;case"videoReplayed":this.videoReplayed(i,{topicSubType:o});break;case"quartileCompleted":this.quartileCompleted(i,{topicSubType:o});break}}}};return V.listen(r)})}exposedPauseAdEnabled=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:g.Kind.STREAM_PAUSED,topicId:e,parentTopicId:r,topicType:g.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:g.PollOpenedFrom.UNSET})};exposedPauseAdClosed=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:g.Kind.EXTERNAL_AD_CLOSED,topicId:e,parentTopicId:r,topicType:g.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:g.PollOpenedFrom.UNSET})};exposedPauseAdDisabled=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:g.Kind.STREAM_RESUMED,topicId:e,parentTopicId:r,topicType:g.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:g.PollOpenedFrom.UNSET})};exposedPauseAdOpened=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:g.Kind.EXTERNAL_AD_RENDERED,topicId:e,parentTopicId:r,topicType:g.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:g.PollOpenedFrom.UNSET})};exposedPauseAdLoad=({id:e,parentId:r},n)=>{const i=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...i,kind:n?g.Kind.EXTERNAL_AD_LOADED:g.Kind.EXTERNAL_AD_REQUESTED,topicId:e,parentTopicId:r,topicType:g.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:g.PollOpenedFrom.UNSET})};received=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.POLLS_RECEIVED,topicId:e,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:r},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.POLLS_OPENED,topicId:e,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:r==="notification"?g.PollOpenedFrom.IN_APP:g.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:r})=>{};videoMuted=({id:e},{topicSubType:r,muted:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:n?g.Kind.AD_VIDEO_MUTED:g.Kind.AD_VIDEO_UNMUTED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};quartileCompleted=({id:e,quartile:r},{topicSubType:n})=>{r&&this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:Ks[r],topicType:g.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:g.PollOpenedFrom.UNSET})};videoReplayed=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_VIDEO_REPLAYED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_VIDEO_PLAYED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};videoEnd=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_VIDEO_COMPLETE,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};videoRendered=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_VIDEO_RENDERED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_INTERACTION_BUTTON_NAVIGATED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_INTERACTION_BANNER_NAVIGATED,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})};bannerShown=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:g.Kind.AD_BANNER_SHOWN,topicType:g.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:g.PollOpenedFrom.UNSET})}}const rt={[v.QuestionType.UNSET]:g.TopicType.UNSET,[v.QuestionType.FACTOID]:g.TopicType.POLLS_INSIGHT,[v.QuestionType.POLL]:g.TopicType.POLLS_POLL,[v.QuestionType.PREDICTION]:g.TopicType.POLLS_PREDICTION,[v.QuestionType.PROMOTION]:g.TopicType.POLLS_PROMOTION,[v.QuestionType.TRIVIA]:g.TopicType.POLLS_TRIVIA,[v.QuestionType.TWEET]:g.TopicType.POLLS_TWITTER};v.QuestionType.UNSET+"",ne.NotificationKind.UNSET,v.QuestionType.FACTOID+"",ne.NotificationKind.POLLS,v.QuestionType.POLL+"",ne.NotificationKind.POLLS,v.QuestionType.PREDICTION+"",ne.NotificationKind.POLLS,v.QuestionType.PROMOTION+"",ne.NotificationKind.POLLS,v.QuestionType.TRIVIA+"",ne.NotificationKind.POLLS,v.QuestionType.TWEET+"",ne.NotificationKind.POLLS;const Hs={[M.SdkOverlayType.UNSET]:g.Category.UNSET,[M.SdkOverlayType.INPLAY]:g.Category.INPLAY,[M.SdkOverlayType.MESSAGING]:g.Category.MESSAGING,[M.SdkOverlayType.STATISTICS]:g.Category.STATS,[M.SdkOverlayType.BETTING]:g.Category.BETTING,[M.SdkOverlayType.TWITTER]:g.Category.TWITTER,[M.SdkOverlayType.MERCHANDISE]:g.Category.MERCHANDISE,[M.SdkOverlayType.CONTESTS]:g.Category.CONTESTS,[M.SdkOverlayType.VOICE_CHAT]:g.Category.CALLING,[M.SdkOverlayType.TICKETS]:g.Category.TICKETS,[M.SdkOverlayType.WHOIS_WATCHING]:g.Category.WHOISWATCHING,[M.SdkOverlayType.PROFILE]:g.Category.PROFILE,[M.SdkOverlayType.GAMES]:g.Category.POLLS,[M.SdkOverlayType.GOLF_STATISTICS]:g.Category.STATS,[M.SdkOverlayType.HIGHLIGHTS]:g.Category.HIGHLIGHTS,[M.SdkOverlayType.PUBLIC_CHAT]:g.Category.PUBLIC_CHAT};class zs{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="notification")switch(n.slEventBus.action){case"rendered":this.received(n.slEventBus.payload);break;case"opened":this.opened(n.slEventBus.payload);break}if(n.slEventBus?.type==="advertisement")switch(n.slEventBus.action){case"notification-received":this.received({questionId:n.slEventBus.payload.id,questionType:v.QuestionType.PROMOTION,topicSubType:dr(n.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:n.slEventBus.payload.id,questionType:v.QuestionType.PROMOTION,topicSubType:dr(n.slEventBus.payload.type)});break}};return V.listen(r)})}received=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:r?rt[r]:g.TopicType.UNSET,topicSubType:n},notificationKind:ne.NotificationKind.POLLS,notificationType:ne.NotificationType.IN_APP})};opened=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.NOTIFICATION_OPENED,topicId:e,topicType:r?rt[r]:g.TopicType.UNSET,topicSubType:n},notificationKind:ne.NotificationKind.POLLS,notificationType:ne.NotificationType.IN_APP})}}class Ys{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"viewed":this.viewed(n.slEventBus.payload);break}};return V.listen(r)})}received=({questionId:e,questionType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.POLLS_RECEIVED,topicId:e,topicType:r?rt[r]:g.TopicType.UNSET},pollOpenedFrom:g.PollOpenedFrom.UNSET})};viewed=({questionId:e,questionType:r,questionOpenedFrom:n,isAd:i})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:i?g.Kind.POLLS_AD_OPENED:g.Kind.POLLS_OPENED,topicId:e,topicType:r?rt[r]:g.TopicType.UNSET},pollOpenedFrom:n==="list"?g.PollOpenedFrom.PICK_HISTORY:g.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:r,isAd:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:n?g.Kind.POLLS_AD_VOTE:g.Kind.POLLS_VOTE,topicId:e,topicType:r?rt[r]:g.TopicType.UNSET},pollOpenedFrom:g.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.GAMES_JOINED},pollOpenedFrom:g.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:g.Kind.POLLS_NAVIGATED},pollOpenedFrom:g.PollOpenedFrom.UNSET})}}const Js=({transport:t,$commonStore:e})=>{let r;const n=G(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(Bn.AnalyticsService,{method:"send",params:[n]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:g.Kind.SESSION_HEARTBEAT}}}})}catch(m){ye.error(m,"send heartbeat failed")}return Date.now()},revalidateInterval:i}),u=()=>{ye.debug("mounted heartbeat"),r=a.subscribe(()=>{})},c=()=>{ye.debug("enabled heartbeat"),n.set(!0),a.lc===0&&u()},l=()=>{ye.debug("disabled heartbeat"),n.set(!1)};return{enable:c,disable:l,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),r?.(),r=void 0,l()}}},ye=Z("analytics");class Xs{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 Ne(J({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=Js({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new zs(this),this.polls=new Ys(this),this.invitation=new js(this),this.interactions=new Qs(this),this.advertisement=new Ws(this);const{client:r}=e.analyticsTransport.createPromiseClient(Bn.AnalyticsService,{method:"send"});this.analyticsClient=r}connect=()=>{this.writeCommon("sessionId",$e.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,r)=>{r&&this.analyticsClient.unary({message:{case:e,value:r}}).then(()=>{ye.trace("send analytics success",e,r)}).catch(n=>{ye.error(n,"send analytics failed")})};writeCommon=(e,r)=>{this.commonStore.setValue(e,r)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(r=>{this.writeCommon("eventId",r)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(r=>{r&&this.writeCommon("category",Hs[r]),r!==M.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",$e.v4()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const r=n=>{if(!n.slEventBus)return;const i=n.slEventBus?.action;n.slEventBus?.type==="exposedPauseAd"&&((i==="disabled"||i==="closed")&&setTimeout(()=>{this.writeCommon("overlaySessionId",""),this.writeCommon("topicId",""),this.writeCommon("parentTopicId",""),this.writeCommon("topicType",g.TopicType.UNSET),this.writeCommon("category",g.Category.UNSET)},200),i==="enabled"&&(this.writeCommon("overlaySessionId",$e.v4()),this.writeCommon("category",g.Category.EXPOSED_PAUSED_AD))),n.slEventBus?.type==="advertisement"&&(i==="opened"&&this.writeCommon("overlaySessionId",$e.v4()),i==="closed"&&this.writeCommon("overlaySessionId",""))};return V.listen(r)}),this.onConnect(()=>{const r=window.matchMedia("(orientation: portrait)"),n=i=>{this.writeCommon("screenOrientation",i.matches?g.ScreenOrientation.PORTRAIT:g.ScreenOrientation.LANDSCAPE)};return r.addEventListener("change",n),()=>{r.removeEventListener("change",n)}}),this.onConnect(()=>e.deepLink.$store.subscribe(r=>{r?.handled&&this.invitation.accepted()}))}}const Zs=(t,e,r)=>{t.analytics=new Xs(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),t.sdk.writeOverlaySessionId=n=>{n===""?t.analytics.writeCommon("overlaySessionId",""):t.analytics.writeCommon("overlaySessionId",$e.v4())},()=>{t.analytics.disconnect()})),r()};var Er=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ea(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ir={exports:{}},Or={exports:{}};function ta(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 ra=ta,na=ra;function ai(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=na(ia),i=null,o=null,s=0,a=null,u={push:y,drain:ee,saturated:ee,pause:l,paused:!1,get concurrency(){return r},set concurrency(k){if(!(k>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=k,!u.paused)for(;i&&s<r;)s++,O()},running:c,resume:m,idle:T,length:d,getQueue:p,unshift:E,empty:ee,kill:w,killAndDrain:I,error:L};return u;function c(){return s}function l(){u.paused=!0}function d(){for(var k=i,q=0;k;)k=k.next,q++;return q}function p(){for(var k=i,q=[];k;)q.push(k.value),k=k.next;return q}function m(){if(u.paused){if(u.paused=!1,i===null){s++,O();return}for(;i&&s<r;)s++,O()}}function T(){return s===0&&u.length()===0}function y(k,q){var _=n.get();_.context=t,_.release=O,_.value=k,_.callback=q||ee,_.errorHandler=a,s>=r||u.paused?o?(o.next=_,o=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function E(k,q){var _=n.get();_.context=t,_.release=O,_.value=k,_.callback=q||ee,_.errorHandler=a,s>=r||u.paused?i?(_.next=i,i=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function O(k){k&&n.release(k);var q=i;q&&s<=r?u.paused?s--:(o===i&&(o=null),i=q.next,q.next=null,e.call(t,q.value,q.worked),o===null&&u.empty()):--s===0&&u.drain()}function w(){i=null,o=null,u.drain=ee}function I(){i=null,o=null,u.drain(),u.drain=ee}function L(k){a=k}}function ee(){}function ia(){this.value=null,this.callback=ee,this.next=null,this.release=ee,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=ee,t.errorHandler&&o(r,s),i.call(t.context,r,n),t.release(t)}}function oa(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(l,d){e.call(this,l).then(function(p){d(null,p)},d)}var i=ai(t,n,r),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=c,i;function a(l){var d=new Promise(function(p,m){o(l,function(T,y){if(T){m(T);return}p(y)})});return d.catch(ee),d}function u(l){var d=new Promise(function(p,m){s(l,function(T,y){if(T){m(T);return}p(y)})});return d.catch(ee),d}function c(){if(i.idle())return new Promise(function(p){p()});var l=i.drain,d=new Promise(function(p){i.drain=function(){l(),p()}});return d}}Or.exports=ai;Or.exports.promise=oa;var ui=Or.exports,kr={exports:{}},We=typeof Reflect=="object"?Reflect:null,hn=We&&typeof We.apply=="function"?We.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},bt;We&&typeof We.ownKeys=="function"?bt=We.ownKeys:Object.getOwnPropertySymbols?bt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:bt=function(e){return Object.getOwnPropertyNames(e)};function sa(t){console&&console.warn&&console.warn(t)}var ci=Number.isNaN||function(e){return e!==e};function x(){x.init.call(this)}kr.exports=x;kr.exports.once=la;x.EventEmitter=x;x.prototype._events=void 0;x.prototype._eventsCount=0;x.prototype._maxListeners=void 0;var mn=10;function Dt(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(x,"defaultMaxListeners",{enumerable:!0,get:function(){return mn},set:function(t){if(typeof t!="number"||t<0||ci(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");mn=t}});x.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};x.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ci(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 li(t){return t._maxListeners===void 0?x.defaultMaxListeners:t._maxListeners}x.prototype.getMaxListeners=function(){return li(this)};x.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")hn(u,this,r);else for(var c=u.length,l=mi(u,c),n=0;n<c;++n)hn(l[n],this,r);return!0};function di(t,e,r,n){var i,o,s;if(Dt(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=li(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,sa(a)}return t}x.prototype.addListener=function(e,r){return di(this,e,r,!1)};x.prototype.on=x.prototype.addListener;x.prototype.prependListener=function(e,r){return di(this,e,r,!0)};function aa(){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 pi(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=aa.bind(n);return i.listener=r,n.wrapFn=i,i}x.prototype.once=function(e,r){return Dt(r),this.on(e,pi(this,e,r)),this};x.prototype.prependOnceListener=function(e,r){return Dt(r),this.prependListener(e,pi(this,e,r)),this};x.prototype.removeListener=function(e,r){var n,i,o,s,a;if(Dt(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():ua(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};x.prototype.off=x.prototype.removeListener;x.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 fi(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?ca(i):mi(i,i.length)}x.prototype.listeners=function(e){return fi(this,e,!0)};x.prototype.rawListeners=function(e){return fi(this,e,!1)};x.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):hi.call(t,e)};x.prototype.listenerCount=hi;function hi(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}x.prototype.eventNames=function(){return this._eventsCount>0?bt(this._events):[]};function mi(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function ua(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ca(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function la(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))}gi(t,e,o,{once:!0}),e!=="error"&&da(t,i,{once:!0})})}function da(t,e,r){typeof t.on=="function"&&gi(t,"error",e,r)}function gi(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 yi=kr.exports,Ft={},bi={},vi=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},pa=vi,Ut=function(){return pa()&&!!Symbol.toStringTag},fa=Error,ha=EvalError,ma=RangeError,ga=ReferenceError,Ti=SyntaxError,Vt=TypeError,ya=URIError,gn=typeof Symbol<"u"&&Symbol,ba=vi,va=function(){return typeof gn!="function"||typeof Symbol!="function"||typeof gn("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ba()},jt={__proto__:null,foo:{}},Ta=Object,Sa=function(){return{__proto__:jt}.foo===jt.foo&&!(jt instanceof Ta)},Aa="Function.prototype.bind called on incompatible ",wa=Object.prototype.toString,Ea=Math.max,Ia="[object Function]",yn=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},Oa=function(e,r){for(var n=[],i=r,o=0;i<e.length;i+=1,o+=1)n[o]=e[i];return n},ka=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r},Na=function(e){var r=this;if(typeof r!="function"||wa.apply(r)!==Ia)throw new TypeError(Aa+r);for(var n=Oa(arguments,1),i,o=function(){if(this instanceof i){var l=r.apply(this,yn(n,arguments));return Object(l)===l?l:this}return r.apply(e,yn(n,arguments))},s=Ea(0,r.length-n.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+ka(a,",")+"){ return binder.apply(this,arguments); }")(o),r.prototype){var c=function(){};c.prototype=r.prototype,i.prototype=new c,c.prototype=null}return i},Ca=Na,Nr=Function.prototype.bind||Ca,La=Function.prototype.call,Pa=Object.prototype.hasOwnProperty,Ra=Nr,_a=Ra.call(La,Pa),R,Da=fa,Fa=ha,Ua=ma,Va=ga,Ye=Ti,He=Vt,xa=ya,Si=Function,Qt=function(t){try{return Si('"use strict"; return ('+t+").constructor;")()}catch{}},Ce=Object.getOwnPropertyDescriptor;if(Ce)try{Ce({},"")}catch{Ce=null}var Gt=function(){throw new He},Ba=Ce?function(){try{return arguments.callee,Gt}catch{try{return Ce(arguments,"callee").get}catch{return Gt}}}():Gt,Be=va(),Ma=Sa(),K=Object.getPrototypeOf||(Ma?function(t){return t.__proto__}:null),qe={},qa=typeof Uint8Array>"u"||!K?R:K(Uint8Array),Le={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?R:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?R:ArrayBuffer,"%ArrayIteratorPrototype%":Be&&K?K([][Symbol.iterator]()):R,"%AsyncFromSyncIteratorPrototype%":R,"%AsyncFunction%":qe,"%AsyncGenerator%":qe,"%AsyncGeneratorFunction%":qe,"%AsyncIteratorPrototype%":qe,"%Atomics%":typeof Atomics>"u"?R:Atomics,"%BigInt%":typeof BigInt>"u"?R:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?R:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?R:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?R:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Da,"%eval%":eval,"%EvalError%":Fa,"%Float32Array%":typeof Float32Array>"u"?R:Float32Array,"%Float64Array%":typeof Float64Array>"u"?R:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?R:FinalizationRegistry,"%Function%":Si,"%GeneratorFunction%":qe,"%Int8Array%":typeof Int8Array>"u"?R:Int8Array,"%Int16Array%":typeof Int16Array>"u"?R:Int16Array,"%Int32Array%":typeof Int32Array>"u"?R:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Be&&K?K(K([][Symbol.iterator]())):R,"%JSON%":typeof JSON=="object"?JSON:R,"%Map%":typeof Map>"u"?R:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Be||!K?R:K(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?R:Promise,"%Proxy%":typeof Proxy>"u"?R:Proxy,"%RangeError%":Ua,"%ReferenceError%":Va,"%Reflect%":typeof Reflect>"u"?R:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?R:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Be||!K?R:K(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?R:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Be&&K?K(""[Symbol.iterator]()):R,"%Symbol%":Be?Symbol:R,"%SyntaxError%":Ye,"%ThrowTypeError%":Ba,"%TypedArray%":qa,"%TypeError%":He,"%Uint8Array%":typeof Uint8Array>"u"?R:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?R:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?R:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?R:Uint32Array,"%URIError%":xa,"%WeakMap%":typeof WeakMap>"u"?R:WeakMap,"%WeakRef%":typeof WeakRef>"u"?R:WeakRef,"%WeakSet%":typeof WeakSet>"u"?R:WeakSet};if(K)try{null.error}catch(t){var $a=K(K(t));Le["%Error.prototype%"]=$a}var ja=function t(e){var r;if(e==="%AsyncFunction%")r=Qt("async function () {}");else if(e==="%GeneratorFunction%")r=Qt("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Qt("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&K&&(r=K(i.prototype))}return Le[e]=r,r},bn={__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"]},st=Nr,It=_a,Qa=st.call(Function.call,Array.prototype.concat),Ga=st.call(Function.apply,Array.prototype.splice),vn=st.call(Function.call,String.prototype.replace),Ot=st.call(Function.call,String.prototype.slice),Ka=st.call(Function.call,RegExp.prototype.exec),Wa=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ha=/\\(\\)?/g,za=function(e){var r=Ot(e,0,1),n=Ot(e,-1);if(r==="%"&&n!=="%")throw new Ye("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Ye("invalid intrinsic syntax, expected opening `%`");var i=[];return vn(e,Wa,function(o,s,a,u){i[i.length]=a?vn(u,Ha,"$1"):s||o}),i},Ya=function(e,r){var n=e,i;if(It(bn,n)&&(i=bn[n],n="%"+i[0]+"%"),It(Le,n)){var o=Le[n];if(o===qe&&(o=ja(n)),typeof o>"u"&&!r)throw new He("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new Ye("intrinsic "+e+" does not exist!")},at=function(e,r){if(typeof e!="string"||e.length===0)throw new He("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new He('"allowMissing" argument must be a boolean');if(Ka(/^%?[^%]*%?$/,e)===null)throw new Ye("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=za(e),i=n.length>0?n[0]:"",o=Ya("%"+i+"%",r),s=o.name,a=o.value,u=!1,c=o.alias;c&&(i=c[0],Ga(n,Qa([0,1],c)));for(var l=1,d=!0;l<n.length;l+=1){var p=n[l],m=Ot(p,0,1),T=Ot(p,-1);if((m==='"'||m==="'"||m==="`"||T==='"'||T==="'"||T==="`")&&m!==T)throw new Ye("property names with quotes must have matching quotes");if((p==="constructor"||!d)&&(u=!0),i+="."+p,s="%"+i+"%",It(Le,s))a=Le[s];else if(a!=null){if(!(p in a)){if(!r)throw new He("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ce&&l+1>=n.length){var y=Ce(a,p);d=!!y,d&&"get"in y&&!("originalValue"in y.get)?a=y.get:a=a[p]}else d=It(a,p),a=a[p];d&&!u&&(Le[s]=a)}}return a},Ai={exports:{}},Kt,Tn;function Cr(){if(Tn)return Kt;Tn=1;var t=at,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Kt=e,Kt}var Ja=at,vt=Ja("%Object.getOwnPropertyDescriptor%",!0);if(vt)try{vt([],"length")}catch{vt=null}var xt=vt,Sn=Cr(),Xa=Ti,Me=Vt,An=xt,Za=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Me("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Me("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Me("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Me("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Me("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Me("`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=!!An&&An(e,r);if(Sn)Sn(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 Xa("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},pr=Cr(),wi=function(){return!!pr};wi.hasArrayLengthDefineBug=function(){if(!pr)return null;try{return pr([],"length",{value:1}).length!==1}catch{return!0}};var eu=wi,tu=at,wn=Za,ru=eu(),En=xt,In=Vt,nu=tu("%Math.floor%"),iu=function(e,r){if(typeof e!="function")throw new In("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||nu(r)!==r)throw new In("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&En){var s=En(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!n)&&(ru?wn(e,"length",r,!0,!0):wn(e,"length",r)),e};(function(t){var e=Nr,r=at,n=iu,i=Vt,o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||e.call(s,o),u=Cr(),c=r("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var m=a(e,s,arguments);return n(m,1+c(0,p.length-(arguments.length-1)),!0)};var l=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:l}):t.exports.apply=l})(Ai);var Lr=Ai.exports,Ei=at,Ii=Lr,ou=Ii(Ei("String.prototype.indexOf")),Pr=function(e,r){var n=Ei(e,!!r);return typeof n=="function"&&ou(e,".prototype.")>-1?Ii(n):n},su=Ut(),au=Pr,fr=au("Object.prototype.toString"),Bt=function(e){return su&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:fr(e)==="[object Arguments]"},Oi=function(e){return Bt(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&fr(e)!=="[object Array]"&&fr(e.callee)==="[object Function]"},uu=function(){return Bt(arguments)}();Bt.isLegacyArguments=Oi;var cu=uu?Bt:Oi,lu=Object.prototype.toString,du=Function.prototype.toString,pu=/^\s*(?:function)?\*/,ki=Ut(),Wt=Object.getPrototypeOf,fu=function(){if(!ki)return!1;try{return Function("return function*() {}")()}catch{}},Ht,hu=function(e){if(typeof e!="function")return!1;if(pu.test(du.call(e)))return!0;if(!ki){var r=lu.call(e);return r==="[object GeneratorFunction]"}if(!Wt)return!1;if(typeof Ht>"u"){var n=fu();Ht=n?Wt(n):!1}return Wt(e)===Ht},Ni=Function.prototype.toString,Ge=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,hr,Tt;if(typeof Ge=="function"&&typeof Object.defineProperty=="function")try{hr=Object.defineProperty({},"length",{get:function(){throw Tt}}),Tt={},Ge(function(){throw 42},null,hr)}catch(t){t!==Tt&&(Ge=null)}else Ge=null;var mu=/^\s*class\b/,mr=function(e){try{var r=Ni.call(e);return mu.test(r)}catch{return!1}},zt=function(e){try{return mr(e)?!1:(Ni.call(e),!0)}catch{return!1}},St=Object.prototype.toString,gu="[object Object]",yu="[object Function]",bu="[object GeneratorFunction]",vu="[object HTMLAllCollection]",Tu="[object HTML document.all class]",Su="[object HTMLCollection]",Au=typeof Symbol=="function"&&!!Symbol.toStringTag,wu=!(0 in[,]),gr=function(){return!1};if(typeof document=="object"){var Eu=document.all;St.call(Eu)===St.call(document.all)&&(gr=function(e){if((wu||!e)&&(typeof e>"u"||typeof e=="object"))try{var r=St.call(e);return(r===vu||r===Tu||r===Su||r===gu)&&e("")==null}catch{}return!1})}var Iu=Ge?function(e){if(gr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ge(e,null,hr)}catch(r){if(r!==Tt)return!1}return!mr(e)&&zt(e)}:function(e){if(gr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(Au)return zt(e);if(mr(e))return!1;var r=St.call(e);return r!==yu&&r!==bu&&!/^\[object HTML/.test(r)?!1:zt(e)},Ou=Iu,ku=Object.prototype.toString,Ci=Object.prototype.hasOwnProperty,Nu=function(e,r,n){for(var i=0,o=e.length;i<o;i++)Ci.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Cu=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)},Lu=function(e,r,n){for(var i in e)Ci.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Pu=function(e,r,n){if(!Ou(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=n),ku.call(e)==="[object Array]"?Nu(e,r,i):typeof e=="string"?Cu(e,r,i):Lu(e,r,i)},Li=Pu,Ru=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],Yt=Ru,_u=typeof globalThis>"u"?Er:globalThis,Pi=function(){for(var e=[],r=0;r<Yt.length;r++)typeof _u[Yt[r]]=="function"&&(e[e.length]=Yt[r]);return e},kt=Li,Du=Pi,On=Lr,Rr=Pr,At=xt,Fu=Rr("Object.prototype.toString"),Ri=Ut(),kn=typeof globalThis>"u"?Er:globalThis,yr=Du(),_r=Rr("String.prototype.slice"),Jt=Object.getPrototypeOf,Uu=Rr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},Nt={__proto__:null};Ri&&At&&Jt?kt(yr,function(t){var e=new kn[t];if(Symbol.toStringTag in e){var r=Jt(e),n=At(r,Symbol.toStringTag);if(!n){var i=Jt(r);n=At(i,Symbol.toStringTag)}Nt["$"+t]=On(n.get)}}):kt(yr,function(t){var e=new kn[t],r=e.slice||e.set;r&&(Nt["$"+t]=On(r))});var Vu=function(e){var r=!1;return kt(Nt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=_r(i,1))}catch{}}),r},xu=function(e){var r=!1;return kt(Nt,function(n,i){if(!r)try{n(e),r=_r(i,1)}catch{}}),r},Bu=function(e){if(!e||typeof e!="object")return!1;if(!Ri){var r=_r(Fu(e),8,-1);return Uu(yr,r)>-1?r:r!=="Object"?!1:xu(e)}return At?Vu(e):null},Ct=Li,Mu=Pi,Nn=Lr,Dr=Pr,wt=xt,qu=Dr("Object.prototype.toString"),_i=Ut(),Cn=typeof globalThis>"u"?Er:globalThis,br=Mu(),Fr=Dr("String.prototype.slice"),Xt=Object.getPrototypeOf,$u=Dr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},Lt={__proto__:null};_i&&wt&&Xt?Ct(br,function(t){var e=new Cn[t];if(Symbol.toStringTag in e){var r=Xt(e),n=wt(r,Symbol.toStringTag);if(!n){var i=Xt(r);n=wt(i,Symbol.toStringTag)}Lt["$"+t]=Nn(n.get)}}):Ct(br,function(t){var e=new Cn[t],r=e.slice||e.set;r&&(Lt["$"+t]=Nn(r))});var ju=function(e){var r=!1;return Ct(Lt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Fr(i,1))}catch{}}),r},Qu=function(e){var r=!1;return Ct(Lt,function(n,i){if(!r)try{n(e),r=Fr(i,1)}catch{}}),r},Gu=function(e){if(!e||typeof e!="object")return!1;if(!_i){var r=Fr(qu(e),8,-1);return $u(br,r)>-1?r:r!=="Object"?!1:Qu(e)}return wt?ju(e):null},Ku=Gu,Wu=function(e){return!!Ku(e)};(function(t){var e=cu,r=hu,n=Bu,i=Wu;function o(S){return S.call.bind(S)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),c=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var m=o(Symbol.prototype.valueOf);function T(S,Mi){if(typeof S!="object")return!1;try{return Mi(S),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=i;function y(S){return typeof Promise<"u"&&S instanceof Promise||S!==null&&typeof S=="object"&&typeof S.then=="function"&&typeof S.catch=="function"}t.isPromise=y;function E(S){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(S):i(S)||b(S)}t.isArrayBufferView=E;function O(S){return n(S)==="Uint8Array"}t.isUint8Array=O;function w(S){return n(S)==="Uint8ClampedArray"}t.isUint8ClampedArray=w;function I(S){return n(S)==="Uint16Array"}t.isUint16Array=I;function L(S){return n(S)==="Uint32Array"}t.isUint32Array=L;function k(S){return n(S)==="Int8Array"}t.isInt8Array=k;function q(S){return n(S)==="Int16Array"}t.isInt16Array=q;function _(S){return n(S)==="Int32Array"}t.isInt32Array=_;function oe(S){return n(S)==="Float32Array"}t.isFloat32Array=oe;function se(S){return n(S)==="Float64Array"}t.isFloat64Array=se;function Re(S){return n(S)==="BigInt64Array"}t.isBigInt64Array=Re;function Ee(S){return n(S)==="BigUint64Array"}t.isBigUint64Array=Ee;function de(S){return u(S)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Mt(S){return typeof Map>"u"?!1:de.working?de(S):S instanceof Map}t.isMap=Mt;function Se(S){return u(S)==="[object Set]"}Se.working=typeof Set<"u"&&Se(new Set);function et(S){return typeof Set>"u"?!1:Se.working?Se(S):S instanceof Set}t.isSet=et;function _e(S){return u(S)==="[object WeakMap]"}_e.working=typeof WeakMap<"u"&&_e(new WeakMap);function qt(S){return typeof WeakMap>"u"?!1:_e.working?_e(S):S instanceof WeakMap}t.isWeakMap=qt;function De(S){return u(S)==="[object WeakSet]"}De.working=typeof WeakSet<"u"&&De(new WeakSet);function pe(S){return De(S)}t.isWeakSet=pe;function Fe(S){return u(S)==="[object ArrayBuffer]"}Fe.working=typeof ArrayBuffer<"u"&&Fe(new ArrayBuffer);function ut(S){return typeof ArrayBuffer>"u"?!1:Fe.working?Fe(S):S instanceof ArrayBuffer}t.isArrayBuffer=ut;function h(S){return u(S)==="[object DataView]"}h.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&h(new DataView(new ArrayBuffer(1),0,1));function b(S){return typeof DataView>"u"?!1:h.working?h(S):S instanceof DataView}t.isDataView=b;var A=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function N(S){return u(S)==="[object SharedArrayBuffer]"}function F(S){return typeof A>"u"?!1:(typeof N.working>"u"&&(N.working=N(new A)),N.working?N(S):S instanceof A)}t.isSharedArrayBuffer=F;function U(S){return u(S)==="[object AsyncFunction]"}t.isAsyncFunction=U;function P(S){return u(S)==="[object Map Iterator]"}t.isMapIterator=P;function D(S){return u(S)==="[object Set Iterator]"}t.isSetIterator=D;function B(S){return u(S)==="[object Generator]"}t.isGeneratorObject=B;function Y(S){return u(S)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=Y;function Ie(S){return T(S,c)}t.isNumberObject=Ie;function ct(S){return T(S,l)}t.isStringObject=ct;function Ue(S){return T(S,d)}t.isBooleanObject=Ue;function lt(S){return s&&T(S,p)}t.isBigIntObject=lt;function xr(S){return a&&T(S,m)}t.isSymbolObject=xr;function xi(S){return Ie(S)||ct(S)||Ue(S)||lt(S)||xr(S)}t.isBoxedPrimitive=xi;function Bi(S){return typeof Uint8Array<"u"&&(ut(S)||F(S))}t.isAnyArrayBuffer=Bi,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(S){Object.defineProperty(t,S,{enumerable:!1,value:function(){throw new Error(S+" is not supported in userland")}})})})(bi);var Hu=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},vr={exports:{}};typeof Object.create=="function"?vr.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:vr.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 zu=vr.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(b){for(var A=Object.keys(b),N={},F=0;F<A.length;F++)N[A[F]]=Object.getOwnPropertyDescriptor(b,A[F]);return N},r=/%[sdj%]/g;t.format=function(h){if(!k(h)){for(var b=[],A=0;A<arguments.length;A++)b.push(s(arguments[A]));return b.join(" ")}for(var A=1,N=arguments,F=N.length,U=String(h).replace(r,function(D){if(D==="%%")return"%";if(A>=F)return D;switch(D){case"%s":return String(N[A++]);case"%d":return Number(N[A++]);case"%j":try{return JSON.stringify(N[A++])}catch{return"[Circular]"}default:return D}}),P=N[A];A<F;P=N[++A])w(P)||!se(P)?U+=" "+P:U+=" "+s(P);return U},t.deprecate=function(h,b){if(typeof C<"u"&&C.noDeprecation===!0)return h;if(typeof C>"u")return function(){return t.deprecate(h,b).apply(this,arguments)};var A=!1;function N(){if(!A){if(C.throwDeprecation)throw new Error(b);C.traceDeprecation?console.trace(b):console.error(b),A=!0}return h.apply(this,arguments)}return N};var n={},i=/^$/;if(C.env.NODE_DEBUG){var o=C.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(h){if(h=h.toUpperCase(),!n[h])if(i.test(h)){var b=C.pid;n[h]=function(){var A=t.format.apply(t,arguments);console.error("%s %d: %s",h,b,A)}}else n[h]=function(){};return n[h]};function s(h,b){var A={seen:[],stylize:u};return arguments.length>=3&&(A.depth=arguments[2]),arguments.length>=4&&(A.colors=arguments[3]),O(b)?A.showHidden=b:b&&t._extend(A,b),_(A.showHidden)&&(A.showHidden=!1),_(A.depth)&&(A.depth=2),_(A.colors)&&(A.colors=!1),_(A.customInspect)&&(A.customInspect=!0),A.colors&&(A.stylize=a),l(A,h,A.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(h,b){var A=s.styles[b];return A?"\x1B["+s.colors[A][0]+"m"+h+"\x1B["+s.colors[A][1]+"m":h}function u(h,b){return h}function c(h){var b={};return h.forEach(function(A,N){b[A]=!0}),b}function l(h,b,A){if(h.customInspect&&b&&de(b.inspect)&&b.inspect!==t.inspect&&!(b.constructor&&b.constructor.prototype===b)){var N=b.inspect(A,h);return k(N)||(N=l(h,N,A)),N}var F=d(h,b);if(F)return F;var U=Object.keys(b),P=c(U);if(h.showHidden&&(U=Object.getOwnPropertyNames(b)),Ee(b)&&(U.indexOf("message")>=0||U.indexOf("description")>=0))return p(b);if(U.length===0){if(de(b)){var D=b.name?": "+b.name:"";return h.stylize("[Function"+D+"]","special")}if(oe(b))return h.stylize(RegExp.prototype.toString.call(b),"regexp");if(Re(b))return h.stylize(Date.prototype.toString.call(b),"date");if(Ee(b))return p(b)}var B="",Y=!1,Ie=["{","}"];if(E(b)&&(Y=!0,Ie=["[","]"]),de(b)){var ct=b.name?": "+b.name:"";B=" [Function"+ct+"]"}if(oe(b)&&(B=" "+RegExp.prototype.toString.call(b)),Re(b)&&(B=" "+Date.prototype.toUTCString.call(b)),Ee(b)&&(B=" "+p(b)),U.length===0&&(!Y||b.length==0))return Ie[0]+B+Ie[1];if(A<0)return oe(b)?h.stylize(RegExp.prototype.toString.call(b),"regexp"):h.stylize("[Object]","special");h.seen.push(b);var Ue;return Y?Ue=m(h,b,A,P,U):Ue=U.map(function(lt){return T(h,b,A,P,lt,Y)}),h.seen.pop(),y(Ue,B,Ie)}function d(h,b){if(_(b))return h.stylize("undefined","undefined");if(k(b)){var A="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return h.stylize(A,"string")}if(L(b))return h.stylize(""+b,"number");if(O(b))return h.stylize(""+b,"boolean");if(w(b))return h.stylize("null","null")}function p(h){return"["+Error.prototype.toString.call(h)+"]"}function m(h,b,A,N,F){for(var U=[],P=0,D=b.length;P<D;++P)De(b,String(P))?U.push(T(h,b,A,N,String(P),!0)):U.push("");return F.forEach(function(B){B.match(/^\d+$/)||U.push(T(h,b,A,N,B,!0))}),U}function T(h,b,A,N,F,U){var P,D,B;if(B=Object.getOwnPropertyDescriptor(b,F)||{value:b[F]},B.get?B.set?D=h.stylize("[Getter/Setter]","special"):D=h.stylize("[Getter]","special"):B.set&&(D=h.stylize("[Setter]","special")),De(N,F)||(P="["+F+"]"),D||(h.seen.indexOf(B.value)<0?(w(A)?D=l(h,B.value,null):D=l(h,B.value,A-1),D.indexOf(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qi=require("pino"),v=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),z=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),M=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),dt=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),J=require("nanostores"),$e=require("uuid"),j=require("@connectrpc/connect"),Br=require("@connectrpc/connect-web"),Mr=require("@nanostores/query"),Vn=require("@streamlayer/sl-eslib/sports/events/events_pb"),ot=require("@streamlayer/sl-eslib/sdkSettings/client/client_pb"),Ar=require("@streamlayer/sl-eslib/users/users_pb"),xn=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb"),$i=require("@streamlayer/sl-eslib/shortLinks/linksClient_pb"),qr=require("@streamlayer/sl-eslib/polymarket/sportsClient_pb"),m=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),Bn=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_pb"),$r=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),ne=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function ji(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Mn={exports:{}},Q=Mn.exports={},ue,ce;function sr(){throw new Error("setTimeout has not been defined")}function ar(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?ue=setTimeout:ue=sr}catch{ue=sr}try{typeof clearTimeout=="function"?ce=clearTimeout:ce=ar}catch{ce=ar}})();function qn(t){if(ue===setTimeout)return setTimeout(t,0);if((ue===sr||!ue)&&setTimeout)return ue=setTimeout,setTimeout(t,0);try{return ue(t,0)}catch{try{return ue.call(null,t,0)}catch{return ue.call(this,t,0)}}}function Qi(t){if(ce===clearTimeout)return clearTimeout(t);if((ce===ar||!ce)&&clearTimeout)return ce=clearTimeout,clearTimeout(t);try{return ce(t)}catch{try{return ce.call(null,t)}catch{return ce.call(this,t)}}}var be=[],Ke=!1,ke,mt=-1;function Gi(){!Ke||!ke||(Ke=!1,ke.length?be=ke.concat(be):mt=-1,be.length&&$n())}function $n(){if(!Ke){var t=qn(Gi);Ke=!0;for(var e=be.length;e;){for(ke=be,be=[];++mt<e;)ke&&ke[mt].run();mt=-1,e=be.length}ke=null,Ke=!1,Qi(t)}}Q.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];be.push(new jn(t,e)),be.length===1&&!Ke&&qn($n)};function jn(t,e){this.fun=t,this.array=e}jn.prototype.run=function(){this.fun.apply(null,this.array)};Q.title="browser";Q.browser=!0;Q.env={};Q.argv=[];Q.version="";Q.versions={};function Te(){}Q.on=Te;Q.addListener=Te;Q.once=Te;Q.off=Te;Q.removeListener=Te;Q.removeAllListeners=Te;Q.emit=Te;Q.prependListener=Te;Q.prependOnceListener=Te;Q.listeners=function(t){return[]};Q.binding=function(t){throw new Error("process.binding is not supported")};Q.cwd=function(){return"/"};Q.chdir=function(t){throw new Error("process.chdir is not supported")};Q.umask=function(){return 0};var Ki=Mn.exports;const C=ji(Ki),Wi=qi.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),Z=(t,e)=>Wi.child({name:t},e);class Hi extends Event{slEventBus;constructor(e,r){super(e),this.slEventBus=r}}const zi=Z("event-bus");class Yi{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,r)=>{const n=new Hi(this.name,{...r,type:e});zi.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 Xi{}var ve;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(ve||(ve={}));window.slStore=Object.create(null);class Rt{store;name;constructor(e,r){this.store=e,this.name=r}getStore(){return this.store}}const Ji=t=>{const e=Object.keys(t);return J.computed(e.map(r=>t[r].getStore()),(...r)=>Object.fromEntries(e.map((n,i)=>[n,r[i]])))};class Ne extends Rt{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 X=t=>J.map(t);var me;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(me||(me={}));const Zi={[M.SdkOverlayType.BETTING]:"betting",[M.SdkOverlayType.GAMES]:"games",[M.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[M.SdkOverlayType.TWITTER]:"twitter"};var we;(function(t){t.Ready="ready",t.Suspended="suspended"})(we||(we={}));const eo=new Set(["equals","clone","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","getType"]);class Qn{status;listeners=new Set;constructor(){this.status=J.atom(we.Suspended)}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(we.Ready)};disable=()=>{this.status.set(we.Suspended)};fireEvent(e){for(const r of this.listeners.values())try{r.onEvent(e)}catch(n){console.error(n)}}}class Gn{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...r},n){this.settingsKey=Zi[r.type],this.status=J.atom(we.Suspended),this.config=new Ne(X(r),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ne(X(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ne(X({}),`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(we.Ready)};disable=()=>{this.status.set(we.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)!eo.has(o)&&i[o]&&this.settings.setValue(o,i[o])}}};update=(e,r)=>{this.source===me.STREAM&&r===me.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 te extends Rt{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 G=t=>J.atom(t);class ie extends Rt{atomStore;constructor(e,r,n){super(e,`api:${r}`),this.atomStore=J.atom(),n&&e.subscribe(i=>{const o=this.atomStore.get(),s=n(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;getValue=()=>new Promise((e,r)=>window.requestAnimationFrame(async()=>{try{const n=this.getStore();if(n.value===void 0)throw new Error("no store");if(!n.key){e(void 0);return}await n.fetch(),e(n.get().data)}catch(n){r(n)}}));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 V=new Yi;async function*to(t,e){for await(const r of e){t.response.message=r,t.received_at=Date.now(),t.id=Date.now();const n={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(n),yield r}}const ro=()=>t=>async e=>{const r={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};try{window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:r})}catch(n){console.log("devtools error",n)}try{const n=await t(e);if(r.received_at=Date.now(),r.response.header=Object.fromEntries(n.header.entries()),r.response.trailer=Object.fromEntries(n.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...r,stream:!0}};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}return{...n,message:to(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};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}}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};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}throw n}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Kn(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class Je{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){Kn(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 re;(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"})(re||(re={}));const jr=Z("grpc:stream");class no{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,r,n,i){const o={status:re.Init,ts:new Date,log:[]};this.state=new Ne(X(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 te(G(null),`subscription:${i.name}:store`)),"subscribe"in n&&typeof n.subscribe=="function"&&(this.paramsListener=n.subscribe(s=>{this.state.getValue("status")===re.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(re.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const r=this.state.getStore().get().log,n=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(r.push(n),this.state.setValue("log",r),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?jr.trace({name:this.options.name,attempt:this.attempt},"received data"):jr.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
+
`+n)}catch(i){Kn(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(re.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 j.ConnectError&&n.code!=j.Code.Canceled&&this.onStreamError(n)}})(),this.updateState(re.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(re.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(re.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(re.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 j.ConnectError&&e.code!==j.Code.Canceled){this.updateState(re.Failed),this.state.setValue("error",e),e.code===j.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const io=new Set([j.Code.Unknown,j.Code.Internal,j.Code.DeadlineExceeded,j.Code.ResourceExhausted,j.Code.FailedPrecondition,j.Code.Unavailable,j.Code.DataLoss]),Qr=Z("grpc:retry"),oo=t=>async e=>{const r=e.contextValues.get(ur.retryAttempts),n=300,i=e.contextValues.get(ur.retryDelay);if(e.stream||r===0)return t(e);Qr.trace({url:e.url,attempts:r,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Qr.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=j.ConnectError.from(s);if(o>=r||!(a instanceof j.ConnectError)||!io.has(a.code))throw s;const u=Math.min(i,Math.pow(2,o)*n),c=Math.round(u*(1+Math.random())/2);await new Promise(l=>setTimeout(l,c))}},ur={retryAttempts:j.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:j.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},so=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=$e.v4();return localStorage.setItem("sl-device-id",e),e},ao=()=>navigator.userAgentData?.platform||navigator.platform,uo=t=>t?"webOS":navigator.userAgentData&&navigator.userAgentData.mobile||"ontouchstart"in window||navigator.maxTouchPoints>0?"mobile-web":"desktop-web";class Gr{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;storeCache;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,r){this.host=e,this.opts=r,this.$headers=new Ne(X({"sl-device-id":so(),"sl-device-os":ao(),"sl-platform":uo(r?.webOS)}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map,this.storeCache=new Map;const[n,i,o]=Mr.nanoquery({dedupeTime:r?.dedupeTime,revalidateInterval:r?.refetchInterval});this.nanoquery={createFetcherStore:n,createMutatorStore:i,utils:o},this.transport=Br.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=Br.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,r,n)=>{const i=this.subscriptions.get(r);if(i)return i;const o=new no(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]=Mr.nanoquery({dedupeTime:this.opts?.dedupeTime,revalidateInterval: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=j.createClient(e,this.transport);return this.clients.set(r,n),n};getStreamClient=e=>{const r=`stream-${e.typeName}`;if(this.clients.has(r))return this.clients.get(r);const n=j.createClient(e,this.streamTransport);return this.clients.set(r,n),n};createPromiseClient=(e,{params:r=[],method:n})=>{const i=this.getClient(e),o=n.toString(),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:c=>{const l=j.createContextValues();for(const d in c){const p=ur[d];l.set(p,c[d])}return l},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),window.localStorage.getItem("SL_GRPC_DEVTOOLS")==="true"?this.interceptors.push(ro()):console.warn("SL GRPC DevTools is disabled. To enable, set SL_GRPC_DEVTOOLS to true in localStorage."),this.opts?.retryable&&this.interceptors.push(oo)}}const co=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Vn.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""}}})},lo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.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})},po=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Vn.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>s?(await r.summary({id:s})).data?.attributes:void 0})},fo=(t,e)=>{const{queryKey:r,client:n}=e.createPromiseClient(Ar.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{if(!e.getHeader("authorization"))return{data:void 0};const{data:o}=await n.me({});return{data:o}}})},ho=t=>{const{client:e,createRequestOptions:r}=t.createPromiseClient(Ar.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})},mo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.get({})).data?.attributes})},go=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.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}})},yo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(ot.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>(await r.getOrganizationAdvertising({})).data?.attributes})},bo=(t,e,r)=>{t.transport=new Gr(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0,webOS:e.webOS}),t.analyticsTransport=new Gr(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 he;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(he||(he={}));class je extends Je{constructor(){super("user")}setSchema=e=>{this.write(he.SCHEMA,e)};getSchema=()=>this.read(he.SCHEMA);setToken=e=>{this.write(he.TOKEN,e)};getToken=()=>this.read(he.TOKEN);setExternalToken=e=>{this.write(he.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(he.EXTERNAL_TOKEN);removeToken=()=>{this.remove(he.TOKEN)}}var ge;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(ge||(ge={}));const vo=t=>{const e=new je,r=new te(G(e.getExternalToken()),"userKey"),n=new te(G(e.getToken()),"userToken"),i=new ie(fo(n.getStore(),t),"user",({data:s,error:a,loading:u},c)=>{if(!a)return s?.data?.id?s.data.id:u===!1?void 0:c}),o=new ie(mo(n.getStore(),t),"userSettings");return{userKey:r,userToken:n,user:i,userSettings:o}},To=t=>{const e=new te(G(void 0),"providerStreamId"),r=new ie(co(e.getStore(),t),"slStreamId",o=>o?.data),n=new ie(lo(r.getAtomStore(),t),"streamSettings"),i=new ie(po(r.getAtomStore(),t),"streamSettings");return r.getAtomStore().listen(o=>{(o===""||o===void 0)&&(n.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:r,streamSettings:n,streamSummary:i}},So=t=>{const e=new te(G(void 0),"enabled"),r=new te(G(ge.DISABLED),"status"),n=new ie(go(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new ie(yo(n.getAtomStore(),t),"organizationAdvertising"),o=vo(t),s=To(t);return{enabled:e,status:r,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:n,organizationAdvertising:i}};class Ao extends Rt{stores;constructor(e){const r=So(e),n=Ji(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 wo=(t,e,r)=>{t.store=new Ao(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([n,i])=>[n,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},r()},Eo=t=>{const{client:e}=t.createPromiseClient(xn.Leaderboard,{method:"list"});return r=>e.list(r)},Wn=t=>{const{client:e}=t.createPromiseClient(xn.Leaderboard,{method:"summary"});return r=>e.summary(r)},Io=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(Ar.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[]}}})},Oo=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(z.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>(await r.get({eventId:s})).data?.attributes,revalidateInterval:0,dedupeTime:1e3*60*60})},ko=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(z.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const c=await n.syncQuestion({filter:{eventId:a}});if(c.data?.attributes?.question?.type!==v.QuestionType.PROMOTION)return c.data?.attributes},dedupeTime:1e3*60*10,revalidateInterval:0})},No=async(t,e)=>{const{client:r}=e.createPromiseClient(z.Feed,{method:"item",params:[t]});return(await r.item({id:t})).data},Co=(t,e)=>{const{client:r}=e.createStreamClient(z.Feed),n=J.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{n.set({eventId:o,feedId:""})}),e.addSubscription(r.subscription,n,{name:"feedSubscription"})},Po=(t,e)=>{const{client:r}=e.createStreamClient(z.Feed);return e.addSubscription(r.questionSubscription,{questionId:t},{name:"questionSubscription"})},Hn=async(t,e)=>{const{client:r}=e.createPromiseClient(z.Feed,{method:"questionByUser",params:[t]});return(await r.questionByUser({questionId:t})).data?.attributes?.question},gt=(t,e)=>{const{client:r,queryKey:n,queryKeyStr:i}=e.createPromiseClient(z.Feed,{method:"questionByUser",params:[t]});let o=i;if(typeof t!="object"?o+=t:o+="atom",e.storeCache.has(o))return e.storeCache.get(o);{const s=e.nanoquery.createFetcherStore(n,{fetcher:async(a,u,c)=>(await r.questionByUser({questionId:c})).data?.attributes?.question,dedupeTime:1/0,revalidateInterval:0});return e.storeCache.set(o,s),s}},zn=async(t,e)=>{if(!t)return;const{client:r}=e.createPromiseClient(z.Feed,{method:"getQuestion",params:[t]}),n=await r.getQuestion({id:t});if(!n.data?.attributes)return;const{options:i,notification:o,...s}=n.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},Lo=(t,e,r,n,i,o,s)=>{const{client:a,queryKey:u}=s.createPromiseClient(z.Feed,{method:"list",params:[t,e,o?"true":""]});return s.nanoquery.createFetcherStore(u,{fetcher:async(c,l,d,p,g)=>{if(!d||g)return[];const T=await a.list({eventId:d,filter:{types:p===Ae.ALLOWED?[]:[v.QuestionType.FACTOID,v.QuestionType.PROMOTION,v.QuestionType.TWEET],statuses:[v.QuestionStatus.ACTIVE,v.QuestionStatus.RESOLVED]}}),y={eventId:d,userId:r.get(),organizationId:n.get()};for(const E of T.data)i.isQuestionReceived(y,E.id)||(V.emit("poll",{action:"received",payload:{isAd:E.attributes?.adUnit==v.AdUnit.UNSET,questionId:E.id,questionType:E.attributes?.type}}),i.saveQuestionReceived(y,E.id));return T.data},dedupeTime:1/0,revalidateInterval:0})},Ro=(t,e)=>{const{client:r,queryKey:n}=e.createPromiseClient(z.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await r.list({eventId:s,filter:{types:[v.QuestionType.PROMOTION],statuses:[v.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u.type==="promotion")return zn(u.id,e)},dedupeTime:1/0,revalidateInterval:0})},_o=(t,e,r,n,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(z.Feed,{method:"betPack",params:[t,e,r]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,c,l,d)=>{if(!c||!l||!d)return{timestamp:Date.now(),data:null};const p=await o.betPack({eventId:c,types:[v.QuestionType.PREDICTION],statuses:[v.QuestionStatus.ACTIVE,v.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!p.data||!p.data.length?{timestamp:Date.now(),data:null}:{timestamp:Date.now(),data:p.data?.reduce((g,T)=>{const y=T?.attributes?.question;if(!y?.id)return g;const E={eventId:c,userId:l,organizationId:d};return n.isQuestionReceived(E,y.id)||(V.emit("poll",{action:"received",payload:{isAd:y?.adUnit==v.AdUnit.UNSET,questionId:y.id,questionType:y.type}}),n.saveQuestionReceived(E,y.id)),y.answers=y.answers.sort((O,w)=>O.id>w.id?1:-1),{...g,[y.id]:y}},{})}},dedupeTime:1/0,revalidateInterval:0})},Do=(t,e,r)=>{const n=J.batched([e,r],()=>{const a=e.get();if(!a)return;const u=r.get().data?.find(l=>l.id===a?.questionId),c=a?.question?.openedFrom;return u?(u.openedFrom=c,u):a.question}),i=J.batched(n,a=>a&&a.type==="question"?a.id:void 0),o=gt(i,t);return{$store:n,$extendedStore:o,updateExtendedQuestion:a=>{const u=o.get().data,c=(l,d)=>{if(!l||!d)return(l||d||[]).sort((y,E)=>y.id>E.id?1:-1);const p=l.sort((y,E)=>y.id>E.id?1:-1),g=d.sort((y,E)=>y.id>E.id?1:-1),T=[];for(let y=0;y<p.length;y++)T.push({...p[y],...g[y],correct:p[y].correct,youVoted:p[y].youVoted,pointsEarned:p[y].pointsEarned});return T};o.mutate({...a,options:u?.options,subject:u?.subject,appearance:u?.appearance,answers:c(u?.answers,a?.answers)})}}};var Qe;(function(t){t.SHOWED="showed",t.EVENT="ev"})(Qe||(Qe={}));class Fo extends Je{constructor(){super("advertisement")}setShowed=e=>{this.write(Qe.SHOWED,e,"true")};isViewed=e=>this.read(Qe.SHOWED,e);fireEvent=(e,r)=>{this.write(Qe.EVENT,r,e,"true")};isEventFired=(e,r)=>this.read(Qe.EVENT,r,e)==="true"}const Uo=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:n,notification:i,...o}=e,s=n?.options.case==="promotion"?n.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},pt=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,Vo=({gamOptions:t,gamBaseUrl:e})=>{const r=`${e}?`,n=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")n.push(`${o}=${pt(s)}`);else if(Array.isArray(s))n.push(`${o}=${s.map(pt).join(",")}`);else{const a=Object.entries(s).map(([u,c])=>Array.isArray(c)?`${u}=${c.map(pt).join(",")}`:typeof c=="string"?`${u}=${pt(c)}`:`${u}=${c}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");n.push(`${o}=${a}`)}}return r+n.join("&")},Ve=t=>(t?.promotion?.type===v.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===v.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,xo=(t,e,r)=>{let n=!1;const i=r.transport,o=Z("advertisement"),s=new Fo,a=(w,I)=>{s.fireEvent(w,I)},u=(w,I)=>s.isEventFired(w,I),c=X({}),l=Ro(t,i),d=w=>{const I=c.get(),P=I.data?.question.id,k=I.data?.promotion?.type;if(!P)return;c.get()?.isOpened||(c.setKey("isOpened",!0),V.emit("advertisement",{action:"opened",payload:{id:P,type:k,hasBanner:Ve(I.data),openedFrom:w?.fromNotification?"notification":"auto"}})),w?.fromNotification&&(c.setKey("hasNotification",!1),V.emit("advertisement",{action:"notification-opened",payload:{id:P,type:k,hasBanner:Ve(I.data)}}))},p=()=>{const w=c.get(),I=w.data?.question.id,P=w.data?.promotion?.type,k=c.get()?.isOpened;I&&!k&&(o.debug({id:I},"markAsViewed: %o"),s.setShowed(I),c.setKey("isOpened",!0),V.emit("advertisement",{action:"viewed",payload:{id:I,type:P,hasBanner:Ve(w.data)}}))},g=(w,I)=>{I?c.set({loading:!1,error:void 0,data:I,hasNotification:I?.notification?.enabled===v.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>T(I.question.id),togglePause:P=>y(I.question.id,P),toggleMute:P=>E(I.question.id,P),isViewed:!!s.isViewed(I.question.id),fireEvent:P=>a(w,P),isEventFired:P=>u(w,P)}):(c.setKey("loading",!0),zn(w,i).then(P=>c.set({loading:!1,error:void 0,data:P,hasNotification:P?.notification?.enabled===v.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>T(P?.question.id),togglePause:k=>y(P?.question.id,k),toggleMute:k=>E(P?.question.id,k),isViewed:P&&!!s.isViewed(P.question.id),fireEvent:k=>a(w,k),isEventFired:k=>u(w,k)})).catch(P=>c.set({loading:!1,error:P,data:void 0,fireEvent:()=>{},isEventFired:()=>!1})))};c.subscribe((w,I)=>{if(!(w.data?.id===I?.data?.id&&w.isPaused!==I?.isPaused)){if(w.data?.promotion?.type===v.PromotionType.EXTERNAL_AD&&!w?.externalAd&&w.data.promotion.adCampaigns?.desktopWebSettings){const P=Vo(w.data.promotion.adCampaigns.desktopWebSettings);c.setKey("externalAd",{type:"gam",url:P})}w.data?.promotion&&!w.isOpened&&(V.emit("advertisement",{action:"received",payload:{id:w.data.question.id,type:w.data.promotion.type,hasNotification:!!w.hasNotification,hasBanner:Ve(w.data),isViewed:!!s.isViewed(w.data.question.id)},skipAnalytics:w.data.question.id===I?.data?.question.id}),w.data.question.id!==I?.data?.question.id&&!s.isViewed(w.data.question.id)&&V.emit("advertisement",{action:"notification-received",payload:{id:w.data.question.id,type:w.data.promotion.type,hasNotification:!0,hasBanner:Ve(w.data),isViewed:!1}})),!w?.data&&I?.data&&V.emit("advertisement",{action:"closed",payload:{id:I.data.question.id,type:I.data.promotion?.type,hasNotification:!!I.hasNotification,hasBanner:Ve(I.data),isViewed:!!s.isViewed(I.data.question.id)}})}});const T=w=>{(!w||c.get()?.data?.question.id===w)&&c.set({})},y=(w,I)=>{c.get()?.data?.question.id===w&&c.setKey("isPaused",I)},E=(w,I)=>{c.get()?.data?.question.id===w&&c.setKey("isMuted",I)};return{connect:()=>{n||(n=!0,l.subscribe((w,I)=>{w.data&&(!I?.data||w.data.id!==I.data.id)&&g(w.data.question.id,w.data)}),e.addListener("promotion",w=>{const I=Uo(w);if(I){if(I.question.status===v.QuestionStatus.RESOLVED){T(I.question.id),o.debug({promotion:I},"resolved: %o");return}if(I.question.status===v.QuestionStatus.ACTIVE){o.debug({promotion:I},"active: %o"),g(I.question.id,I);return}o.debug({promotion:I},"skip: %o")}}))},hide:T,show:g,open:d,markAsViewed:p,$store:c}};var ae;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.QUESTION_RECEIVED="q-received",t.QUESTION_OPENED="q-opened"})(ae||(ae={}));class Bo extends Je{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,r)=>{this.write(...e,r)};readValue=e=>this.read(...e)}class Mo extends Je{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new Bo}saveQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.QUESTION_RECEIVED,n,e,r,i,"1")};isQuestionReceived=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(ae.QUESTION_RECEIVED,n,e,r,i);saveQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.QUESTION_OPENED,n,e,r,i,"1")};isQuestionOpened=({userId:e,eventId:r,organizationId:n},i)=>!!this.read(ae.QUESTION_OPENED,n,e,r,i);saveOnboardingStatus=({userId:e,eventId:r,organizationId:n},i)=>{this.write(ae.ONBOARDING,n,e,r,i)};getOnboardingStatus=({userId:e,eventId:r,organizationId:n})=>this.read(ae.ONBOARDING,n,e,r);setOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>{this.sessionStorage.writeValue([ae.ONBOARDING_IO,n,e,r],"1")};getOnboardingInstantOpen=({userId:e,eventId:r,organizationId:n})=>this.sessionStorage.readValue([ae.ONBOARDING_IO,n,e,r])}var Ae;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Ae||(Ae={}));class qo{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=Z("gamification-background"),this.storage=new Mo,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new te(G(void 0),"moderationId").getStore(),this.interactiveAllowed=new te(G(Ae.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new te(G(void 0),"openedQuestionId").getStore(),this.notifications=e.notifications,this.moderation=new ie(Oo(this.slStreamId,e.transport),"gamification:moderation");const r=!!e.sdk.options.get().betPack;this.feedList=new ie(Lo(this.slStreamId,this.interactiveAllowed,this.userId,this.organizationId,this.storage,r,e.transport),"gamification:feedList"),this.betPack=new ie(_o(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=ko(this.slStreamId,r,e.transport),this.openedQuestion=Do(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(n=>{this.log.debug({item:n},"received question"),n?.questionId?(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0),this.questionSubscription=Po(n.questionId,e.transport),this.questionSubscription.addListener("feed-subscription-opened-question",i=>{const o=i.data?.attributes?.question;if(this.openedQuestion.updateExtendedQuestion(o),this.betPack&&o?.type===v.QuestionType.PREDICTION&&(o.status===v.QuestionStatus.ACTIVE||o.status===v.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data?.data||{},a=s?.[o.id];if(a){const u=[],c=a.answers.sort((d,p)=>d.id>p.id?1:-1),l=o.answers.sort((d,p)=>d.id>p.id?1:-1);for(let d=0;d<c.length;d++)u.push({...c[d],...l[d],correct:c[d].correct,youVoted:c[d].youVoted,pointsEarned:c[d].pointsEarned});this.betPack.getStore().mutate({timestamp:Date.now(),data:{...s,[o.id]:{...a,status:o.status,marketClosed:o.marketClosed,activatedAt:o.activatedAt,answerSetAt:o.answerSetAt,answers:u}}})}}}),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=Co(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async n=>{const i=n.data?.attributes?.question;if(this.betPack&&i?.type===v.QuestionType.PREDICTION&&(i.status===v.QuestionStatus.ACTIVE||i.status===v.QuestionStatus.RESOLVED)){const o=this.betPack.getValues().data?.data||{},s=o?.[i.id];if(s)this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:{...s,status:i.status,marketClosed:i.marketClosed,activatedAt:i.activatedAt,answerSetAt:i.answerSetAt}}});else if(!s&&Object.keys(o).length<5){const a=await Hn(i.id,this.transport);this.betPack.getStore().mutate({timestamp:Date.now(),data:{...o,[i.id]:a}})}}})),this.cancels.add(this.feedSubscription.addListener("feed-subscription-active-question",n=>{const i=this.activeQuestionId.get().data?.question?.id,o=n.data?.attributes?.question;if(!(!o||o.type===v.QuestionType.PROMOTION)){if(o.status===v.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(n.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",n=>{window.requestAnimationFrame(()=>{n.data?.attributes?.question===void 0&&n.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((n,i)=>{n.data?.feedItem&&n.data?.feedItem?.id!==i?.data?.feedItem?.id&&e.onQuestionActivate({stage:"activate",id:n.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:n.data.feedItem.id})),hasNotification:!0,type:n.data.feedItem.type}),!n.data?.feedItem&&i?.data?.feedItem&&e.onQuestionActivate({stage:"deactivate",id:i.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:i.data.feedItem.id})),hasNotification:!0,type:i.data.feedItem.type})})),this.feedSubscription.connect(),this.cancels.add(this.interactiveAllowed.listen(()=>{window.requestAnimationFrame(()=>{this.activeQuestionId.invalidate()})})),e.sdk.onMount({name:"gamification-background"},()=>()=>{this.activeQuestionId.off();for(const n of this.cancels)n(),this.cancels.delete(n)}),r||(this.advertisement=xo(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 $o{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=Z("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=G(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}V.emit("notification",{action:"received",payload:{type:r.type,questionId:r.data.questionId,questionType:r.data.questionType}});const n=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(r.id,r),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:r.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},r.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},r.delay||0);this.timeouts.set(e,n),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:r=!0}={})=>{const n=new Map(this.notificationsList.get()),i=n.get(e);if(i){const o=!(this.waitingQueue.size>=this.options.concurrency)&&r;i.hiding=o,this.notificationsList.set(n);const s=()=>{const a=new Map(this.notificationsList.get());a.delete(e),this.notificationsList.set(a);const u=this.timeouts.get(e);u!==void 0&&(clearTimeout(u),this.timeouts.delete(e)),this.logger.debug({notificationId:e},"notification hidden"),i.hiding&&V.emit("notification",{action:"closed",payload:{type:i.type,questionId:i.data.questionId,questionType:i.data.questionType}})};if(o){const a=setTimeout(s,this.options.animationDelay||0);this.timeouts.set(e,a)}else s()}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 Et;(function(t){t.OPENED="opened"})(Et||(Et={}));class jo extends Je{constructor(){super("notification")}setOpened=e=>{this.write(Et.OPENED,e,"true")};isOpened=e=>this.read(Et.OPENED,e);clearNotification=()=>{this.clear()}}class Qo{queue;storage;constructor(e={}){this.storage=new jo,this.queue=new $o({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),V.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)};update=(e,r)=>{const n=this.queue.notificationsList.get()?.get(e);r(n)};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 Go=(t,e,r)=>{t.notifications=new Qo(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 ze;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(ze||(ze={}));const Kr=async(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(z.Feed,{method:"submitAnswer"}),i=n({retryAttempts:0});try{return await r.submitAnswer({data:e},{contextValues:i})}catch(o){throw j.ConnectError.from(o)?.code===j.Code.AlreadyExists?new Error(ze.ALREADY_VOTED):new Error(ze.UNKNOWN)}},Yn=(t,e)=>{const{client:r,createRequestOptions:n}=t.createPromiseClient(z.Feed,{method:"submitInplay"}),i=n({retryAttempts:0});return r.submitInplay({data:{eventId:+e}},{contextValues:i})},Ko={pageSize:10},Wo=(t,e,r,n,i)=>{let o=0;const s=G({pageSize:Ko.pageSize,page:0}),a=X({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=Eo(t),c=async()=>{const p=e.get(),g=n?.getStore().get().data?.map(T=>T.slId)||[];if(p&&g?.length){const T=r.get();T&&g.push(T),a.setKey("loading",!0),a.setKey("data",[]);const E=await u({eventId:p,usersIds:g,leaderboardId:""});a.set({data:E.data.map((O,w)=>({...O.attributes,friendsRank:w+1})),hasMore:!1,key:Date.now(),loading:!1}),E.meta&&(o=Math.round(E.meta.count/E.meta.pageSize))}},l=()=>{c()},d=p=>{const g=s.get(),T=p||g.page+1;T<=o&&s.set({...g,page:T})};return J.onMount(a,()=>{const p=e.listen(c),g=n?.listen(c);return()=>{p(),g?.()}}),{$store:a,fetchMore:d,invalidate:l}};class Ho extends Je{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const Wr="sldl",_t="sldl_uid",Xn="sldl_eid",Jn="sldl_e_eid",zo=new Set([_t,Xn,Jn]),Hr=t=>{const e={},r={};for(const[n,i]of t)zo.has(n)?e[n]=i:r[n]=i;return{result:e,remain:r}},Yo=({hash:t,search:e})=>{if(t&&t.includes(Wr)){const r=new URLSearchParams(t.substr(1));return{hash:Hr(r)}}if(e&&e.includes(Wr)){const r=new URLSearchParams(e);return{search:Hr(r)}}return null},zr=Z("deep_link"),le={debug:(...t)=>{zr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{zr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Xo=(t,e)=>{const{hash:r,search:n}=window.location;if(le.debug({hash:r,search:n},"get deep link data from"),r||n){const i=Yo({hash:r,search:n});if(le.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 c=Object.keys(u).length!==0;if(o){let l="";c&&(l=`#${new URLSearchParams(u).toString()}`,le.debug({updatedHash:l},"update hash")),window.history.replaceState(null,"",window.location.pathname+window.location.search+l)}if(s){let l="";c&&(l=`?${new URLSearchParams(u).toString()}`,le.debug({updatedSearch:l},"update search")),window.history.replaceState(null,"",window.location.pathname+l+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},Jo=(t,e,r)=>{const n=new Ho,i=n.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){le.debug(a)}t.deepLink={$store:new Ne(X(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{le.debug(`logged in with inviterId: ${a}`),t.deepLink.$store.setValue("used",!0)},onDeepLinkHandlers:new Set},t.sdk.getInviter=()=>{const{data:a,used:u}=t.deepLink.getDeepLinkData();return u?a?.[_t]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),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")&&le.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{le.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),le.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{le.trace("called handler"),u(a)}catch(c){console.error(c)}};Xo(t.deepLink.$store,s),r()},Zo=Z("bypass");class es extends Xi{$coreStore;deepLink;transport;bypassLogin;constructor(e,r,n){super(),this.$coreStore=e,this.deepLink=n,this.transport=r,this.bypassLogin=ho(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?.[_t];Zo.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 je().clear()};softLogout=()=>{const e=new je;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const r=new je,n=r.getToken(),i=r.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),n)return this.saveUser(n,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(n,s)}return o});if(i&&!n&&!e){const o=r.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,r)=>{this.transport.setAuth(e,r),this.$coreStore.getValues().userToken.setValue(e),new je().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 tt=new je,ts=(t,e,r)=>{t.auth=new es(t.store,t.transport,t.deepLink),t.stores.status.listen(n=>{n===ge.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(n,i)=>{if(!(tt.getSchema()===n&&tt.getExternalToken()===i&&t.transport.getHeader("authorization")))try{await t.auth.login(n,i),tt.setSchema(n),tt.setExternalToken(i)}catch{t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),tt.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),r()},Yr=Z("video_player"),ft={debug:(...t)=>{Yr.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Yr.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},rs=(t,e,r)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=n=>{ft.trace("adding video player controller"),t.videoPlayer.controllers.add(n)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=n=>{ft.trace("removing video player controller"),t.videoPlayer.controllers.delete(n)},t.sdk.controlVideoPlayer=n=>{ft.trace("controlling video player");for(const i of t.videoPlayer.controllers){ft.trace("calling video player controller");try{i(n)}catch(o){console.error(o)}}},r()},ns={[v.QuestionType.FACTOID]:"insight",[v.QuestionType.POLL]:"poll",[v.QuestionType.TRIVIA]:"trivia",[v.QuestionType.PREDICTION]:"prediction",[v.QuestionType.TWEET]:"tweet"},xe=t=>t===v.PromotionType.INGAME_IAB11||t===v.PromotionType.INGAME_IAB21||t===v.PromotionType.NFL_SHOP_OVERLAY||t===v.PromotionType.SHOP_OVERLAY,is=(t,e,r)=>{t.sdk.uiState=X({}),t.ui={enableAppNotification:function(){t.sdk.uiState.setKey("appNotification",!0)},disableAppNotification:function(){t.sdk.uiState.get().app||t.sdk.uiState.setKey("appNotification",!1)},enableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!0)},disableOnboardingNotification:function(){t.sdk.uiState.setKey("onboardingNotification",!1)},enablePolymarket:function(){t.sdk.uiState.setKey("polymarket",!0)},disablePolymarket:function(){t.sdk.uiState.setKey("polymarket",!1)},enableApp:function(){t.sdk.uiState.set({app:!0,appNotification:!0})},disableApp:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),onboardingNotification:!1,appBanner:!1,appSidebar:!1,appNotification:!1,app:!1})},enableExposedPauseAd:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),exposedPauseAd:!0})},disableExposedPauseAd:function(){t.sdk.uiState.set({...t.sdk.uiState.get(),exposedPauseAd:!1})}},t.sdk.uiHandlers={enablePolymarket:t.ui.enablePolymarket,disablePolymarket:t.ui.disablePolymarket},e.onContentActivate&&(t.ui.onContentActivate=e.onContentActivate);const n=i=>{t.ui.onContentActivate&&t.ui.onContentActivate({...i,type:"advertisement"})};t.onQuestionActivate=({questionType:i,...o})=>{if(t.ui.enableAppNotification(),t.ui.onContentActivate){const s=o.type||i&&ns[i]||"question";t.ui.onContentActivate({...o,type:s})}},t.sdk.onMount({name:"ui"},()=>{const i=a=>{if(a.slEventBus?.type==="exposedPauseAd")switch(a.slEventBus.action){case"enabled":t.ui.enableExposedPauseAd();break;case"disabled":t.ui.disableExposedPauseAd();break}if(a.slEventBus?.type==="app")switch(a.slEventBus.action){case"open":t.ui.enableApp();break;case"close":t.ui.disableApp();break}if(a.slEventBus?.type==="poll"){const u=a.slEventBus.action,{hasBanner:c}=a.slEventBus.payload;switch(u){case"onboardingOpen":t.sdk.uiState.set({app:!0});break;case"opened":t.sdk.uiState.set({...t.sdk.uiState.get(),appBanner:c,appSidebar:!0});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),appBanner:!1,appSidebar:!1});break}}if(a.slEventBus?.type==="notification"){const u=a.slEventBus.action;if(a.slEventBus.payload.type===ve.ONBOARDING)switch(u){case"received":t.ui.enableOnboardingNotification();break;case"closed":t.ui.disableOnboardingNotification();break}else switch(u){case"received":t.ui.enableAppNotification();break;case"closed":t.ui.disableAppNotification();break}}if(a.slEventBus?.type==="advertisement"&&e.withAd){const u=a.slEventBus,{hasNotification:c,hasBanner:l,id:d,isViewed:p,type:g}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:g===v.PromotionType.EXTERNAL_AD,promotionBanner:l,promotionNotification:!1,promotionOverlay:xe(g),promotionSidebar:!xe(g)});break;case"received":if(t.sdk.closeFeature(),n({stage:"activate",id:d,hasNotification:c,hasBanner:l,isViewed:p}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:l,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:xe(g),promotionSidebar:!xe(g),promotionExternalAd:g===v.PromotionType.EXTERNAL_AD});break}c?t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionNotification:!0}):t.sdk.uiState.set({onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionBanner:l,promotionOverlay:xe(g),promotionSidebar:!xe(g),promotionExternalAd:g===v.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),n({stage:"deactivate",id:d,hasNotification:c,hasBanner:l,isViewed:p});break}}},o=V.listen(i),s=t.activeFeature.subscribe(a=>{a||t.ui.disableApp()});return()=>{o(),s()}}),r()},os=(t,e,r)=>{const n={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=X(e),t.sdk.withAuth=!1,t.sdk.onMount=({name:s,clear:a},u)=>{if(i.has(s)){const c=o.get(s);c&&c(),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=s=>(t.contextConfig=s,t.stores.enabled.get()==="on"?Promise.resolve({enabled:!0}):(t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(ge.INITIALIZATION),new Promise(a=>{window.requestAnimationFrame(async()=>{try{const u=await t.stores.organizationSettings.getValue();return u?(t.stores.status.setValue(ge.READY),a({enabled:!!u})):(t.stores.status.setValue(ge.FAILED),a({err:"failed"}))}catch(u){return t.stores.enabled.setValue(),t.stores.status.setValue(ge.FAILED),a({err:`${u}`})}})}))),t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(ge.DISABLED),t.stores.slStreamId.setValue(),t.stores.providerStreamId.setValue(),t.sdk.closeFeature(!0),t.storeUnsubscribe(),t.transport.disconnect())},t.sdk.createEventSession=(s,a)=>{a?t.stores.slStreamId.getStore().set({loading:!1,data:s}):t.stores.providerStreamId.setValue(s)},r()},ss=(t,e)=>{const{client:r,queryKey:n}=t.createPromiseClient(ot.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,revalidateInterval:0})},as=(t,{web:e,mobile:r})=>{const{client:n}=t.createPromiseClient($i.LinksClient,{method:"generate"});return n.generate({web:e,mobile:r})},Xr=(t,e)=>{const r=new URLSearchParams(t);for(const[n,i]of Object.entries(e))r.append(n,i);return r.toString()},us=(t,e,r,n)=>{const i=X({});return J.onMount(i,()=>ss(t,[e,r]).subscribe(async({data:a,loading:u})=>{const c=a===void 0&&u===!1?"https://streamlayer.io":a?.url,l=n.get()||"",d=e.get()||"",p=r.get()||"",g={[_t]:l,[Xn]:d,[Jn]:p};if(!u&&c){i.setKey("loading",!0);let T=window.location.search,y=window.location.hash;T&&y||y?T=`?${Xr(T,g)}`:y=`#${Xr("",g)}`;const E=window.location.origin+window.location.pathname+T+y;try{const O=await as(t,{web:E,mobile:c});i.set({data:O.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 $;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})($||($={}));const cs=(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,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:v.QuestionType.UNSET,onboarding:{...i,instantOpen:!n.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),markIstantOpen:()=>{n.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),r.update(o,s=>{s?.data?.onboarding&&(s.data.onboarding.instantOpen=!0)})}}}})},ht=(t,e,r,n,i,o,s,a)=>{try{const u=e.userId.get(),c=e.organizationId.get(),l=e.slStreamId.get();if(!u||!c||!l)return;const d=i.getOnboardingStatus({userId:u,organizationId:c,eventId:l});if(d===$.Completed||a?.skipOnboarding){t.set($.Completed);for(const E of o)E();a?.skipOnboarding&&d!==$.Completed&&(i.saveOnboardingStatus({organizationId:c,userId:u,eventId:l},$.Completed),Yn(s,l));return}const p=e.moderation.getStore().value?.data,g=r.featureSettings.get().inplayGame;if(p===void 0||g===void 0)return;const T=p?.options?.onboardingEnabled,y=g?.titleCard?.optIn;T?y?t.set($.Required):t.set($.Optional):(y?t.set($.Unavailable):t.set($.Disabled),n.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},Jr=(t,e,r,n,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=G($.Unset);a.subscribe(l=>{l!==$.Unset&&(l===$.Optional||l===$.Required?o===!1&&(cs(t,e,n,s),o=!0):t.onboardingProcessed.set(!0),l===$.Completed&&e.activeQuestionId.invalidate(),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==$.Completed&&(u.push(e.userId.listen(l=>{l&&ht(a,e,t,n,s,u,r,i)})),u.push(e.moderation.listen(l=>{l.data&&ht(a,e,t,n,s,u,r,i)})),u.push(t.featureSettings.listen(l=>{l&&ht(a,e,t,n,s,u,r,i)}))),ht(a,e,t,n,s,u,r,i),{$store:a,submitInplay:async()=>{const l=e.slStreamId.get();if(l){await Yn(r,l),a.set($.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:l},$.Completed),V.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const d=e.getCurrentSessionId({prefix:"onboarding"});n.close(d)}}}},ls=(t,e,r,n)=>{const i=X(void 0),o=Wn(n),s=async()=>{const u=t.get(),c=e.get(),l=r?r.getStore().get().data?.map(g=>g.slId):[];if(!l||!u||!c)return;const d={eventId:u,userId:c,leaderboardId:"",usersIds:[...l,c]},p=await o(d);i.set(p.data?.attributes)},a=()=>{s()};return J.onMount(i,()=>{a();const u=t.listen(s),c=r?.listen(s),l=e.listen(s);return()=>{u(),c?.(),l()}}),{$store:i,invalidate:a}},ds=async(t,e,r,n,i)=>{const o=Wn(i),s=t.get(),a=e.get(),u=r?.getStore().get().data?.map(p=>p.slId)||[],c={eventId:s,userId:n,leaderboardId:"",usersIds:[...u,a]};return(await o(c)).data?.attributes?.summary},Zr=new Set([v.QuestionType.POLL,v.QuestionType.PREDICTION,v.QuestionType.TRIVIA]);class ps extends Gn{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,r,n){if(super(e,r),this.background=new qo(n),this.advertisement=this.background.advertisement,this.onQuestionActivate=n.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.onboardingProcessed=G(!n.sdk.withAuth),this.leaderboardId=new te(G(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=n.notifications,this.transport=n.transport,this.closeFeature=(i=!0)=>n.sdk.closeFeature(i),this.openFeature=()=>n.sdk.openFeature(M.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=us(this.transport,this.background.slStreamId,n.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=ls(this.background.slStreamId,this.background.userId,this.friends,this.transport),!n.sdk.options.get().hideFriends){this.friends=new ie(Io(this.background.userId,n.transport),"gamification:friends"),this.openedUser=G(void 0);const i=this.leaderboardList=Wo(this.transport,this.background.slStreamId,this.background.userId,this.friends);this.cancels.add(this.userSummary.$store.listen((o,s)=>{s?.summary&&o?.summary&&i.invalidate()}))}this.connect(),this.skipOnboarding=!!n.sdk.options.get().skipOnboarding,this.onboardingStatus=Jr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding}),n.sdk.options.get().skipOnboarding||(this.onboardingStatus=Jr(this,this.background,n.transport,n.notifications,{skipOnboarding:n.sdk.options.get().skipOnboarding})),this.cancels.add(this.onboardingStatus.$store.listen(this.checkInteractiveFlag)),this.cancels.add(this.background.moderation.getStore().listen(this.checkInteractiveFlag)),this.cancels.add(this.settings.subscribe(this.checkInteractiveFlag)),this.cancels.add(this.onboardingStatus.$store.listen((i,o)=>{(o===void 0||i!==$.Unset)&&this.background.activeQuestionId.invalidate()})),this.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=G(!1),this.cancels.add(n.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{n.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),n.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Ae.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Ae.ALLOWED);else{const e=this.onboardingStatus.$store.get(),r=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,n=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===$.Completed,o=!r||i||n!==!0;this.background.interactiveAllowed.set(o?Ae.ALLOWED:Ae.DISALLOWED)}};connect=()=>{this.onboardingProcessed.subscribe(e=>{e&&this.advertisement&&this.advertisement.connect()}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-prediction-close",async e=>{if(!this.isInteractiveAllowed)return;const r=e.data?.attributes?.question,n=e.data?.attributes?.feedItem;if(!r||!n?.attributes)return;const{status:i,type:o,id:s,answers:a}=r;if(i===v.QuestionStatus.RESOLVED&&o===v.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),c=[...this.feedList.getValues().data||[]],l=c.findIndex(I=>I.id===s),d=c[l];let p=d?.attributes?.attributes?.value?.answerId;const g=gt(s,this.transport),T=g.subscribe(()=>{});await g.fetch();let y=g.get().data;y||(y=await Hn(s,this.transport),g.mutate(y)),T(),window.requestAnimationFrame(()=>{g.invalidate()}),p||(p=y?.answers.find(({youVoted:I})=>I)?.id);const E=a.find(({correct:I})=>I),O=p?a.find(({id:I})=>I===p):void 0,w=!!O?.correct;if(d&&c[l]?.attributes?.attributes.case==="question"){try{c[l].attributes.attributes.value.answerId=p,c[l].attributes.attributes.value.openForVoting=!1,p&&(c[l].attributes.attributes.value.status=w?z.PickHistoryStatus.WON:z.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(c)}if(!O||!E)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:w?15e3:14e3,id:u,emitEvent:!1,data:{questionId:s,questionType:v.QuestionType.PREDICTION,question:{title:w?`Congratulations! You answered correctly! You won ${E.points} pts!`:`Better luck next time! Correct: ${E?.text}!`,votedAnswer:{title:O?.text,points:O?.points},correctAnswerTitle:E?.text,correct:!!w,predictionResult:!0,questionTitle:r?.subject},inApp:{notification:r.notification,appearance:r.appearance,sponsorship:r.sponsorship,adUnit:r?.adUnit,sponsorLogo:r.promotion?.sponsor?.logo}}}),this.userSummary.invalidate()}})),J.onStart(this.feedList.getStore(),()=>{this.cancels.add(this.feedList.subscribe(()=>{}))}),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!==v.QuestionStatus.ACTIVE&&n.attributes.status!==v.QuestionStatus.RESOLVED)&&!(!this.isInteractiveAllowed&&Zr.has(n.attributes.type)&&n?.attributes?.adUnit!==v.AdUnit.STANDART)){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===!1?!1:n.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),V.emit("poll",{action:"received",payload:{isAd:n.attributes?.adUnit==v.AdUnit.UNSET,questionId:n.id,questionType:n.attributes?.type}})),this.feedList.getStore().mutate(r)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,r)=>{if(!this.betPack)return;try{await Kr(this.transport,{questionId:e,answerId:r})}catch(o){if(o.message===ze.ALREADY_VOTED){const s=gt(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const n={...this.betPack.getValues().data?.data},i=n?.[e];i&&(V.emit("poll",{action:"voted",payload:{questionId:e,isAd:i?.adUnit==v.AdUnit.UNSET,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===r?{...o,youVoted:!0}:o),this.betPack.getStore().mutate({data:n,timestamp:Date.now()}))};submitAnswer=async(e,r)=>{const n=gt(e,this.transport),i=n.subscribe(()=>{}),o={...n.get().data||{}},s=()=>{const a=this.feedList.getValues().data;if(!a)return;const u=a.findIndex(d=>d.id===e),c=a[u],l=c?.attributes?.attributes.case==="question"&&c.attributes.attributes.value;if(l){V.emit("poll",{action:"voted",payload:{isAd:c.attributes?.adUnit==v.AdUnit.UNSET,questionId:e,questionType:l.questionType}});const d=n.get().data;if(i(),d){const p=d.answers.find(E=>E.correct===!0),g=d.answers.findIndex(E=>E.id===r),T=d.answers[g],y=d.answers.every(({percentageDecimal:E},O)=>E===o?.answers[O].percentageDecimal);a[u].attributes.attributes.value.answerId=r,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=T?.text||"",p&&(a[u].attributes.attributes.value.status=p.id===r?z.PickHistoryStatus.WON:z.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a]),d.answers[g].correct=p?.id===r,d.answers[g].youVoted=!0,y&&d.answers.forEach(E=>{E.percentageDecimal=0}),p?.id===r&&(d.answers[g].pointsEarned=d.status===v.QuestionStatus.RESOLVED?0:p.points),n.mutate({...d})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Kr(this.transport,{questionId:e,answerId:r}),s()}catch(a){if(a.message===ze.ALREADY_VOTED){this.userSummary.invalidate();const u=n.subscribe(()=>{});n.invalidate(),u()}throw a}};openQuestion=(e,r)=>{if(!e)return()=>{};const n=r?.openedFrom==="bet-pack";this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=r?.attributes?.type,o=r?.attributes?.adUnit===v.AdUnit.STANDART&&!!r?.attributes?.adPromotion?.banner?.imageUrl;if(!i&&!n){const u=(this.feedList.getStore().value?.data||[]).find(c=>c.id===e)?.attributes;i=u?.type,o=u?.adUnit===v.AdUnit.STANDART&&!!u?.adPromotion?.banner?.imageUrl}const s={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return V.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,isAd:r?.attributes?.adUnit==v.AdUnit.UNSET,questionOpenedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom,hasBanner:o}}),this.storage.isQuestionOpened(s,e)||(V.emit("poll",{action:"viewed",payload:{questionId:e,questionType:i,isAd:r?.attributes?.adUnit==v.AdUnit.UNSET,questionOpenedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}}),this.storage.saveQuestionOpened(s,e)),n||this.openFeature(),this.background.openQuestion(e,r?{...r,openedFrom:r?.openedFrom==="bet-pack"?"list":r?.openedFrom}:void 0)};getFeedItem=e=>No(e,this.transport);isOpenedQuestion=e=>!!this.notifications.isViewed(e);closeQuestion=e=>(e&&(this.onQuestionActivate({stage:"deactivate",id:e,isViewed:!!this.notifications.isViewed(this.background.getCurrentSessionId({prefix:"notification",entity:e}))}),V.emit("poll",{action:"closed",payload:{questionId:e}})),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const r=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!r){this.openedUser?.set(r);return}if(r.summaryLoaded){this.openedUser?.set(r);return}const n={...r};try{const i=await ds(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)};openOnboarding=()=>{this.openFeature(),V.emit("poll",{action:"onboardingOpen",payload:{}})};showInApp=e=>{const r=this.onboardingStatus.$store.get(),n=e?.data?.question?.adUnit===v.AdUnit.STANDART;if(e&&e.data&&(n||r&&r!==$.Unset)&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==v.SilenceSetting.ON&&e.data.question.status===v.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Zr.has(e.data.question.type))(this.isInteractiveAllowed||n)&&e.data.question.notification!==void 0&&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},inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship,adUnit:e.data.question?.adUnit,sponsorLogo:e.data.question.promotion?.sponsor?.logo}}});else if(e.data.question.type===v.QuestionType.FACTOID){const i=e.data.question.options?.options.value,o=e.data.question.notification?.useContentTexts===v.NotificationUseContentTexts.ENABLED?e.data.question.subject:e.data.question.notification?.title||"",s=e.data.question.notification?.useContentTexts===v.NotificationUseContentTexts.ENABLED?i.body:e.data.question.notification?.body,a={heading:o,body:s,imageMode:i?.imageMode,image:i?.image,video:{id:i?.video?.id||"",url:i?.video?.url||"",thumbnailUrl:i?.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:a,inApp:{useMediaFromContent:i?.useAsNotification===v.UseAsNotification.ENABLED,notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship,adUnit:e.data.question?.adUnit,sponsorLogo:e.data.question.promotion?.sponsor?.logo,isVideo:i?.mode===v.FactoidMediaMode.VIDEO}}})}else if(e.data.question.type===v.QuestionType.TWEET&&e.data.question.notification!==void 0){const i=e.data.question.options?.options.value,o={image:"",video:""};if(i.tweetMeta?.tweet?.meta?.extendedEntities?.media?.[0]){const a=i.tweetMeta.tweet.meta.extendedEntities.media;if(a){const u=a.find(({type:c})=>c==="photo")||a[0];o.image=u.mediaUrlHttps,u.type==="video"&&(o.video=u.url)}}const s={title:e.data.question.notification?.title,body:e.data.question.notification?.body,image:e.data.question.notification?.image,account:i?.tweetMeta?.account||"",accountVerified:!!i?.tweetMeta?.accountVerified,tweet:i?.tweetMeta?.tweet,tweetId:e.data.question.id,tweetMedia:o};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:s,inApp:{notification:e.data.question.notification,appearance:e.data.question.appearance,sponsorship:e.data.question.sponsorship}}})}}}}const fs={[M.SdkOverlayType.GAMES]:!0};class hs extends Gn{constructor(e,r){super(e,r)}}const ms=(t,e,r)=>t.type===M.SdkOverlayType.GAMES?new ps(t,e,r):new hs(t,e),gs=(t,e,r)=>{t.features=new Map,t.sdk.featuresList=new te(G(new Set),"features-list"),t.activeFeature=new te(G(M.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=n=>t.features.get(n),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=n=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(n)})},t.sdk.closeFeature=(n=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(M.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=me.ORGANIZATION)=>{if(n.type in fs&&!t.features.has(n.type)){const o=ms(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,me.ORGANIZATION)},t.stores.providerStreamId.listen(n=>{n||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const n=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===me.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(me.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{n(me.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},r()},ys=(t,e,r)=>{const{client:n,queryKey:i}=r.createPromiseClient(qr.PolymarketSportsClient,{method:"getMarketWithSeries",params:[t,e]});return r.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(u)try{return(await n.getMarketWithSeries({eventId:a,timeframe:qr.Timeframe.TIMEFRAME_ALL})).event}catch{return}}})},bs=t=>{const e=t.stores.slStreamId.getAtomStore(),r=t.stores.user.getAtomStore();return ys(e,r,t.transport)};class vs extends Qn{marketWithSeries;log;constructor(e){super(),this.log=Z("polymarket"),this.marketWithSeries=bs(e)}connect=()=>{this.log.debug("connect")};disconnect=()=>{this.marketWithSeries.off(),this.log.debug("disconnect")}}const Ts=(t,e,r)=>{t.sdk.polymarket=new vs(t),t.sdk.onMount({name:"polymarket"},()=>(t.sdk.polymarket.connect(),()=>{t.sdk.polymarket.disconnect()})),r()};function wr(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:t.id||null,adId:t.adId||null,sequence:t.sequence||null,apiFramework:t.apiFramework||null,universalAdIds:[],creativeExtensions:[]}}const Ss=["ADCATEGORIES","ADCOUNT","ADPLAYHEAD","ADSERVINGID","ADTYPE","APIFRAMEWORKS","APPBUNDLE","ASSETURI","BLOCKEDADCATEGORIES","BREAKMAXADLENGTH","BREAKMAXADS","BREAKMAXDURATION","BREAKMINADLENGTH","BREAKMINDURATION","BREAKPOSITION","CLICKPOS","CLICKTYPE","CLIENTUA","CONTENTID","CONTENTPLAYHEAD","CONTENTURI","DEVICEIP","DEVICEUA","DOMAIN","EXTENSIONS","GDPRCONSENT","IFA","IFATYPE","INVENTORYSTATE","LATLONG","LIMITADTRACKING","MEDIAMIME","MEDIAPLAYHEAD","OMIDPARTNER","PAGEURL","PLACEMENTTYPE","PLAYERCAPABILITIES","PLAYERSIZE","PLAYERSTATE","PODSEQUENCE","REGULATIONS","SERVERSIDE","SERVERUA","TRANSACTIONID","UNIVERSALADID","VASTVERSIONS","VERIFICATIONVENDORS"];function en(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const n=[],i=ei(t);!e.ERRORCODE||r.isCustomCode||/^[0-9]{3}$/.test(e.ERRORCODE)||(e.ERRORCODE=900),e.CACHEBUSTING=ni(Math.round(1e8*Math.random())),e.TIMESTAMP=new Date().toISOString(),e.RANDOM=e.random=e.CACHEBUSTING;for(const o in e)e[o]=ri(e[o]);for(const o in i){const s=i[o];typeof s=="string"&&n.push(Zn(s,e))}return n}function Zn(t,e){const r=(t=tn(t,e)).match(/[^[\]]+(?=])/g);if(!r)return t;let n=r.filter(i=>Ss.indexOf(i)>-1);return n.length===0?t:(n=n.reduce((i,o)=>(i[o]=-1,i),{}),tn(t,n))}function tn(t,e){let r=t;for(const n in e){const i=e[n];r=r.replace(new RegExp("(?:\\[|%%)(".concat(n,")(?:\\]|%%)"),"g"),i)}return r}function ei(t){return Array.isArray(t)?t.map(e=>e&&e.hasOwnProperty("url")?e.url:e):t}function rn(t){return/^(https?:\/\/|\/\/)/.test(t)}function nn(t,e){for(let r=0;r<e.length;r++)if(ti(e[r],t))return!0;return!1}function ti(t,e){if(t&&e){const r=Object.getOwnPropertyNames(t),n=Object.getOwnPropertyNames(e);return r.length===n.length&&t.id===e.id&&t.url===e.url}return!1}function ri(t){return encodeURIComponent(t).replace(/[!'()*]/g,e=>"%".concat(e.charCodeAt(0).toString(16)))}function ni(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:8;return t.toString().padStart(e,"0")}const Le={track:function(t,e,r){en(t,e,r).forEach(n=>{typeof window<"u"&&window!==null&&(new Image().src=n)})},resolveURLTemplates:en,extractURLsFromTemplates:ei,filterUrlTemplates:function(t){return t.reduce((e,r)=>{const n=r.url||r;return rn(n)?e.validUrls.push(n):e.invalidUrls.push(n),e},{validUrls:[],invalidUrls:[]})},containsTemplateObject:nn,isTemplateObjectEqual:ti,encodeURIComponentRFC3986:ri,replaceUrlMacros:Zn,isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},flatten:function t(e){return e.reduce((r,n)=>r.concat(Array.isArray(n)?t(n):n),[])},joinArrayOfUniqueTemplateObjs:function(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];const r=Array.isArray(t)?t:[],n=Array.isArray(e)?e:[];return r.concat(n).reduce((i,o)=>(nn(o,i)||i.push(o),i),[])},isValidTimeValue:function(t){return Number.isFinite(t)&&t>=-2},addLeadingZeros:ni,isValidUrl:rn,isBrowserEnvironment:function(){return typeof window<"u"},formatMacrosValues:function(t){return typeof t!="object"?t:JSON.stringify(t)}};function on(t){return["true","TRUE","True","1"].includes(t)}function As(t){if(t==null)return-1;if(Le.isNumeric(t))return parseInt(t);const e=t.split(":");if(e.length!==3)return-1;const r=e[2].split(".");let n=parseInt(r[0]);r.length===2&&(n+=parseFloat("0.".concat(r[1])));const i=parseInt(60*e[1]),o=parseInt(60*e[0]*60);return isNaN(o)||isNaN(i)||isNaN(n)||i>3600||n>60?-1:o+i+n}const f={childByName:function(t,e){return Array.from(t.childNodes).find(r=>r.nodeName===e)},childrenByName:function(t,e){return Array.from(t.childNodes).filter(r=>r.nodeName===e)},resolveVastAdTagURI:function(t,e){if(!e)return t;if(t.startsWith("//")){const{protocol:r}=location;return"".concat(r).concat(t)}if(!t.includes("://")){const r=e.slice(0,e.lastIndexOf("/"));return"".concat(r,"/").concat(t)}return t},parseBoolean:on,parseNodeText:function(t){return t&&(t.textContent||t.text||"").trim()},copyNodeAttribute:function(t,e,r){const n=e.getAttribute(t);n&&r.setAttribute(t,n)},parseAttributes:function(t){return Array.from(t.attributes).reduce((e,r)=>(e[r.nodeName]=r.nodeValue,e),{})},parseDuration:As,getStandAloneAds:function(){return(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).filter(t=>!parseInt(t.sequence,10))},getSortedAdPods:function(){return(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).filter(t=>parseInt(t.sequence,10)).sort((t,e)=>t.sequence-e.sequence)},assignAttributes:function(t,e){t&&Array.from(t).forEach(r=>{let{nodeName:n,nodeValue:i}=r;if(n&&i&&e.hasOwnProperty(n)){let o=i;typeof e[n]=="boolean"&&(o=on(o)),e[n]=o}})},mergeWrapperAdData:function(t,e){var r;t.errorURLTemplates=e.errorURLTemplates.concat(t.errorURLTemplates),t.impressionURLTemplates=e.impressionURLTemplates.concat(t.impressionURLTemplates),t.extensions=e.extensions.concat(t.extensions),e.viewableImpression.length>0&&(t.viewableImpression=[...t.viewableImpression,...e.viewableImpression]),t.followAdditionalWrappers=e.followAdditionalWrappers,t.allowMultipleAds=e.allowMultipleAds,t.fallbackOnNoAd=e.fallbackOnNoAd;const n=(e.creatives||[]).filter(a=>a&&a.type==="companion"),i=n.reduce((a,u)=>((u.variations||[]).forEach(c=>{(c.companionClickTrackingURLTemplates||[]).forEach(l=>{Le.containsTemplateObject(l,a)||a.push(l)})}),a),[]);t.creatives=n.concat(t.creatives);const o=e.videoClickTrackingURLTemplates&&e.videoClickTrackingURLTemplates.length,s=e.videoCustomClickURLTemplates&&e.videoCustomClickURLTemplates.length;if(t.creatives.forEach(a=>{if(e.trackingEvents&&e.trackingEvents[a.type])for(const u in e.trackingEvents[a.type]){const c=e.trackingEvents[a.type][u];Array.isArray(a.trackingEvents[u])||(a.trackingEvents[u]=[]),a.trackingEvents[u]=a.trackingEvents[u].concat(c)}a.type==="linear"&&(o&&(a.videoClickTrackingURLTemplates=a.videoClickTrackingURLTemplates.concat(e.videoClickTrackingURLTemplates)),s&&(a.videoCustomClickURLTemplates=a.videoCustomClickURLTemplates.concat(e.videoCustomClickURLTemplates)),!e.videoClickThroughURLTemplate||a.videoClickThroughURLTemplate!==null&&a.videoClickThroughURLTemplate!==void 0||(a.videoClickThroughURLTemplate=e.videoClickThroughURLTemplate)),a.type==="companion"&&i.length&&(a.variations||[]).forEach(u=>{u.companionClickTrackingURLTemplates=Le.joinArrayOfUniqueTemplateObjs(u.companionClickTrackingURLTemplates,i)})}),e.adVerifications&&(t.adVerifications=t.adVerifications.concat(e.adVerifications)),e.blockedAdCategories&&(t.blockedAdCategories=t.blockedAdCategories.concat(e.blockedAdCategories)),(r=e.creatives)!==null&&r!==void 0&&r.length){const a=e.creatives.filter(u=>{var c;return((c=u.icons)===null||c===void 0?void 0:c.length)&&!u.mediaFiles.length});a.length&&(t.creatives=t.creatives.concat(a))}}};function ws(t,e){const r=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=wr(n);return{id:i,adId:o,sequence:s,apiFramework:a,type:"companion",required:null,variations:[]}}(e);return r.required=t.getAttribute("required")||null,r.variations=f.childrenByName(t,"Companion").map(n=>{const i=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:a.id||null,adType:"companionAd",width:a.width||0,height:a.height||0,assetWidth:a.assetWidth||null,assetHeight:a.assetHeight||null,expandedWidth:a.expandedWidth||null,expandedHeight:a.expandedHeight||null,apiFramework:a.apiFramework||null,adSlotId:a.adSlotId||null,pxratio:a.pxratio||"1",renderingMode:a.renderingMode||"default",staticResources:[],htmlResources:[],iframeResources:[],adParameters:null,altText:null,companionClickThroughURLTemplate:null,companionClickTrackingURLTemplates:[],trackingEvents:{}}}(f.parseAttributes(n));i.htmlResources=f.childrenByName(n,"HTMLResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat(c):a},[]),i.iframeResources=f.childrenByName(n,"IFrameResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat(c):a},[]),i.staticResources=f.childrenByName(n,"StaticResource").reduce((a,u)=>{const c=f.parseNodeText(u);return c?a.concat({url:c,creativeType:u.getAttribute("creativeType")||null}):a},[]),i.altText=f.parseNodeText(f.childByName(n,"AltText"))||null;const o=f.childByName(n,"TrackingEvents");o&&f.childrenByName(o,"Tracking").forEach(a=>{const u=a.getAttribute("event"),c=f.parseNodeText(a);u&&c&&(Array.isArray(i.trackingEvents[u])||(i.trackingEvents[u]=[]),i.trackingEvents[u].push(c))}),i.companionClickTrackingURLTemplates=f.childrenByName(n,"CompanionClickTracking").map(a=>({id:a.getAttribute("id")||null,url:f.parseNodeText(a)})),i.companionClickThroughURLTemplate=f.parseNodeText(f.childByName(n,"CompanionClickThrough"))||null;const s=f.childByName(n,"AdParameters");return s&&(i.adParameters={value:f.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),i}),r}function Es(t,e){let r;const n=function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:c,adId:l,sequence:d,apiFramework:p}=wr(u);return{id:c,adId:l,sequence:d,apiFramework:p,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}}(e);n.duration=f.parseDuration(f.parseNodeText(f.childByName(t,"Duration")));const i=t.getAttribute("skipoffset");if(i==null)n.skipDelay=null;else if(i.charAt(i.length-1)==="%"&&n.duration!==-1){const u=parseInt(i,10);n.skipDelay=n.duration*(u/100)}else n.skipDelay=f.parseDuration(i);const o=f.childByName(t,"VideoClicks");if(o){const u=f.childByName(o,"ClickThrough");n.videoClickThroughURLTemplate=u?{id:u.getAttribute("id")||null,url:f.parseNodeText(u)}:null,f.childrenByName(o,"ClickTracking").forEach(c=>{n.videoClickTrackingURLTemplates.push({id:c.getAttribute("id")||null,url:f.parseNodeText(c)})}),f.childrenByName(o,"CustomClick").forEach(c=>{n.videoCustomClickURLTemplates.push({id:c.getAttribute("id")||null,url:f.parseNodeText(c)})})}const s=f.childByName(t,"AdParameters");s&&(n.adParameters={value:f.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),f.childrenByName(t,"TrackingEvents").forEach(u=>{f.childrenByName(u,"Tracking").forEach(c=>{let l=c.getAttribute("event");const d=f.parseNodeText(c);if(l&&d){if(l==="progress"){if(r=c.getAttribute("offset"),!r)return;l=r.charAt(r.length-1)==="%"?"progress-".concat(r):"progress-".concat(f.parseDuration(r))}Array.isArray(n.trackingEvents[l])||(n.trackingEvents[l]=[]),n.trackingEvents[l].push(d)}})}),f.childrenByName(t,"MediaFiles").forEach(u=>{f.childrenByName(u,"MediaFile").forEach(g=>{n.mediaFiles.push(function(T){const y={id:null,fileURL:null,fileSize:0,deliveryType:"progressive",mimeType:null,mediaType:null,codec:null,bitrate:0,minBitrate:0,maxBitrate:0,width:0,height:0,apiFramework:null,scalable:null,maintainAspectRatio:null};y.id=T.getAttribute("id"),y.fileURL=f.parseNodeText(T),y.deliveryType=T.getAttribute("delivery"),y.codec=T.getAttribute("codec"),y.mimeType=T.getAttribute("type"),y.mediaType=T.getAttribute("mediaType")||"2D",y.apiFramework=T.getAttribute("apiFramework"),y.fileSize=parseInt(T.getAttribute("fileSize")||0),y.bitrate=parseInt(T.getAttribute("bitrate")||0),y.minBitrate=parseInt(T.getAttribute("minBitrate")||0),y.maxBitrate=parseInt(T.getAttribute("maxBitrate")||0),y.width=parseInt(T.getAttribute("width")||0),y.height=parseInt(T.getAttribute("height")||0);const E=T.getAttribute("scalable");E&&typeof E=="string"&&(y.scalable=f.parseBoolean(E));const O=T.getAttribute("maintainAspectRatio");return O&&typeof O=="string"&&(y.maintainAspectRatio=f.parseBoolean(O)),y}(g))});const c=f.childByName(u,"InteractiveCreativeFile");c&&(n.interactiveCreativeFile=function(g){const T=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:y.type||null,apiFramework:y.apiFramework||null,variableDuration:f.parseBoolean(y.variableDuration),fileURL:null}}(f.parseAttributes(g));return T.fileURL=f.parseNodeText(g),T}(c));const l=f.childByName(u,"ClosedCaptionFiles");l&&f.childrenByName(l,"ClosedCaptionFile").forEach(g=>{const T=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:y.type||null,language:y.language||null,fileURL:null}}(f.parseAttributes(g));T.fileURL=f.parseNodeText(g),n.closedCaptionFiles.push(T)});const d=f.childByName(u,"Mezzanine"),p=function(g,T){const y={};let E=!1;return T.forEach(O=>{g&&g.getAttribute(O)?y[O]=g.getAttribute(O):E=!0}),E?null:y}(d,["delivery","type","width","height"]);if(p){const g={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};g.id=d.getAttribute("id"),g.fileURL=f.parseNodeText(d),g.delivery=p.delivery,g.codec=d.getAttribute("codec"),g.type=p.type,g.width=parseInt(p.width,10),g.height=parseInt(p.height,10),g.fileSize=parseInt(d.getAttribute("fileSize"),10),g.mediaType=d.getAttribute("mediaType")||"2D",n.mezzanine=g}});const a=f.childByName(t,"Icons");return a&&f.childrenByName(a,"Icon").forEach(u=>{n.icons.push(function(c){const l={program:null,height:0,width:0,xPosition:0,yPosition:0,apiFramework:null,offset:null,duration:0,type:null,staticResource:null,htmlResource:null,iframeResource:null,pxratio:"1",iconClickThroughURLTemplate:null,iconClickTrackingURLTemplates:[],iconViewTrackingURLTemplate:null,iconClickFallbackImages:[],altText:null,hoverText:null};l.program=c.getAttribute("program"),l.height=parseInt(c.getAttribute("height")||0),l.width=parseInt(c.getAttribute("width")||0),l.xPosition=function(p){return["left","right"].indexOf(p)!==-1?p:parseInt(p||0)}(c.getAttribute("xPosition")),l.yPosition=function(p){return["top","bottom"].indexOf(p)!==-1?p:parseInt(p||0)}(c.getAttribute("yPosition")),l.apiFramework=c.getAttribute("apiFramework"),l.pxratio=c.getAttribute("pxratio")||"1",l.offset=f.parseDuration(c.getAttribute("offset")),l.duration=f.parseDuration(c.getAttribute("duration")),l.altText=c.getAttribute("altText"),l.hoverText=c.getAttribute("hoverText"),f.childrenByName(c,"HTMLResource").forEach(p=>{l.type=p.getAttribute("creativeType")||"text/html",l.htmlResource=f.parseNodeText(p)}),f.childrenByName(c,"IFrameResource").forEach(p=>{l.type=p.getAttribute("creativeType")||0,l.iframeResource=f.parseNodeText(p)}),f.childrenByName(c,"StaticResource").forEach(p=>{l.type=p.getAttribute("creativeType")||0,l.staticResource=f.parseNodeText(p)});const d=f.childByName(c,"IconClicks");if(d){l.iconClickThroughURLTemplate=f.parseNodeText(f.childByName(d,"IconClickThrough")),f.childrenByName(d,"IconClickTracking").forEach(g=>{l.iconClickTrackingURLTemplates.push({id:g.getAttribute("id")||null,url:f.parseNodeText(g)})});const p=f.childByName(d,"IconClickFallbackImages");p&&f.childrenByName(p,"IconClickFallbackImage").forEach(g=>{l.iconClickFallbackImages.push({url:f.parseNodeText(g)||null,width:g.getAttribute("width")||null,height:g.getAttribute("height")||null})})}return l.iconViewTrackingURLTemplate=f.parseNodeText(f.childByName(c,"IconViewTracking")),l}(u))}),n}function Is(t,e){const r=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=wr(n);return{id:i,adId:o,sequence:s,apiFramework:a,type:"nonlinear",variations:[],trackingEvents:{}}}(e);return f.childrenByName(t,"TrackingEvents").forEach(n=>{let i,o;f.childrenByName(n,"Tracking").forEach(s=>{i=s.getAttribute("event"),o=f.parseNodeText(s),i&&o&&(Array.isArray(r.trackingEvents[i])||(r.trackingEvents[i]=[]),r.trackingEvents[i].push(o))})}),f.childrenByName(t,"NonLinear").forEach(n=>{const i={id:null,width:0,height:0,expandedWidth:0,expandedHeight:0,scalable:!0,maintainAspectRatio:!0,minSuggestedDuration:0,apiFramework:"static",adType:"nonLinearAd",type:null,staticResource:null,htmlResource:null,iframeResource:null,nonlinearClickThroughURLTemplate:null,nonlinearClickTrackingURLTemplates:[],adParameters:null};i.id=n.getAttribute("id")||null,i.width=n.getAttribute("width"),i.height=n.getAttribute("height"),i.expandedWidth=n.getAttribute("expandedWidth"),i.expandedHeight=n.getAttribute("expandedHeight"),i.scalable=f.parseBoolean(n.getAttribute("scalable")),i.maintainAspectRatio=f.parseBoolean(n.getAttribute("maintainAspectRatio")),i.minSuggestedDuration=f.parseDuration(n.getAttribute("minSuggestedDuration")),i.apiFramework=n.getAttribute("apiFramework"),f.childrenByName(n,"HTMLResource").forEach(s=>{i.type=s.getAttribute("creativeType")||"text/html",i.htmlResource=f.parseNodeText(s)}),f.childrenByName(n,"IFrameResource").forEach(s=>{i.type=s.getAttribute("creativeType")||0,i.iframeResource=f.parseNodeText(s)}),f.childrenByName(n,"StaticResource").forEach(s=>{i.type=s.getAttribute("creativeType")||0,i.staticResource=f.parseNodeText(s)});const o=f.childByName(n,"AdParameters");o&&(i.adParameters={value:f.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),i.nonlinearClickThroughURLTemplate=f.parseNodeText(f.childByName(n,"NonLinearClickThrough")),f.childrenByName(n,"NonLinearClickTracking").forEach(s=>{i.nonlinearClickTrackingURLTemplates.push({id:s.getAttribute("id")||null,url:f.parseNodeText(s)})}),r.variations.push(i)}),r}function sn(t){const e=[];return t.forEach(r=>{const n=ii(r);n&&e.push(n)}),e}function ii(t){if(t.nodeName==="#comment")return null;const e={name:null,value:null,attributes:{},children:[]},r=t.attributes,n=t.childNodes;if(e.name=t.nodeName,t.attributes){for(const o in r)if(r.hasOwnProperty(o)){const s=r[o];s.nodeName&&s.nodeValue&&(e.attributes[s.nodeName]=s.nodeValue)}}for(const o in n)if(n.hasOwnProperty(o)){const s=ii(n[o]);s&&e.children.push(s)}if(e.children.length===0||e.children.length===1&&["#cdata-section","#text"].indexOf(e.children[0].name)>=0){const o=f.parseNodeText(t);o!==""&&(e.value=o),e.children=[]}return(i=e).value===null&&Object.keys(i.attributes).length===0&&i.children.length===0?null:e;var i}function Os(t){return t.getAttribute("AdID")||t.getAttribute("adID")||t.getAttribute("adId")||null}const yt={Wrapper:{subElements:["VASTAdTagURI","Impression"]},BlockedAdCategories:{attributes:["authority"]},InLine:{subElements:["AdSystem","AdTitle","Impression","AdServingId","Creatives"]},Category:{attributes:["authority"]},Pricing:{attributes:["model","currency"]},Verification:{oneOfinLineResources:["JavaScriptResource","ExecutableResource"],attributes:["vendor"]},UniversalAdId:{attributes:["idRegistry"]},JavaScriptResource:{attributes:["apiFramework","browserOptional"]},ExecutableResource:{attributes:["apiFramework","type"]},Tracking:{attributes:["event"]},Creatives:{subElements:["Creative"]},Creative:{subElements:["UniversalAdId"]},Linear:{subElements:["MediaFiles","Duration"]},MediaFiles:{subElements:["MediaFile"]},MediaFile:{attributes:["delivery","type","width","height"]},Mezzanine:{attributes:["delivery","type","width","height"]},NonLinear:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},Companion:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"],attributes:["width","height"]},StaticResource:{attributes:["creativeType"]},Icons:{subElements:["Icon"]},Icon:{oneOfinLineResources:["StaticResource","IFrameResource","HTMLResource"]}};function an(t,e){if(!yt[t.nodeName]||!yt[t.nodeName].attributes)return;const r=yt[t.nodeName].attributes.filter(n=>!t.getAttribute(n));r.length>0&&it({name:t.nodeName,parentName:t.parentNode.nodeName,attributes:r},e)}function un(t,e,r){const n=yt[t.nodeName],i=!r&&t.nodeName!=="Wrapper";if(!(!n||i)){if(n.subElements){const o=n.subElements.filter(s=>!f.childByName(t,s));o.length>0&&it({name:t.nodeName,parentName:t.parentNode.nodeName,subElements:o},e)}!r||!n.oneOfinLineResources||n.oneOfinLineResources.some(o=>f.childByName(t,o))||it({name:t.nodeName,parentName:t.parentNode.nodeName,oneOfResources:n.oneOfinLineResources},e)}}function cn(t){return t.children&&t.children.length!==0}function it(t,e){let{name:r,parentName:n,attributes:i,subElements:o,oneOfResources:s}=t,a="Element '".concat(r,"'");a+=i?" missing required attribute(s) '".concat(i.join(", "),"' "):o?" missing required sub element(s) '".concat(o.join(", "),"' "):s?" must provide one of the following '".concat(s.join(", "),"' "):" is empty",e("VAST-warning",{message:a,parentElement:n,specVersion:4.1})}const ks={verifyRequiredValues:function t(e,r,n){if(e&&e.nodeName)if(e.nodeName==="InLine"&&(n=!0),an(e,r),cn(e)){un(e,r,n);for(let i=0;i<e.children.length;i++)t(e.children[i],r,n)}else f.parseNodeText(e).length===0&&it({name:e.nodeName,parentName:e.parentNode.nodeName},r)},hasSubElements:cn,emitMissingValueWarning:it,verifyRequiredAttributes:an,verifyRequiredSubElements:un};function Ns(t,e){let{allowMultipleAds:r,followAdditionalWrappers:n}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=Array.from(t.childNodes).filter(o=>{const s=o.nodeName.toLowerCase();return s==="inline"||n!==!1&&s==="wrapper"});for(const o of i){if(f.copyNodeAttribute("id",t,o),f.copyNodeAttribute("sequence",t,o),f.copyNodeAttribute("adType",t,o),o.nodeName==="Wrapper")return{ad:Ps(o,e),type:"WRAPPER"};if(o.nodeName==="InLine")return{ad:Cs(o,e,{allowMultipleAds:r}),type:"INLINE"};const s=o.nodeName.toLowerCase();e("VAST-warning",{message:"<".concat(o.nodeName,s==="inline"?"> must be written <InLine>":"> must be written <Wrapper>"),wrongNode:o})}}function Cs(t,e){let{allowMultipleAds:r}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return r===!1&&t.getAttribute("sequence")?null:oi(t,e)}function oi(t,e){let r=[];e&&ks.verifyRequiredValues(t,e);const n=Array.from(t.childNodes),i=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{id:o.id||null,sequence:o.sequence||null,adType:o.adType||null,adServingId:null,categories:[],expires:null,viewableImpression:[],system:null,title:null,description:null,advertiser:null,pricing:null,survey:null,errorURLTemplates:[],impressionURLTemplates:[],creatives:[],extensions:[],adVerifications:[],blockedAdCategories:[],followAdditionalWrappers:!0,allowMultipleAds:!1,fallbackOnNoAd:null}}(f.parseAttributes(t));return n.forEach(o=>{switch(o.nodeName){case"Error":i.errorURLTemplates.push(f.parseNodeText(o));break;case"Impression":i.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:f.parseNodeText(o)});break;case"Creatives":i.creatives=function(s){const a=[];return s.forEach(u=>{const c={id:u.getAttribute("id")||null,adId:Os(u),sequence:u.getAttribute("sequence")||null,apiFramework:u.getAttribute("apiFramework")||null},l=[];let d;f.childrenByName(u,"UniversalAdId").forEach(g=>{const T={idRegistry:g.getAttribute("idRegistry")||"unknown",value:f.parseNodeText(g)};l.push(T)});const p=f.childByName(u,"CreativeExtensions");p&&(d=sn(f.childrenByName(p,"CreativeExtension")));for(const g in u.childNodes){const T=u.childNodes[g];let y;switch(T.nodeName){case"Linear":y=Es(T,c);break;case"NonLinearAds":y=Is(T,c);break;case"CompanionAds":y=ws(T,c)}y&&(l&&(y.universalAdIds=l),d&&(y.creativeExtensions=d),a.push(y))}}),a}(f.childrenByName(o,"Creative"));break;case"Extensions":{const s=f.childrenByName(o,"Extension");i.extensions=sn(s),i.adVerifications.length||(r=function(a){let u=null,c=[];return a.some(l=>u=f.childByName(l,"AdVerifications")),u&&(c=ln(f.childrenByName(u,"Verification"))),c}(s));break}case"AdVerifications":i.adVerifications=ln(f.childrenByName(o,"Verification"));break;case"AdSystem":i.system={value:f.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":i.title=f.parseNodeText(o);break;case"AdServingId":i.adServingId=f.parseNodeText(o);break;case"Category":i.categories.push({authority:o.getAttribute("authority")||null,value:f.parseNodeText(o)});break;case"Expires":i.expires=parseInt(f.parseNodeText(o),10);break;case"ViewableImpression":i.viewableImpression.push(function(s){const a=(u,c)=>{const l=f.parseNodeText(c);return l&&u.push(l),u};return{id:s.getAttribute("id")||null,viewable:f.childrenByName(s,"Viewable").reduce(a,[]),notViewable:f.childrenByName(s,"NotViewable").reduce(a,[]),viewUndetermined:f.childrenByName(s,"ViewUndetermined").reduce(a,[])}}(o));break;case"Description":i.description=f.parseNodeText(o);break;case"Advertiser":i.advertiser={id:o.getAttribute("id")||null,value:f.parseNodeText(o)};break;case"Pricing":i.pricing={value:f.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":i.survey={value:f.parseNodeText(o),type:o.getAttribute("type")||null};break;case"BlockedAdCategories":i.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:f.parseNodeText(o)})}}),r.length&&(i.adVerifications=i.adVerifications.concat(r)),i}function Ps(t,e){const r=oi(t,e),n=t.getAttribute("followAdditionalWrappers"),i=t.getAttribute("allowMultipleAds"),o=t.getAttribute("fallbackOnNoAd");r.followAdditionalWrappers=!n||f.parseBoolean(n),r.allowMultipleAds=!!i&&f.parseBoolean(i),r.fallbackOnNoAd=o?f.parseBoolean(o):null;let s=f.childByName(t,"VASTAdTagURI");if(s?r.nextWrapperURL=f.parseNodeText(s):(s=f.childByName(t,"VASTAdTagURL"),s&&(r.nextWrapperURL=f.parseNodeText(f.childByName(s,"URL")))),r.creatives.forEach(a=>{if(["linear","nonlinear"].includes(a.type)){if(a.trackingEvents){r.trackingEvents||(r.trackingEvents={}),r.trackingEvents[a.type]||(r.trackingEvents[a.type]={});for(const u in a.trackingEvents){const c=a.trackingEvents[u];Array.isArray(r.trackingEvents[a.type][u])||(r.trackingEvents[a.type][u]=[]),c.forEach(l=>{r.trackingEvents[a.type][u].push(l)})}}a.videoClickTrackingURLTemplates&&(Array.isArray(r.videoClickTrackingURLTemplates)||(r.videoClickTrackingURLTemplates=[]),a.videoClickTrackingURLTemplates.forEach(u=>{r.videoClickTrackingURLTemplates.push(u)})),a.videoClickThroughURLTemplate&&(r.videoClickThroughURLTemplate=a.videoClickThroughURLTemplate),a.videoCustomClickURLTemplates&&(Array.isArray(r.videoCustomClickURLTemplates)||(r.videoCustomClickURLTemplates=[]),a.videoCustomClickURLTemplates.forEach(u=>{r.videoCustomClickURLTemplates.push(u)}))}}),r.nextWrapperURL)return r}function ln(t){const e=[];return t.forEach(r=>{const n={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(r.childNodes);f.assignAttributes(r.attributes,n),i.forEach(s=>{let{nodeName:a,textContent:u,attributes:c}=s;switch(a){case"JavaScriptResource":case"ExecutableResource":n.resource=u.trim(),f.assignAttributes(c,n);break;case"VerificationParameters":n.parameters=u.trim()}});const o=f.childByName(r,"TrackingEvents");o&&f.childrenByName(o,"Tracking").forEach(s=>{const a=s.getAttribute("event"),u=f.parseNodeText(s);a&&u&&(Array.isArray(n.trackingEvents[a])||(n.trackingEvents[a]=[]),n.trackingEvents[a].push(u))}),e.push(n)}),e}class Ls{constructor(){this._handlers=[]}on(e,r){if(typeof r!="function")throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof r));if(!e)throw new TypeError("The event argument must be of type String. Received type ".concat(typeof e));return this._handlers.push({event:e,handler:r}),this}once(e,r){return this.on(e,function(n,i,o){const s={fired:!1,wrapFn:void 0};function a(){s.fired||(n.off(i,s.wrapFn),s.fired=!0,o.bind(n)(...arguments))}return s.wrapFn=a,a}(this,e,r))}off(e,r){return this._handlers=this._handlers.filter(n=>n.event!==e||n.handler!==r),this}emit(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];let o=!1;return this._handlers.forEach(s=>{s.event==="*"&&(o=!0,s.handler(e,...n)),s.event===e&&(o=!0,s.handler(...n))}),o}removeAllListeners(e){return e?(this._handlers=this._handlers.filter(r=>r.event!==e),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter(r=>r.event===e).length}listeners(e){return this._handlers.reduce((r,n)=>(n.event===e&&r.push(n.handler),r),[])}eventNames(){return this._handlers.map(e=>e.event)}}let dn=0,cr=0;const si=(t,e)=>{!t||!e||t<=0||e<=0||(cr=(cr*dn+8*t/e)/++dn)},Rs={ERRORCODE:900,extensions:[]},pn="VAST response version not supported";class _s extends Ls{constructor(){let{fetcher:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.maxWrapperDepth=null,this.rootErrorURLTemplates=[],this.errorURLTemplates=[],this.remainingAds=[],this.parsingOptions={},this.fetcher=e||null,this.keepFailedAdPod=!1}trackVastError(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;o<n;o++)i[o-2]=arguments[o];this.emit("VAST-error",Object.assign({},Rs,r,...i)),Le.track(e,r)}getErrorURLTemplates(){return this.rootErrorURLTemplates.concat(this.errorURLTemplates)}getEstimatedBitrate(){return cr}initParsingStatus(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.maxWrapperDepth=e.wrapperLimit||10,this.parsingOptions={allowMultipleAds:e.allowMultipleAds},this.keepFailedAdPod=e.keepFailedAdPod||!1,this.rootURL="",this.resetParsingStatus(),si(e.byteLength,e.requestDuration)}resetParsingStatus(){this.errorURLTemplates=[],this.rootErrorURLTemplates=[],this.vastVersion=null}getRemainingAds(e){if(this.remainingAds.length===0)return Promise.reject(new Error("No more ads are available for the given VAST"));const r=e?this.remainingAds:[this.remainingAds.shift()];return this.errorURLTemplates=[],this.resolveAds(r,{wrapperDepth:0,url:this.rootURL}).then(n=>this.buildVASTResponse(n))}parseVAST(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.initParsingStatus(r),r.isRootVAST=!0,this.parse(e,r).then(n=>this.buildVASTResponse(n))}buildVASTResponse(e){const r=function(n){let{ads:i,errorURLTemplates:o,version:s}=n;return{ads:i||[],errorURLTemplates:o||[],version:s||null}}({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(r),r}parseVastXml(e,r){let{isRootVAST:n=!1,url:i=null,wrapperDepth:o=0,allowMultipleAds:s,followAdditionalWrappers:a}=r;if(!e||!e.documentElement||e.documentElement.nodeName!=="VAST"){var u;this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:o});const p=(e==null||(u=e.documentElement)===null||u===void 0?void 0:u.nodeName)==="VideoAdServingTemplate";throw new Error(p?pn:"Invalid VAST XMLDocument")}const c=[],l=e.documentElement.childNodes,d=e.documentElement.getAttribute("version");n&&d&&(this.vastVersion=d);for(const p in l){const g=l[p];if(g.nodeName==="Error"){const T=f.parseNodeText(g);n?this.rootErrorURLTemplates.push(T):this.errorURLTemplates.push(T)}else if(g.nodeName==="Ad"){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(s===!1&&c.length>1)break;const T=Ns(g,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:a});T.ad?(c.push(T.ad),this.emit("VAST-ad-parsed",{type:T.type,url:i,wrapperDepth:o,adIndex:c.length-1,vastVersion:d})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}parse(e){let{url:r=null,resolveAll:n=!0,wrapperSequence:i=null,previousUrl:o=null,wrapperDepth:s=0,isRootVAST:a=!1,followAdditionalWrappers:u,allowMultipleAds:c}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=[];this.vastVersion&&parseFloat(this.vastVersion)<3&&a&&(c=!0);try{l=this.parseVastXml(e,{isRootVAST:a,url:r,wrapperDepth:s,allowMultipleAds:c,followAdditionalWrappers:u})}catch(d){return Promise.reject(d)}if(l.length===1&&i!=null&&(l[0].sequence=i),n===!1){const d=f.getSortedAdPods(l),p=f.getStandAloneAds(l);d.length?l=d:p.length&&(l=[p.shift()]),this.remainingAds=p}return this.resolveAds(l,{wrapperDepth:s,previousUrl:o,url:r})}resolveAds(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],{wrapperDepth:r,previousUrl:n,url:i}=arguments.length>1?arguments[1]:void 0;const o=[];return n=i,e.forEach(s=>{const a=this.resolveWrappers(s,r,n);o.push(a)}),Promise.all(o).then(s=>Le.flatten(s))}resolveWrappers(e,r,n){const i={...e};return new Promise(o=>{var s;if(r++,!i.nextWrapperURL)return delete i.nextWrapperURL,o(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,o(i);if(r>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,o(i);i.nextWrapperURL=f.resolveVastAdTagURI(i.nextWrapperURL,n);const a=(s=this.parsingOptions.allowMultipleAds)!==null&&s!==void 0?s:i.allowMultipleAds,u=i.sequence;this.fetcher.fetchVAST({url:i.nextWrapperURL,emitter:this.emit.bind(this),maxWrapperDepth:this.maxWrapperDepth}).then(c=>this.parse(c,{url:i.nextWrapperURL,previousUrl:n,wrapperSequence:u,wrapperDepth:r,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:a}).then(l=>{if(delete i.nextWrapperURL,l.length===0)return i.creatives=[],o(i);l.forEach(d=>{d&&f.mergeWrapperAdData(d,i)}),o(l)})).catch(c=>{i.errorCode=c.message===pn?102:301,i.errorMessage=c.message,o(i)})})}completeWrapperResolving(e){if(e.ads.length===0)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let r=e.ads.length-1;r>=0;r--){const n=e.ads[r],i=!n.creatives.some(o=>{var s,a;return((s=o.mediaFiles)===null||s===void 0?void 0:s.length)>0||((a=o.variations)===null||a===void 0?void 0:a.length)>0});!n.errorCode&&!i||n.VASTAdTagURI||(this.trackVastError(n.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:n.errorCode||303},{ERRORMESSAGE:n.errorMessage||""},{extensions:n.extensions},{system:n.system}),this.keepFailedAdPod&&n.sequence?n.hasFailed=!0:e.ads.splice(r,1))}}}let fe=null;const Ds={data:{},length:0,getItem(t){return this.data[t]},setItem(t,e){this.data[t]=e,this.length=Object.keys(this.data).length},removeItem(t){delete this.data[t],this.length=Object.keys(this.data).length},clear(){this.data={},this.length=0}};class Fs{constructor(){this.storage=this.initStorage()}initStorage(){if(fe)return fe;try{fe=typeof window<"u"&&window!==null?window.localStorage||window.sessionStorage:null}catch{fe=null}return fe&&!this.isStorageDisabled(fe)||(fe=Ds,fe.clear()),fe}isStorageDisabled(e){const r="__VASTStorage__";try{if(e.setItem(r,r),e.getItem(r)!==r)return e.removeItem(r),!0}catch{return!0}return e.removeItem(r),!1}getItem(e){return this.storage.getItem(e)}setItem(e,r){return this.storage.setItem(e,r)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const lr=12e4,Us={get:async function(t,e){try{const r=new AbortController,n=setTimeout(()=>{throw r.abort(),new Error("URLHandler: Request timed out after ".concat(e.timeout||lr," ms (408)"))},e.timeout||lr),i=await fetch(t,{...e,signal:r.signal,credentials:e.withCredentials?"include":"omit"}).finally(()=>{clearTimeout(n)}),o=function(s){return Le.isBrowserEnvironment()&&window.location.protocol==="https:"&&s.url.includes("http://")?"URLHandler: Cannot go from HTTPS to HTTP.":s.status===200&&s.ok?null:"URLHandler: ".concat(s.statusText," (").concat(s.status,")")}(i);return o?{error:new Error(o),statusCode:i.status}:async function(s){const a=await s.text();let u;return u=Le.isBrowserEnvironment()?new DOMParser:new(await Promise.resolve().then(()=>require("../index-a0VyCTSb.cjs")).then(c=>c.index)).DOMParser,{xml:u.parseFromString(a,"text/xml"),details:{byteLength:a.length,statusCode:s.status,rawXml:a}}}(i)}catch(r){return{error:r,statusCode:r.name==="AbortError"?408:null}}}};class Vs{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||Us,this.fetchingOptions={...e.fetchOptions,timeout:e.timeout||lr,withCredentials:!!e.withCredentials}}addURLTemplateFilter(e){typeof e=="function"&&this.URLTemplateFilters.push(e)}removeLastURLTemplateFilter(){this.URLTemplateFilters.pop()}countURLTemplateFilters(){return this.URLTemplateFilters.length}clearURLTemplateFilters(){this.URLTemplateFilters=[]}async fetchVAST(e){var r;let{url:n,maxWrapperDepth:i,emitter:o,wrapperDepth:s=0,previousUrl:a=null,wrapperAd:u=null}=e;const c=Date.now();this.URLTemplateFilters.forEach(p=>{n=p(n)}),o("VAST-resolving",{url:n,previousUrl:a,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:u});const l=await this.urlHandler.get(n,this.fetchingOptions),d=Math.round(Date.now()-c);if(o("VAST-resolved",{url:n,previousUrl:a,wrapperDepth:s,error:l?.error||null,duration:d,statusCode:l?.statusCode||null,...l?.details}),si(l==null||(r=l.details)===null||r===void 0?void 0:r.byteLength,d),l.error)throw new Error(l.error);return l.xml}}class xs{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new Fs;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=r,this.fetcher=new Vs,this.vastParser=new _s({fetcher:this.fetcher}),this.storage=n,this.lastSuccessfulAd===void 0&&(this.lastSuccessfulAd=0),this.totalCalls===void 0&&(this.totalCalls=0),this.totalCallsTimeout===void 0&&(this.totalCallsTimeout=0)}addURLTemplateFilter(e){this.fetcher.addURLTemplateFilter(e)}removeLastURLTemplateFilter(){this.fetcher.removeLastURLTemplateFilter()}countURLTemplateFilters(){return this.fetcher.countURLTemplateFilters()}clearURLTemplateFilters(){this.fetcher.clearURLTemplateFilters()}getParser(){return this.vastParser}get lastSuccessfulAd(){return this.storage.getItem("vast-client-last-successful-ad")}set lastSuccessfulAd(e){this.storage.setItem("vast-client-last-successful-ad",e)}get totalCalls(){return this.storage.getItem("vast-client-total-calls")}set totalCalls(e){this.storage.setItem("vast-client-total-calls",e)}get totalCallsTimeout(){return this.storage.getItem("vast-client-total-calls-timeout")}set totalCallsTimeout(e){this.storage.setItem("vast-client-total-calls-timeout",e)}hasRemainingAds(){return this.vastParser.remainingAds.length>0}getNextAds(e){return this.vastParser.getRemainingAds(e)}parseVAST(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.fetcher.setOptions(r),this.vastParser.parseVAST(e,r)}get(e){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=Date.now();return r.hasOwnProperty("resolveAll")||(r.resolveAll=!1),this.totalCallsTimeout<n?(this.totalCalls=1,this.totalCallsTimeout=n+36e5):this.totalCalls++,new Promise((i,o)=>{if(this.cappingFreeLunch>=this.totalCalls)return o(new Error("VAST call canceled – FreeLunch capping not reached yet ".concat(this.totalCalls,"/").concat(this.cappingFreeLunch)));const s=n-this.lastSuccessfulAd;if(s<0)this.lastSuccessfulAd=0;else if(s<this.cappingMinimumTimeInterval)return o(new Error("VAST call canceled – (".concat(this.cappingMinimumTimeInterval,")ms minimum interval reached")));this.vastParser.initParsingStatus(r),this.fetcher.setOptions(r),this.vastParser.rootURL=e,this.fetcher.fetchVAST({url:e,emitter:this.vastParser.emit.bind(this.vastParser),maxWrapperDepth:this.vastParser.maxWrapperDepth}).then(a=>(r.previousUrl=e,r.isRootVAST=!0,r.url=e,this.vastParser.parse(a,r).then(u=>{const c=this.vastParser.buildVASTResponse(u);i(c)}))).catch(a=>o(a))})}}const Bs=new xs,$t=Z("ui:gam-static"),fn=t=>new Promise((e,r)=>{const n=new Image;n.onload=()=>e(t),n.onerror=()=>r(),n.src=t}),Ms=t=>(e,r,n)=>t.transport.nanoquery.createFetcherStore([e,r],{dedupeTime:n.prefetch?n.refetchInterval:1/0,revalidateInterval:n.refetchInterval>0?n.refetchInterval:0,fetcher:async i=>{if(!i||typeof i!="string")throw new Error("no_valid_ad");V.emit("exposedPauseAd",{action:"load",payload:{}});try{const s=(await Bs.get(i)).ads.find(a=>a.creatives.length>0);if(s){const a=s.id||"";$t.debug(s,"validAd");const u=s.creatives.find(p=>p.type==="nonlinear");if(u){const p=u.adId||u.id||a;$t.debug(u,"nonlinear");const g=u.variations?.[0]?.staticResource,T=u.variations?.[0]?.nonlinearClickThroughURLTemplate;if(g)return await fn(g),V.emit("exposedPauseAd",{action:"loaded",payload:{id:p,parentId:a}}),{id:p,parentId:a,url:i,imageSrc:g,adUrl:T}}const c=s.creatives.find(p=>p.type==="companion");$t.debug(c,"companion");const l=c?.variations?.[0]?.staticResources?.[0]?.url,d=c?.variations?.[0]?.companionClickThroughURLTemplate;if(l){const p=c.adId||c.id||a;return await fn(l),V.emit("exposedPauseAd",{action:"loaded",payload:{id:p,parentId:a}}),{id:p,parentId:a,url:i,imageSrc:l,adUrl:d}}}throw new Error("no_valid_ad")}catch(o){throw console.error(o,"err"),new Error("no_valid_ad")}}});class qs extends Qn{getExternalPauseAd;externalPauseAdStores=new Map;externalPauseAdEnabled=new Map;log;constructor(e){super(),this.log=Z("advertisement");const r=Ms(e);this.getExternalPauseAd=(n,i)=>{if(this.externalPauseAdStores.has(n)){const a=this.externalPauseAdEnabled.get(n),u=this.externalPauseAdStores.get(n),c=a.get()===!1&&i.$enabled===!0;return a.set(i.$enabled),c&&window.requestAnimationFrame(()=>{u.revalidate()}),[u,n]}const o=G(i.$enabled),s=r(n,o,i);return this.externalPauseAdEnabled.set(n,o),this.externalPauseAdStores.set(n,s),[s,n]}}connect=()=>{this.log.debug("connect")};disconnect=()=>{this.log.debug("disconnect"),this.externalPauseAdStores.forEach(e=>{e.off()}),this.externalPauseAdEnabled.forEach(e=>{e.off()}),this.externalPauseAdEnabled.clear(),this.externalPauseAdStores.clear()}}const $s=(t,e,r)=>{t.sdk.advertisement=new qs(t),t.sdk.onMount({name:"advertisement"},()=>(t.sdk.advertisement.connect(),()=>{t.sdk.advertisement.disconnect()})),r()};class js{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 V.listen(r)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.INVITATION_ACCEPTED},category:dt.InvitationCategory.GAMES,from:dt.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.INVITATION_SENT},category:dt.InvitationCategory.GAMES,from:e||dt.InvitationFrom.UNSET})}}class Qs{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 V.listen(r)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.INTERACTIONS},actionType:$r.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.INTERACTIONS},actionType:$r.InteractionActionType.SCROLL})}}const Gs={[v.PromotionType.UNSET]:m.TopicSubType.UNSET,[v.PromotionType.INGAME_IAB21]:m.TopicSubType.PROMOTION_INGAME_IAB21,[v.PromotionType.INGAME_IAB21_SIDEBAR]:m.TopicSubType.PROMOTION_INGAME_IAB21,[v.PromotionType.INGAME_IAB11_LBAR]:m.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[v.PromotionType.INGAME_IAB11]:m.TopicSubType.PROMOTION_INGAME_IAB11,[v.PromotionType.INGAME_IAB11_SIDEBAR]:m.TopicSubType.PROMOTION_INGAME_IAB11,[v.PromotionType.INGAME_IAB21_LBAR]:m.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[v.PromotionType.INGAME_IAB61]:m.TopicSubType.PROMOTION_INGAME_IAB61,[v.PromotionType.INGAME_IAB61_SIDEBAR]:m.TopicSubType.PROMOTION_INGAME_IAB61,[v.PromotionType.EXTERNAL_AD]:m.TopicSubType.PROMOTION_GAM,[v.PromotionType.VIDEO_SIDE_BY_SIDE]:m.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[v.PromotionType.PICTURE_IN_PICTURE]:m.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[v.PromotionType.LOWER_THIRD]:m.TopicSubType.PROMOTION_LOWER_THIRD,[v.PromotionType.SHOP_LBAR]:m.TopicSubType.PROMOTION_SHOP_LBAR,[v.PromotionType.SHOP_OVERLAY]:m.TopicSubType.PROMOTION_SHOP_OVERLAY,[v.PromotionType.SHOP_SIDEBAR]:m.TopicSubType.PROMOTION_SHOP_SIDEBAR,[v.PromotionType.NFL_SHOP_LBAR]:m.TopicSubType.PROMOTION_SHOP_LBAR,[v.PromotionType.NFL_SHOP_OVERLAY]:m.TopicSubType.PROMOTION_SHOP_OVERLAY,[v.PromotionType.NFL_SHOP_SIDEBAR]:m.TopicSubType.PROMOTION_SHOP_SIDEBAR,[v.PromotionType.STATS]:m.TopicSubType.UNSET,[v.PromotionType.STANDARD]:m.TopicSubType.UNSET,[v.PromotionType.SHOP]:m.TopicSubType.UNSET,[v.PromotionType.NFL_SHOP]:m.TopicSubType.UNSET},dr=t=>t?Gs[t]:m.TopicSubType.UNSET,Ks={25:m.Kind.AD_VIDEO_Q25,50:m.Kind.AD_VIDEO_Q50,75:m.Kind.AD_VIDEO_Q75};class Ws{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(!n.slEventBus?.skipAnalytics){if(n.slEventBus?.type==="exposedPauseAd"){const i=n.slEventBus.payload;switch(n.slEventBus.action){case"enabled":this.exposedPauseAdEnabled(i);break;case"disabled":this.exposedPauseAdDisabled(i);break;case"closed":this.exposedPauseAdClosed(i);break;case"load":this.exposedPauseAdLoad(i,!1);break;case"loaded":this.exposedPauseAdLoad(i,!0);break;case"rendered":this.exposedPauseAdOpened(i);break;case"navigated":this.exposedPauseAdNavigated(i);break}}if(n.slEventBus?.type==="advertisement"){const i=n.slEventBus.payload,o=dr(i.type);switch(n.slEventBus.action){case"videoPlay":this.videoPlay(i,{topicSubType:o});break;case"videoEnd":this.videoEnd(i,{topicSubType:o});break;case"videoRendered":this.videoRendered(i,{topicSubType:o});break;case"buttonSelect":this.buttonSelect(i,{topicSubType:o});break;case"bannerSelect":this.bannerSelect(i,{topicSubType:o});break;case"bannerShown":this.bannerShown(i,{topicSubType:o});break;case"received":this.received(i,{topicSubType:o});break;case"opened":this.opened(i,{topicSubType:o});break;case"viewed":this.viewed(i,{topicSubType:o});break;case"videoMuted":case"videoUnmuted":this.videoMuted(i,{topicSubType:o,muted:n.slEventBus.action==="videoMuted"});break;case"videoReplayed":this.videoReplayed(i,{topicSubType:o});break;case"quartileCompleted":this.quartileCompleted(i,{topicSubType:o});break}}}};return V.listen(r)})}exposedPauseAdEnabled=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:m.Kind.STREAM_PAUSED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};exposedPauseAdClosed=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:m.Kind.EXTERNAL_AD_CLOSED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};exposedPauseAdDisabled=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:m.Kind.STREAM_RESUMED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};exposedPauseAdOpened=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:m.Kind.EXTERNAL_AD_RENDERED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};exposedPauseAdNavigated=({id:e,parentId:r})=>{const n=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...n,kind:m.Kind.AD_INTERACTION_BANNER_NAVIGATED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};exposedPauseAdLoad=({id:e,parentId:r},n)=>{const i=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...i,kind:n?m.Kind.EXTERNAL_AD_LOADED:m.Kind.EXTERNAL_AD_REQUESTED,topicId:e,parentTopicId:r,topicType:m.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:m.PollOpenedFrom.UNSET})};received=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.POLLS_RECEIVED,topicId:e,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:r},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.POLLS_OPENED,topicId:e,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:r==="notification"?m.PollOpenedFrom.IN_APP:m.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:r})=>{};videoMuted=({id:e},{topicSubType:r,muted:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:n?m.Kind.AD_VIDEO_MUTED:m.Kind.AD_VIDEO_UNMUTED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};quartileCompleted=({id:e,quartile:r},{topicSubType:n})=>{r&&this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:Ks[r],topicType:m.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:m.PollOpenedFrom.UNSET})};videoReplayed=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_VIDEO_REPLAYED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_VIDEO_PLAYED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};videoEnd=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_VIDEO_COMPLETE,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};videoRendered=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_VIDEO_RENDERED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_INTERACTION_BUTTON_NAVIGATED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_INTERACTION_BANNER_NAVIGATED,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})};bannerShown=({id:e},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:m.Kind.AD_BANNER_SHOWN,topicType:m.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:m.PollOpenedFrom.UNSET})}}const rt={[v.QuestionType.UNSET]:m.TopicType.UNSET,[v.QuestionType.FACTOID]:m.TopicType.POLLS_INSIGHT,[v.QuestionType.POLL]:m.TopicType.POLLS_POLL,[v.QuestionType.PREDICTION]:m.TopicType.POLLS_PREDICTION,[v.QuestionType.PROMOTION]:m.TopicType.POLLS_PROMOTION,[v.QuestionType.TRIVIA]:m.TopicType.POLLS_TRIVIA,[v.QuestionType.TWEET]:m.TopicType.POLLS_TWITTER};v.QuestionType.UNSET+"",ne.NotificationKind.UNSET,v.QuestionType.FACTOID+"",ne.NotificationKind.POLLS,v.QuestionType.POLL+"",ne.NotificationKind.POLLS,v.QuestionType.PREDICTION+"",ne.NotificationKind.POLLS,v.QuestionType.PROMOTION+"",ne.NotificationKind.POLLS,v.QuestionType.TRIVIA+"",ne.NotificationKind.POLLS,v.QuestionType.TWEET+"",ne.NotificationKind.POLLS;const Hs={[M.SdkOverlayType.UNSET]:m.Category.UNSET,[M.SdkOverlayType.INPLAY]:m.Category.INPLAY,[M.SdkOverlayType.MESSAGING]:m.Category.MESSAGING,[M.SdkOverlayType.STATISTICS]:m.Category.STATS,[M.SdkOverlayType.BETTING]:m.Category.BETTING,[M.SdkOverlayType.TWITTER]:m.Category.TWITTER,[M.SdkOverlayType.MERCHANDISE]:m.Category.MERCHANDISE,[M.SdkOverlayType.CONTESTS]:m.Category.CONTESTS,[M.SdkOverlayType.VOICE_CHAT]:m.Category.CALLING,[M.SdkOverlayType.TICKETS]:m.Category.TICKETS,[M.SdkOverlayType.WHOIS_WATCHING]:m.Category.WHOISWATCHING,[M.SdkOverlayType.PROFILE]:m.Category.PROFILE,[M.SdkOverlayType.GAMES]:m.Category.POLLS,[M.SdkOverlayType.GOLF_STATISTICS]:m.Category.STATS,[M.SdkOverlayType.HIGHLIGHTS]:m.Category.HIGHLIGHTS,[M.SdkOverlayType.PUBLIC_CHAT]:m.Category.PUBLIC_CHAT};class zs{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const r=n=>{if(n.slEventBus?.type==="notification")switch(n.slEventBus.action){case"rendered":this.received(n.slEventBus.payload);break;case"opened":this.opened(n.slEventBus.payload);break}if(n.slEventBus?.type==="advertisement")switch(n.slEventBus.action){case"notification-received":this.received({questionId:n.slEventBus.payload.id,questionType:v.QuestionType.PROMOTION,topicSubType:dr(n.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:n.slEventBus.payload.id,questionType:v.QuestionType.PROMOTION,topicSubType:dr(n.slEventBus.payload.type)});break}};return V.listen(r)})}received=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:r?rt[r]:m.TopicType.UNSET,topicSubType:n},notificationKind:ne.NotificationKind.POLLS,notificationType:ne.NotificationType.IN_APP})};opened=({questionId:e,questionType:r,topicSubType:n})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.NOTIFICATION_OPENED,topicId:e,topicType:r?rt[r]:m.TopicType.UNSET,topicSubType:n},notificationKind:ne.NotificationKind.POLLS,notificationType:ne.NotificationType.IN_APP})}}class Ys{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"viewed":this.viewed(n.slEventBus.payload);break}};return V.listen(r)})}received=({questionId:e,questionType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.POLLS_RECEIVED,topicId:e,topicType:r?rt[r]:m.TopicType.UNSET},pollOpenedFrom:m.PollOpenedFrom.UNSET})};viewed=({questionId:e,questionType:r,questionOpenedFrom:n,isAd:i})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:i?m.Kind.POLLS_AD_OPENED:m.Kind.POLLS_OPENED,topicId:e,topicType:r?rt[r]:m.TopicType.UNSET},pollOpenedFrom:n==="list"?m.PollOpenedFrom.PICK_HISTORY:m.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:r,isAd:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:n?m.Kind.POLLS_AD_VOTE:m.Kind.POLLS_VOTE,topicId:e,topicType:r?rt[r]:m.TopicType.UNSET},pollOpenedFrom:m.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.GAMES_JOINED},pollOpenedFrom:m.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:m.Kind.POLLS_NAVIGATED},pollOpenedFrom:m.PollOpenedFrom.UNSET})}}const Xs=({transport:t,$commonStore:e})=>{let r;const n=G(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(Bn.AnalyticsService,{method:"send",params:[n]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const p=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...p,kind:m.Kind.SESSION_HEARTBEAT}}}})}catch(g){ye.error(g,"send heartbeat failed")}return Date.now()},revalidateInterval:i}),u=()=>{ye.debug("mounted heartbeat"),r=a.subscribe(()=>{})},c=()=>{ye.debug("enabled heartbeat"),n.set(!0),a.lc===0&&u()},l=()=>{ye.debug("disabled heartbeat"),n.set(!1)};return{enable:c,disable:l,mount:u,unmount:()=>{ye.debug("unmounted heartbeat"),a.off(),r?.(),r=void 0,l()}}},ye=Z("analytics");class Js{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 Ne(X({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=Xs({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new zs(this),this.polls=new Ys(this),this.invitation=new js(this),this.interactions=new Qs(this),this.advertisement=new Ws(this);const{client:r}=e.analyticsTransport.createPromiseClient(Bn.AnalyticsService,{method:"send"});this.analyticsClient=r}connect=()=>{this.writeCommon("sessionId",$e.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,ye.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,ye.debug("analytics disconnected")};write=(e,r)=>{r&&this.analyticsClient.unary({message:{case:e,value:r}}).then(()=>{ye.trace("send analytics success",e,r)}).catch(n=>{ye.error(n,"send analytics failed")})};writeCommon=(e,r)=>{this.commonStore.setValue(e,r)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(r=>{this.writeCommon("eventId",r)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(r=>{r&&this.writeCommon("category",Hs[r]),r!==M.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",$e.v4()):this.writeCommon("overlaySessionId","")})),this.onConnect(()=>{const r=n=>{if(!n.slEventBus)return;const i=n.slEventBus?.action;n.slEventBus?.type==="exposedPauseAd"&&((i==="disabled"||i==="closed")&&setTimeout(()=>{this.writeCommon("overlaySessionId",""),this.writeCommon("topicId",""),this.writeCommon("parentTopicId",""),this.writeCommon("topicType",m.TopicType.UNSET),this.writeCommon("category",m.Category.UNSET)},200),i==="enabled"&&(this.writeCommon("overlaySessionId",$e.v4()),this.writeCommon("category",m.Category.EXPOSED_PAUSED_AD))),n.slEventBus?.type==="advertisement"&&(i==="opened"&&this.writeCommon("overlaySessionId",$e.v4()),i==="closed"&&this.writeCommon("overlaySessionId",""))};return V.listen(r)}),this.onConnect(()=>{const r=window.matchMedia("(orientation: portrait)"),n=i=>{this.writeCommon("screenOrientation",i.matches?m.ScreenOrientation.PORTRAIT:m.ScreenOrientation.LANDSCAPE)};return r.addEventListener("change",n),()=>{r.removeEventListener("change",n)}}),this.onConnect(()=>e.deepLink.$store.subscribe(r=>{r?.handled&&this.invitation.accepted()}))}}const Zs=(t,e,r)=>{t.analytics=new Js(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),t.sdk.writeOverlaySessionId=n=>{n===""?t.analytics.writeCommon("overlaySessionId",""):t.analytics.writeCommon("overlaySessionId",$e.v4())},()=>{t.analytics.disconnect()})),r()};var Er=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ea(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ir={exports:{}},Or={exports:{}};function ta(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 ra=ta,na=ra;function ai(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=na(ia),i=null,o=null,s=0,a=null,u={push:y,drain:ee,saturated:ee,pause:l,paused:!1,get concurrency(){return r},set concurrency(k){if(!(k>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(r=k,!u.paused)for(;i&&s<r;)s++,O()},running:c,resume:g,idle:T,length:d,getQueue:p,unshift:E,empty:ee,kill:w,killAndDrain:I,error:P};return u;function c(){return s}function l(){u.paused=!0}function d(){for(var k=i,q=0;k;)k=k.next,q++;return q}function p(){for(var k=i,q=[];k;)q.push(k.value),k=k.next;return q}function g(){if(u.paused){if(u.paused=!1,i===null){s++,O();return}for(;i&&s<r;)s++,O()}}function T(){return s===0&&u.length()===0}function y(k,q){var _=n.get();_.context=t,_.release=O,_.value=k,_.callback=q||ee,_.errorHandler=a,s>=r||u.paused?o?(o.next=_,o=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function E(k,q){var _=n.get();_.context=t,_.release=O,_.value=k,_.callback=q||ee,_.errorHandler=a,s>=r||u.paused?i?(_.next=i,i=_):(i=_,o=_,u.saturated()):(s++,e.call(t,_.value,_.worked))}function O(k){k&&n.release(k);var q=i;q&&s<=r?u.paused?s--:(o===i&&(o=null),i=q.next,q.next=null,e.call(t,q.value,q.worked),o===null&&u.empty()):--s===0&&u.drain()}function w(){i=null,o=null,u.drain=ee}function I(){i=null,o=null,u.drain(),u.drain=ee}function P(k){a=k}}function ee(){}function ia(){this.value=null,this.callback=ee,this.next=null,this.release=ee,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=ee,t.errorHandler&&o(r,s),i.call(t.context,r,n),t.release(t)}}function oa(t,e,r){typeof t=="function"&&(r=e,e=t,t=null);function n(l,d){e.call(this,l).then(function(p){d(null,p)},d)}var i=ai(t,n,r),o=i.push,s=i.unshift;return i.push=a,i.unshift=u,i.drained=c,i;function a(l){var d=new Promise(function(p,g){o(l,function(T,y){if(T){g(T);return}p(y)})});return d.catch(ee),d}function u(l){var d=new Promise(function(p,g){s(l,function(T,y){if(T){g(T);return}p(y)})});return d.catch(ee),d}function c(){if(i.idle())return new Promise(function(p){p()});var l=i.drain,d=new Promise(function(p){i.drain=function(){l(),p()}});return d}}Or.exports=ai;Or.exports.promise=oa;var ui=Or.exports,kr={exports:{}},We=typeof Reflect=="object"?Reflect:null,hn=We&&typeof We.apply=="function"?We.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},bt;We&&typeof We.ownKeys=="function"?bt=We.ownKeys:Object.getOwnPropertySymbols?bt=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:bt=function(e){return Object.getOwnPropertyNames(e)};function sa(t){console&&console.warn&&console.warn(t)}var ci=Number.isNaN||function(e){return e!==e};function x(){x.init.call(this)}kr.exports=x;kr.exports.once=la;x.EventEmitter=x;x.prototype._events=void 0;x.prototype._eventsCount=0;x.prototype._maxListeners=void 0;var mn=10;function Dt(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(x,"defaultMaxListeners",{enumerable:!0,get:function(){return mn},set:function(t){if(typeof t!="number"||t<0||ci(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");mn=t}});x.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};x.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ci(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 li(t){return t._maxListeners===void 0?x.defaultMaxListeners:t._maxListeners}x.prototype.getMaxListeners=function(){return li(this)};x.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")hn(u,this,r);else for(var c=u.length,l=mi(u,c),n=0;n<c;++n)hn(l[n],this,r);return!0};function di(t,e,r,n){var i,o,s;if(Dt(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=li(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,sa(a)}return t}x.prototype.addListener=function(e,r){return di(this,e,r,!1)};x.prototype.on=x.prototype.addListener;x.prototype.prependListener=function(e,r){return di(this,e,r,!0)};function aa(){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 pi(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=aa.bind(n);return i.listener=r,n.wrapFn=i,i}x.prototype.once=function(e,r){return Dt(r),this.on(e,pi(this,e,r)),this};x.prototype.prependOnceListener=function(e,r){return Dt(r),this.prependListener(e,pi(this,e,r)),this};x.prototype.removeListener=function(e,r){var n,i,o,s,a;if(Dt(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():ua(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this};x.prototype.off=x.prototype.removeListener;x.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 fi(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?ca(i):mi(i,i.length)}x.prototype.listeners=function(e){return fi(this,e,!0)};x.prototype.rawListeners=function(e){return fi(this,e,!1)};x.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):hi.call(t,e)};x.prototype.listenerCount=hi;function hi(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}x.prototype.eventNames=function(){return this._eventsCount>0?bt(this._events):[]};function mi(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function ua(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ca(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function la(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))}gi(t,e,o,{once:!0}),e!=="error"&&da(t,i,{once:!0})})}function da(t,e,r){typeof t.on=="function"&&gi(t,"error",e,r)}function gi(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 yi=kr.exports,Ft={},bi={},vi=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},pa=vi,Ut=function(){return pa()&&!!Symbol.toStringTag},fa=Error,ha=EvalError,ma=RangeError,ga=ReferenceError,Ti=SyntaxError,Vt=TypeError,ya=URIError,gn=typeof Symbol<"u"&&Symbol,ba=vi,va=function(){return typeof gn!="function"||typeof Symbol!="function"||typeof gn("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ba()},jt={__proto__:null,foo:{}},Ta=Object,Sa=function(){return{__proto__:jt}.foo===jt.foo&&!(jt instanceof Ta)},Aa="Function.prototype.bind called on incompatible ",wa=Object.prototype.toString,Ea=Math.max,Ia="[object Function]",yn=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},Oa=function(e,r){for(var n=[],i=r,o=0;i<e.length;i+=1,o+=1)n[o]=e[i];return n},ka=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r},Na=function(e){var r=this;if(typeof r!="function"||wa.apply(r)!==Ia)throw new TypeError(Aa+r);for(var n=Oa(arguments,1),i,o=function(){if(this instanceof i){var l=r.apply(this,yn(n,arguments));return Object(l)===l?l:this}return r.apply(e,yn(n,arguments))},s=Ea(0,r.length-n.length),a=[],u=0;u<s;u++)a[u]="$"+u;if(i=Function("binder","return function ("+ka(a,",")+"){ return binder.apply(this,arguments); }")(o),r.prototype){var c=function(){};c.prototype=r.prototype,i.prototype=new c,c.prototype=null}return i},Ca=Na,Nr=Function.prototype.bind||Ca,Pa=Function.prototype.call,La=Object.prototype.hasOwnProperty,Ra=Nr,_a=Ra.call(Pa,La),R,Da=fa,Fa=ha,Ua=ma,Va=ga,Ye=Ti,He=Vt,xa=ya,Si=Function,Qt=function(t){try{return Si('"use strict"; return ('+t+").constructor;")()}catch{}},Ce=Object.getOwnPropertyDescriptor;if(Ce)try{Ce({},"")}catch{Ce=null}var Gt=function(){throw new He},Ba=Ce?function(){try{return arguments.callee,Gt}catch{try{return Ce(arguments,"callee").get}catch{return Gt}}}():Gt,Be=va(),Ma=Sa(),K=Object.getPrototypeOf||(Ma?function(t){return t.__proto__}:null),qe={},qa=typeof Uint8Array>"u"||!K?R:K(Uint8Array),Pe={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?R:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?R:ArrayBuffer,"%ArrayIteratorPrototype%":Be&&K?K([][Symbol.iterator]()):R,"%AsyncFromSyncIteratorPrototype%":R,"%AsyncFunction%":qe,"%AsyncGenerator%":qe,"%AsyncGeneratorFunction%":qe,"%AsyncIteratorPrototype%":qe,"%Atomics%":typeof Atomics>"u"?R:Atomics,"%BigInt%":typeof BigInt>"u"?R:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?R:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?R:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?R:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Da,"%eval%":eval,"%EvalError%":Fa,"%Float32Array%":typeof Float32Array>"u"?R:Float32Array,"%Float64Array%":typeof Float64Array>"u"?R:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?R:FinalizationRegistry,"%Function%":Si,"%GeneratorFunction%":qe,"%Int8Array%":typeof Int8Array>"u"?R:Int8Array,"%Int16Array%":typeof Int16Array>"u"?R:Int16Array,"%Int32Array%":typeof Int32Array>"u"?R:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Be&&K?K(K([][Symbol.iterator]())):R,"%JSON%":typeof JSON=="object"?JSON:R,"%Map%":typeof Map>"u"?R:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Be||!K?R:K(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?R:Promise,"%Proxy%":typeof Proxy>"u"?R:Proxy,"%RangeError%":Ua,"%ReferenceError%":Va,"%Reflect%":typeof Reflect>"u"?R:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?R:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Be||!K?R:K(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?R:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Be&&K?K(""[Symbol.iterator]()):R,"%Symbol%":Be?Symbol:R,"%SyntaxError%":Ye,"%ThrowTypeError%":Ba,"%TypedArray%":qa,"%TypeError%":He,"%Uint8Array%":typeof Uint8Array>"u"?R:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?R:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?R:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?R:Uint32Array,"%URIError%":xa,"%WeakMap%":typeof WeakMap>"u"?R:WeakMap,"%WeakRef%":typeof WeakRef>"u"?R:WeakRef,"%WeakSet%":typeof WeakSet>"u"?R:WeakSet};if(K)try{null.error}catch(t){var $a=K(K(t));Pe["%Error.prototype%"]=$a}var ja=function t(e){var r;if(e==="%AsyncFunction%")r=Qt("async function () {}");else if(e==="%GeneratorFunction%")r=Qt("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Qt("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&K&&(r=K(i.prototype))}return Pe[e]=r,r},bn={__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"]},st=Nr,It=_a,Qa=st.call(Function.call,Array.prototype.concat),Ga=st.call(Function.apply,Array.prototype.splice),vn=st.call(Function.call,String.prototype.replace),Ot=st.call(Function.call,String.prototype.slice),Ka=st.call(Function.call,RegExp.prototype.exec),Wa=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Ha=/\\(\\)?/g,za=function(e){var r=Ot(e,0,1),n=Ot(e,-1);if(r==="%"&&n!=="%")throw new Ye("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Ye("invalid intrinsic syntax, expected opening `%`");var i=[];return vn(e,Wa,function(o,s,a,u){i[i.length]=a?vn(u,Ha,"$1"):s||o}),i},Ya=function(e,r){var n=e,i;if(It(bn,n)&&(i=bn[n],n="%"+i[0]+"%"),It(Pe,n)){var o=Pe[n];if(o===qe&&(o=ja(n)),typeof o>"u"&&!r)throw new He("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:o}}throw new Ye("intrinsic "+e+" does not exist!")},at=function(e,r){if(typeof e!="string"||e.length===0)throw new He("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new He('"allowMissing" argument must be a boolean');if(Ka(/^%?[^%]*%?$/,e)===null)throw new Ye("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=za(e),i=n.length>0?n[0]:"",o=Ya("%"+i+"%",r),s=o.name,a=o.value,u=!1,c=o.alias;c&&(i=c[0],Ga(n,Qa([0,1],c)));for(var l=1,d=!0;l<n.length;l+=1){var p=n[l],g=Ot(p,0,1),T=Ot(p,-1);if((g==='"'||g==="'"||g==="`"||T==='"'||T==="'"||T==="`")&&g!==T)throw new Ye("property names with quotes must have matching quotes");if((p==="constructor"||!d)&&(u=!0),i+="."+p,s="%"+i+"%",It(Pe,s))a=Pe[s];else if(a!=null){if(!(p in a)){if(!r)throw new He("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ce&&l+1>=n.length){var y=Ce(a,p);d=!!y,d&&"get"in y&&!("originalValue"in y.get)?a=y.get:a=a[p]}else d=It(a,p),a=a[p];d&&!u&&(Pe[s]=a)}}return a},Ai={exports:{}},Kt,Tn;function Cr(){if(Tn)return Kt;Tn=1;var t=at,e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return Kt=e,Kt}var Xa=at,vt=Xa("%Object.getOwnPropertyDescriptor%",!0);if(vt)try{vt([],"length")}catch{vt=null}var xt=vt,Sn=Cr(),Ja=Ti,Me=Vt,An=xt,Za=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Me("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Me("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Me("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Me("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Me("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Me("`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=!!An&&An(e,r);if(Sn)Sn(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 Ja("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},pr=Cr(),wi=function(){return!!pr};wi.hasArrayLengthDefineBug=function(){if(!pr)return null;try{return pr([],"length",{value:1}).length!==1}catch{return!0}};var eu=wi,tu=at,wn=Za,ru=eu(),En=xt,In=Vt,nu=tu("%Math.floor%"),iu=function(e,r){if(typeof e!="function")throw new In("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||nu(r)!==r)throw new In("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,o=!0;if("length"in e&&En){var s=En(e,"length");s&&!s.configurable&&(i=!1),s&&!s.writable&&(o=!1)}return(i||o||!n)&&(ru?wn(e,"length",r,!0,!0):wn(e,"length",r)),e};(function(t){var e=Nr,r=at,n=iu,i=Vt,o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||e.call(s,o),u=Cr(),c=r("%Math.max%");t.exports=function(p){if(typeof p!="function")throw new i("a function is required");var g=a(e,s,arguments);return n(g,1+c(0,p.length-(arguments.length-1)),!0)};var l=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:l}):t.exports.apply=l})(Ai);var Pr=Ai.exports,Ei=at,Ii=Pr,ou=Ii(Ei("String.prototype.indexOf")),Lr=function(e,r){var n=Ei(e,!!r);return typeof n=="function"&&ou(e,".prototype.")>-1?Ii(n):n},su=Ut(),au=Lr,fr=au("Object.prototype.toString"),Bt=function(e){return su&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:fr(e)==="[object Arguments]"},Oi=function(e){return Bt(e)?!0:e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&fr(e)!=="[object Array]"&&fr(e.callee)==="[object Function]"},uu=function(){return Bt(arguments)}();Bt.isLegacyArguments=Oi;var cu=uu?Bt:Oi,lu=Object.prototype.toString,du=Function.prototype.toString,pu=/^\s*(?:function)?\*/,ki=Ut(),Wt=Object.getPrototypeOf,fu=function(){if(!ki)return!1;try{return Function("return function*() {}")()}catch{}},Ht,hu=function(e){if(typeof e!="function")return!1;if(pu.test(du.call(e)))return!0;if(!ki){var r=lu.call(e);return r==="[object GeneratorFunction]"}if(!Wt)return!1;if(typeof Ht>"u"){var n=fu();Ht=n?Wt(n):!1}return Wt(e)===Ht},Ni=Function.prototype.toString,Ge=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,hr,Tt;if(typeof Ge=="function"&&typeof Object.defineProperty=="function")try{hr=Object.defineProperty({},"length",{get:function(){throw Tt}}),Tt={},Ge(function(){throw 42},null,hr)}catch(t){t!==Tt&&(Ge=null)}else Ge=null;var mu=/^\s*class\b/,mr=function(e){try{var r=Ni.call(e);return mu.test(r)}catch{return!1}},zt=function(e){try{return mr(e)?!1:(Ni.call(e),!0)}catch{return!1}},St=Object.prototype.toString,gu="[object Object]",yu="[object Function]",bu="[object GeneratorFunction]",vu="[object HTMLAllCollection]",Tu="[object HTML document.all class]",Su="[object HTMLCollection]",Au=typeof Symbol=="function"&&!!Symbol.toStringTag,wu=!(0 in[,]),gr=function(){return!1};if(typeof document=="object"){var Eu=document.all;St.call(Eu)===St.call(document.all)&&(gr=function(e){if((wu||!e)&&(typeof e>"u"||typeof e=="object"))try{var r=St.call(e);return(r===vu||r===Tu||r===Su||r===gu)&&e("")==null}catch{}return!1})}var Iu=Ge?function(e){if(gr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Ge(e,null,hr)}catch(r){if(r!==Tt)return!1}return!mr(e)&&zt(e)}:function(e){if(gr(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(Au)return zt(e);if(mr(e))return!1;var r=St.call(e);return r!==yu&&r!==bu&&!/^\[object HTML/.test(r)?!1:zt(e)},Ou=Iu,ku=Object.prototype.toString,Ci=Object.prototype.hasOwnProperty,Nu=function(e,r,n){for(var i=0,o=e.length;i<o;i++)Ci.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Cu=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)},Pu=function(e,r,n){for(var i in e)Ci.call(e,i)&&(n==null?r(e[i],i,e):r.call(n,e[i],i,e))},Lu=function(e,r,n){if(!Ou(r))throw new TypeError("iterator must be a function");var i;arguments.length>=3&&(i=n),ku.call(e)==="[object Array]"?Nu(e,r,i):typeof e=="string"?Cu(e,r,i):Pu(e,r,i)},Pi=Lu,Ru=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],Yt=Ru,_u=typeof globalThis>"u"?Er:globalThis,Li=function(){for(var e=[],r=0;r<Yt.length;r++)typeof _u[Yt[r]]=="function"&&(e[e.length]=Yt[r]);return e},kt=Pi,Du=Li,On=Pr,Rr=Lr,At=xt,Fu=Rr("Object.prototype.toString"),Ri=Ut(),kn=typeof globalThis>"u"?Er:globalThis,yr=Du(),_r=Rr("String.prototype.slice"),Xt=Object.getPrototypeOf,Uu=Rr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},Nt={__proto__:null};Ri&&At&&Xt?kt(yr,function(t){var e=new kn[t];if(Symbol.toStringTag in e){var r=Xt(e),n=At(r,Symbol.toStringTag);if(!n){var i=Xt(r);n=At(i,Symbol.toStringTag)}Nt["$"+t]=On(n.get)}}):kt(yr,function(t){var e=new kn[t],r=e.slice||e.set;r&&(Nt["$"+t]=On(r))});var Vu=function(e){var r=!1;return kt(Nt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=_r(i,1))}catch{}}),r},xu=function(e){var r=!1;return kt(Nt,function(n,i){if(!r)try{n(e),r=_r(i,1)}catch{}}),r},Bu=function(e){if(!e||typeof e!="object")return!1;if(!Ri){var r=_r(Fu(e),8,-1);return Uu(yr,r)>-1?r:r!=="Object"?!1:xu(e)}return At?Vu(e):null},Ct=Pi,Mu=Li,Nn=Pr,Dr=Lr,wt=xt,qu=Dr("Object.prototype.toString"),_i=Ut(),Cn=typeof globalThis>"u"?Er:globalThis,br=Mu(),Fr=Dr("String.prototype.slice"),Jt=Object.getPrototypeOf,$u=Dr("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n<e.length;n+=1)if(e[n]===r)return n;return-1},Pt={__proto__:null};_i&&wt&&Jt?Ct(br,function(t){var e=new Cn[t];if(Symbol.toStringTag in e){var r=Jt(e),n=wt(r,Symbol.toStringTag);if(!n){var i=Jt(r);n=wt(i,Symbol.toStringTag)}Pt["$"+t]=Nn(n.get)}}):Ct(br,function(t){var e=new Cn[t],r=e.slice||e.set;r&&(Pt["$"+t]=Nn(r))});var ju=function(e){var r=!1;return Ct(Pt,function(n,i){if(!r)try{"$"+n(e)===i&&(r=Fr(i,1))}catch{}}),r},Qu=function(e){var r=!1;return Ct(Pt,function(n,i){if(!r)try{n(e),r=Fr(i,1)}catch{}}),r},Gu=function(e){if(!e||typeof e!="object")return!1;if(!_i){var r=Fr(qu(e),8,-1);return $u(br,r)>-1?r:r!=="Object"?!1:Qu(e)}return wt?ju(e):null},Ku=Gu,Wu=function(e){return!!Ku(e)};(function(t){var e=cu,r=hu,n=Bu,i=Wu;function o(S){return S.call.bind(S)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),c=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(s)var p=o(BigInt.prototype.valueOf);if(a)var g=o(Symbol.prototype.valueOf);function T(S,Mi){if(typeof S!="object")return!1;try{return Mi(S),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=r,t.isTypedArray=i;function y(S){return typeof Promise<"u"&&S instanceof Promise||S!==null&&typeof S=="object"&&typeof S.then=="function"&&typeof S.catch=="function"}t.isPromise=y;function E(S){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(S):i(S)||b(S)}t.isArrayBufferView=E;function O(S){return n(S)==="Uint8Array"}t.isUint8Array=O;function w(S){return n(S)==="Uint8ClampedArray"}t.isUint8ClampedArray=w;function I(S){return n(S)==="Uint16Array"}t.isUint16Array=I;function P(S){return n(S)==="Uint32Array"}t.isUint32Array=P;function k(S){return n(S)==="Int8Array"}t.isInt8Array=k;function q(S){return n(S)==="Int16Array"}t.isInt16Array=q;function _(S){return n(S)==="Int32Array"}t.isInt32Array=_;function oe(S){return n(S)==="Float32Array"}t.isFloat32Array=oe;function se(S){return n(S)==="Float64Array"}t.isFloat64Array=se;function Re(S){return n(S)==="BigInt64Array"}t.isBigInt64Array=Re;function Ee(S){return n(S)==="BigUint64Array"}t.isBigUint64Array=Ee;function de(S){return u(S)==="[object Map]"}de.working=typeof Map<"u"&&de(new Map);function Mt(S){return typeof Map>"u"?!1:de.working?de(S):S instanceof Map}t.isMap=Mt;function Se(S){return u(S)==="[object Set]"}Se.working=typeof Set<"u"&&Se(new Set);function et(S){return typeof Set>"u"?!1:Se.working?Se(S):S instanceof Set}t.isSet=et;function _e(S){return u(S)==="[object WeakMap]"}_e.working=typeof WeakMap<"u"&&_e(new WeakMap);function qt(S){return typeof WeakMap>"u"?!1:_e.working?_e(S):S instanceof WeakMap}t.isWeakMap=qt;function De(S){return u(S)==="[object WeakSet]"}De.working=typeof WeakSet<"u"&&De(new WeakSet);function pe(S){return De(S)}t.isWeakSet=pe;function Fe(S){return u(S)==="[object ArrayBuffer]"}Fe.working=typeof ArrayBuffer<"u"&&Fe(new ArrayBuffer);function ut(S){return typeof ArrayBuffer>"u"?!1:Fe.working?Fe(S):S instanceof ArrayBuffer}t.isArrayBuffer=ut;function h(S){return u(S)==="[object DataView]"}h.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&h(new DataView(new ArrayBuffer(1),0,1));function b(S){return typeof DataView>"u"?!1:h.working?h(S):S instanceof DataView}t.isDataView=b;var A=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function N(S){return u(S)==="[object SharedArrayBuffer]"}function F(S){return typeof A>"u"?!1:(typeof N.working>"u"&&(N.working=N(new A)),N.working?N(S):S instanceof A)}t.isSharedArrayBuffer=F;function U(S){return u(S)==="[object AsyncFunction]"}t.isAsyncFunction=U;function L(S){return u(S)==="[object Map Iterator]"}t.isMapIterator=L;function D(S){return u(S)==="[object Set Iterator]"}t.isSetIterator=D;function B(S){return u(S)==="[object Generator]"}t.isGeneratorObject=B;function Y(S){return u(S)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=Y;function Ie(S){return T(S,c)}t.isNumberObject=Ie;function ct(S){return T(S,l)}t.isStringObject=ct;function Ue(S){return T(S,d)}t.isBooleanObject=Ue;function lt(S){return s&&T(S,p)}t.isBigIntObject=lt;function xr(S){return a&&T(S,g)}t.isSymbolObject=xr;function xi(S){return Ie(S)||ct(S)||Ue(S)||lt(S)||xr(S)}t.isBoxedPrimitive=xi;function Bi(S){return typeof Uint8Array<"u"&&(ut(S)||F(S))}t.isAnyArrayBuffer=Bi,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(S){Object.defineProperty(t,S,{enumerable:!1,value:function(){throw new Error(S+" is not supported in userland")}})})})(bi);var Hu=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"},vr={exports:{}};typeof Object.create=="function"?vr.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:vr.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 zu=vr.exports;(function(t){var e=Object.getOwnPropertyDescriptors||function(b){for(var A=Object.keys(b),N={},F=0;F<A.length;F++)N[A[F]]=Object.getOwnPropertyDescriptor(b,A[F]);return N},r=/%[sdj%]/g;t.format=function(h){if(!k(h)){for(var b=[],A=0;A<arguments.length;A++)b.push(s(arguments[A]));return b.join(" ")}for(var A=1,N=arguments,F=N.length,U=String(h).replace(r,function(D){if(D==="%%")return"%";if(A>=F)return D;switch(D){case"%s":return String(N[A++]);case"%d":return Number(N[A++]);case"%j":try{return JSON.stringify(N[A++])}catch{return"[Circular]"}default:return D}}),L=N[A];A<F;L=N[++A])w(L)||!se(L)?U+=" "+L:U+=" "+s(L);return U},t.deprecate=function(h,b){if(typeof C<"u"&&C.noDeprecation===!0)return h;if(typeof C>"u")return function(){return t.deprecate(h,b).apply(this,arguments)};var A=!1;function N(){if(!A){if(C.throwDeprecation)throw new Error(b);C.traceDeprecation?console.trace(b):console.error(b),A=!0}return h.apply(this,arguments)}return N};var n={},i=/^$/;if(C.env.NODE_DEBUG){var o=C.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(h){if(h=h.toUpperCase(),!n[h])if(i.test(h)){var b=C.pid;n[h]=function(){var A=t.format.apply(t,arguments);console.error("%s %d: %s",h,b,A)}}else n[h]=function(){};return n[h]};function s(h,b){var A={seen:[],stylize:u};return arguments.length>=3&&(A.depth=arguments[2]),arguments.length>=4&&(A.colors=arguments[3]),O(b)?A.showHidden=b:b&&t._extend(A,b),_(A.showHidden)&&(A.showHidden=!1),_(A.depth)&&(A.depth=2),_(A.colors)&&(A.colors=!1),_(A.customInspect)&&(A.customInspect=!0),A.colors&&(A.stylize=a),l(A,h,A.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(h,b){var A=s.styles[b];return A?"\x1B["+s.colors[A][0]+"m"+h+"\x1B["+s.colors[A][1]+"m":h}function u(h,b){return h}function c(h){var b={};return h.forEach(function(A,N){b[A]=!0}),b}function l(h,b,A){if(h.customInspect&&b&&de(b.inspect)&&b.inspect!==t.inspect&&!(b.constructor&&b.constructor.prototype===b)){var N=b.inspect(A,h);return k(N)||(N=l(h,N,A)),N}var F=d(h,b);if(F)return F;var U=Object.keys(b),L=c(U);if(h.showHidden&&(U=Object.getOwnPropertyNames(b)),Ee(b)&&(U.indexOf("message")>=0||U.indexOf("description")>=0))return p(b);if(U.length===0){if(de(b)){var D=b.name?": "+b.name:"";return h.stylize("[Function"+D+"]","special")}if(oe(b))return h.stylize(RegExp.prototype.toString.call(b),"regexp");if(Re(b))return h.stylize(Date.prototype.toString.call(b),"date");if(Ee(b))return p(b)}var B="",Y=!1,Ie=["{","}"];if(E(b)&&(Y=!0,Ie=["[","]"]),de(b)){var ct=b.name?": "+b.name:"";B=" [Function"+ct+"]"}if(oe(b)&&(B=" "+RegExp.prototype.toString.call(b)),Re(b)&&(B=" "+Date.prototype.toUTCString.call(b)),Ee(b)&&(B=" "+p(b)),U.length===0&&(!Y||b.length==0))return Ie[0]+B+Ie[1];if(A<0)return oe(b)?h.stylize(RegExp.prototype.toString.call(b),"regexp"):h.stylize("[Object]","special");h.seen.push(b);var Ue;return Y?Ue=g(h,b,A,L,U):Ue=U.map(function(lt){return T(h,b,A,L,lt,Y)}),h.seen.pop(),y(Ue,B,Ie)}function d(h,b){if(_(b))return h.stylize("undefined","undefined");if(k(b)){var A="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return h.stylize(A,"string")}if(P(b))return h.stylize(""+b,"number");if(O(b))return h.stylize(""+b,"boolean");if(w(b))return h.stylize("null","null")}function p(h){return"["+Error.prototype.toString.call(h)+"]"}function g(h,b,A,N,F){for(var U=[],L=0,D=b.length;L<D;++L)De(b,String(L))?U.push(T(h,b,A,N,String(L),!0)):U.push("");return F.forEach(function(B){B.match(/^\d+$/)||U.push(T(h,b,A,N,B,!0))}),U}function T(h,b,A,N,F,U){var L,D,B;if(B=Object.getOwnPropertyDescriptor(b,F)||{value:b[F]},B.get?B.set?D=h.stylize("[Getter/Setter]","special"):D=h.stylize("[Getter]","special"):B.set&&(D=h.stylize("[Setter]","special")),De(N,F)||(L="["+F+"]"),D||(h.seen.indexOf(B.value)<0?(w(A)?D=l(h,B.value,null):D=l(h,B.value,A-1),D.indexOf(`
|
|
3
3
|
`)>-1&&(U?D=D.split(`
|
|
4
4
|
`).map(function(Y){return" "+Y}).join(`
|
|
5
5
|
`).slice(2):D=`
|
|
6
6
|
`+D.split(`
|
|
7
7
|
`).map(function(Y){return" "+Y}).join(`
|
|
8
|
-
`))):D=h.stylize("[Circular]","special")),_(
|
|
8
|
+
`))):D=h.stylize("[Circular]","special")),_(L)){if(U&&F.match(/^\d+$/))return D;L=JSON.stringify(""+F),L.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(L=L.slice(1,-1),L=h.stylize(L,"name")):(L=L.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),L=h.stylize(L,"string"))}return L+": "+D}function y(h,b,A){var N=h.reduce(function(F,U){return U.indexOf(`
|
|
9
9
|
`)>=0,F+U.replace(/\u001b\[\d\d?m/g,"").length+1},0);return N>60?A[0]+(b===""?"":b+`
|
|
10
10
|
`)+" "+h.join(`,
|
|
11
|
-
`)+" "+A[1]:A[0]+b+" "+h.join(", ")+" "+A[1]}t.types=bi;function E(h){return Array.isArray(h)}t.isArray=E;function O(h){return typeof h=="boolean"}t.isBoolean=O;function w(h){return h===null}t.isNull=w;function I(h){return h==null}t.isNullOrUndefined=I;function
|
|
11
|
+
`)+" "+A[1]:A[0]+b+" "+h.join(", ")+" "+A[1]}t.types=bi;function E(h){return Array.isArray(h)}t.isArray=E;function O(h){return typeof h=="boolean"}t.isBoolean=O;function w(h){return h===null}t.isNull=w;function I(h){return h==null}t.isNullOrUndefined=I;function P(h){return typeof h=="number"}t.isNumber=P;function k(h){return typeof h=="string"}t.isString=k;function q(h){return typeof h=="symbol"}t.isSymbol=q;function _(h){return h===void 0}t.isUndefined=_;function oe(h){return se(h)&&Se(h)==="[object RegExp]"}t.isRegExp=oe,t.types.isRegExp=oe;function se(h){return typeof h=="object"&&h!==null}t.isObject=se;function Re(h){return se(h)&&Se(h)==="[object Date]"}t.isDate=Re,t.types.isDate=Re;function Ee(h){return se(h)&&(Se(h)==="[object Error]"||h instanceof Error)}t.isError=Ee,t.types.isNativeError=Ee;function de(h){return typeof h=="function"}t.isFunction=de;function Mt(h){return h===null||typeof h=="boolean"||typeof h=="number"||typeof h=="string"||typeof h=="symbol"||typeof h>"u"}t.isPrimitive=Mt,t.isBuffer=Hu;function Se(h){return Object.prototype.toString.call(h)}function et(h){return h<10?"0"+h.toString(10):h.toString(10)}var _e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function qt(){var h=new Date,b=[et(h.getHours()),et(h.getMinutes()),et(h.getSeconds())].join(":");return[h.getDate(),_e[h.getMonth()],b].join(" ")}t.log=function(){console.log("%s - %s",qt(),t.format.apply(t,arguments))},t.inherits=zu,t._extend=function(h,b){if(!b||!se(b))return h;for(var A=Object.keys(b),N=A.length;N--;)h[A[N]]=b[A[N]];return h};function De(h,b){return Object.prototype.hasOwnProperty.call(h,b)}var pe=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(b){if(typeof b!="function")throw new TypeError('The "original" argument must be of type Function');if(pe&&b[pe]){var A=b[pe];if(typeof A!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(A,pe,{value:A,enumerable:!1,writable:!1,configurable:!0}),A}function A(){for(var N,F,U=new Promise(function(B,Y){N=B,F=Y}),L=[],D=0;D<arguments.length;D++)L.push(arguments[D]);L.push(function(B,Y){B?F(B):N(Y)});try{b.apply(this,L)}catch(B){F(B)}return U}return Object.setPrototypeOf(A,Object.getPrototypeOf(b)),pe&&Object.defineProperty(A,pe,{value:A,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(A,e(b))},t.promisify.custom=pe;function Fe(h,b){if(!h){var A=new Error("Promise was rejected with a falsy value");A.reason=h,h=A}return b(h)}function ut(h){if(typeof h!="function")throw new TypeError('The "original" argument must be of type Function');function b(){for(var A=[],N=0;N<arguments.length;N++)A.push(arguments[N]);var F=A.pop();if(typeof F!="function")throw new TypeError("The last argument must be of type Function");var U=this,L=function(){return F.apply(U,arguments)};h.apply(this,A).then(function(D){C.nextTick(L.bind(null,null,D))},function(D){C.nextTick(Fe.bind(null,D,L))})}return Object.setPrototypeOf(b,Object.getPrototypeOf(h)),Object.defineProperties(b,e(h)),b}t.callbackify=ut})(Ft);const{inherits:Yu,format:Zt}=Ft;function Oe(t,e,r=Error){if(!t)throw new Error("Avvio error code must not be empty");if(!e)throw new Error("Avvio base error message must not be empty");function n(i,o,s){if(!new.target)return new n(i,o,s);Error.captureStackTrace(this,n),this.code=t,this.message=e,this.name="AvvioError",i&&o&&s?this.message=Zt(e,i,o,s):i&&o?this.message=Zt(e,i,o):i?this.message=Zt(e,i):this.message=e}return n.prototype[Symbol.toStringTag]="Error",n.prototype.toString=function(){return`${this.name} [${this.code}]: ${this.message}`},Yu(n,r),n}var Di={createError:Oe,AVV_ERR_EXPOSE_ALREADY_DEFINED:Oe("AVV_ERR_EXPOSE_ALREADY_DEFINED","'%s' () is already defined, specify an expose option"),AVV_ERR_CALLBACK_NOT_FN:Oe("AVV_ERR_CALLBACK_NOT_FN","Callback for '%s' hook is not a function. Received: '%s'"),AVV_ERR_PLUGIN_NOT_VALID:Oe("AVV_ERR_PLUGIN_NOT_VALID","Plugin must be a function or a promise. Received: '%s'"),AVV_ERR_ROOT_PLG_BOOTED:Oe("AVV_ERR_PLUGIN_NOT_VALID","Root plugin has already booted"),AVV_ERR_PARENT_PLG_LOADED:Oe("AVV_ERR_PARENT_PLG_LOADED","Impossible to load '%s' plugin because the parent '%s' was already loaded"),AVV_ERR_READY_TIMEOUT:Oe("AVV_ERR_READY_TIMEOUT","Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise")},Xu=function t(e,r,n){r===void 0&&(r=""),n||(n={});var i=function(u){var c={"│":"|","└":"`","├":"+","─":"-","┬":"-"};return n.unicode===!1?c[u]:u};typeof e=="string"&&(e={label:e});var o=e.nodes||[],s=(e.label||"").split(`
|
|
12
12
|
`),a=`
|
|
13
13
|
`+r+(o.length?i("│"):" ")+" ";return r+s.join(a)+`
|
|
14
|
-
`+o.map(function(u,c){var l=c===o.length-1,d=u.nodes&&u.nodes.length,p=r+(l?" ":i("│"))+" ";return r+i(l?"└":"├")+i("─")+i(d?"┬":"─")+" "+t(u,p,n).slice(r.length+2)}).join("")};const Xu
|
|
15
|
-
`).slice(0,2).map(r=>r.trim()).join(" -- ")}function cc(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function Ze(t,e,r,n,i){this.started=!1,this.func=e,this.opts=r,this.onFinish=null,this.parent=t,this.timeout=i===void 0?t._timeout:i,this.name=uc(e,r),this.isAfter=n,this.q=ic(t,lc,1),this.q.pause(),this._error=null,this.loaded=!1,this._promise=null}sc(Ze,oc);Ze.prototype.exec=function(t,e){const r=this.func;let n=!1;const i=this.name;if(this.parent._error&&!this.isAfter){W("skipping loading of plugin as parent errored and it is not an after",i),C.nextTick(e);return}if(this.isAfter)this.server=t;else try{this.server=this.parent.override(t,r,this.opts)}catch(u){return W("override errored",i),e(u)}this.opts=typeof this.opts=="function"?this.opts(this.server):this.opts,W("exec",i);let o;const s=u=>{if(n){W("loading complete",i);return}this._error=u,W(u?"exec errored":"exec completed",i),n=!0,o&&clearTimeout(o),e(u)};this.timeout>0&&(W("setting up timeout",i,this.timeout),o=setTimeout(function(){W("timed out",i),o=null;const u=new ac(i);u.fn=r,s(u)},this.timeout)),this.started=!0,this.emit("start",this.server?this.server.name:null,this.name,Date.now());const a=r(this.server,this.opts,s);a&&typeof a.then=="function"&&(W("exec: resolving promise",i),a.then(()=>C.nextTick(s),u=>C.nextTick(s,u)))};Ze.prototype.loadedSoFar=function(){if(this.loaded)return Promise.resolve();const t=()=>{this.server.after((r,n)=>{this._error=r,this.q.pause(),r?(W("rejecting promise",this.name,r),this._promise.reject(r)):(W("resolving promise",this.name),this._promise.resolve()),this._promise=null,C.nextTick(n,r)}),this.q.resume()};let e;return this._promise?e=Promise.resolve():(this._promise=cc(),e=this._promise.promise,this.server?t():this.on("start",t)),e};Ze.prototype.enqueue=function(t,e){W("enqueue",this.name,t.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.q.push(t,e)};Ze.prototype.finish=function(t,e){W("finish",this.name,t);const r=()=>{this.loaded||(W("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,e(t))};if(t){this._promise&&(this._promise.reject(t),this._promise=null),r();return}const n=()=>{if(W("check",this.name,this.q.length(),this.q.running(),this._promise),this.q.length()===0&&this.q.running()===0)if(this._promise){const i=()=>{W("wrap"),queueMicrotask(n)};this._promise.resolve(),this._promise.promise.then(i,i),this._promise=null}else r();else W("delayed",this.name),this.q.drain=()=>{W("drain",this.name),this.q.drain=dc,queueMicrotask(n)}};queueMicrotask(n),this.q.resume()};function lc(t,e){const r=this;C.nextTick(Vr.bind(r),t,e)}function Vr(t,e){if(typeof t.func.then=="function"){t.func.then(n=>{typeof n.default=="function"&&(n=n.default),t.func=n,Vr.call(this,t,e)},e);return}const r=this._current[0];this._current.unshift(t),t.exec(r&&r.server||this._server,n=>{t.finish(n,i=>{this._current.shift(),e(i)})})}function dc(){}Ur.exports=Ze;Ur.exports.loadPlugin=Vr;var pc=Ur.exports;const Fn=ui,fc=yi.EventEmitter,hc=Ft.inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:nr,AVV_ERR_CALLBACK_NOT_FN:nt,AVV_ERR_PLUGIN_NOT_VALID:mc,AVV_ERR_ROOT_PLG_BOOTED:gc,AVV_ERR_READY_TIMEOUT:yc}=Di,bc=ec,Sr=pc,Je=Fi("avvio"),Pt=Symbol("kAvvio"),ir=Symbol("kThenifyDoNotWrap");function vc(t,e,r){const n=e.expose||{},i=n.use||"use",o=n.after||"after",s=n.ready||"ready",a=n.onClose||"onClose",u=n.close||"close";if(t[i])throw new nr(i);if(t[o])throw new nr(o);if(t[s])throw new nr(s);t[i]=function(c,l){return r.use(c,l),this},Object.defineProperty(t,"then",{get:Ui.bind(r)}),t[Pt]=!0,t[o]=function(c){return typeof c!="function"?r._loadRegistered():(r.after(or(c,this)),this)},t[s]=function(c){if(c&&typeof c!="function")throw new nt(s,typeof c);return r.ready(c?or(c,this):void 0)},t[a]=function(c){if(typeof c!="function")throw new nt(a,typeof c);return r.onClose(Ec(c,this)),this},t[u]=function(c){if(c&&typeof c!="function")throw new nt(u,typeof c);return c?(r.close(or(c,this)),this):r.close()}}function H(t,e,r){if(typeof t=="function"&&arguments.length===1&&(r=t,e={},t=null),typeof e=="function"&&(r=e,e={}),e=e||{},!(this instanceof H)){const n=new H(t,e,r);return t&&vc(t,e,n),n}e.autostart!==!1&&(e.autostart=!0),t=t||this,this._timeout=Number(e.timeout)||0,this._server=t,this._current=[],this._error=null,this._isOnCloseHandlerKey=Symbol("isOnCloseHandler"),this._lastUsed=null,this.setMaxListeners(0),r&&this.once("start",r),this.started=!1,this.booted=!1,this.pluginTree=new bc,this._readyQ=Fn(this,Vi,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=Un},this._closeQ=Fn(this,wc,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=Un},this._doStart=null,this._root=new Sr(this,Tc.bind(this),e,!1,0),this._root.once("start",(n,i,o)=>{const s=this.pluginTree.start(null,i,o);this._root.once("loaded",(a,u,c)=>{this.pluginTree.stop(s,c)})}),Sr.loadPlugin.call(this,this._root,n=>{Je("root plugin ready");try{this.emit("preReady"),this._root=null}catch(i){n=n||this._error||i}if(n){if(this._error=n,this._readyQ.length()===0)throw n}else this.booted=!0;this._readyQ.resume()})}function Tc(t,e,r){this._doStart=r,e.autostart&&this.start()}hc(H,fc);H.prototype.start=function(){return this.started=!0,C.nextTick(this._doStart),this};H.prototype.override=function(t,e,r){return t};function Sc(t){if(t&&typeof t=="object"&&typeof t.default=="function"&&(t=t.default),!(t&&(typeof t=="function"||typeof t.then=="function")))throw new mc(typeof t);return t}H.prototype[Pt]=!0;H.prototype.use=function(t,e){return this._lastUsed=this._addPlugin(t,e,!1),this};H.prototype._loadRegistered=function(){const t=this._current[0];return!this.started&&!this.booted&&C.nextTick(()=>this._root.q.resume()),t?t.loadedSoFar():Promise.resolve()};Object.defineProperty(H.prototype,"then",{get:Ui});H.prototype._addPlugin=function(t,e,r){if(t=Sc(t),e=e||{},this.booted)throw new gc;const n=this._current[0],i=new Sr(this,t,e,r);if(i.once("start",(o,s,a)=>{const u=this.pluginTree.start(n.name,s,a);i.once("loaded",(c,l,d)=>{this.pluginTree.stop(u,d)})}),n.loaded)throw new Error(i.name,n.name);return n.enqueue(i,o=>{o&&(this._error=o)}),i};H.prototype.after=function(t){if(!t)return this._loadRegistered();this._addPlugin(e.bind(this),{},!0);function e(r,n,i){Vi.call(this,t,i)}return this};H.prototype.onClose=function(t){if(typeof t!="function")throw new Error("not a function");t[this._isOnCloseHandlerKey]=!0,this._closeQ.unshift(t,e.bind(this));function e(r){r&&(this._error=r)}return this};H.prototype.close=function(t){let e;if(t){if(typeof t!="function")throw new nt("close",typeof t)}else e=new Promise(function(r,n){t=function(i){if(i)return n(i);r()}});return this.ready(()=>{this._error=null,this._closeQ.push(t),C.nextTick(this._closeQ.resume.bind(this._closeQ))}),e};H.prototype.ready=function(t){if(t){if(typeof t!="function")throw new nt("ready",typeof t);this._readyQ.push(t),queueMicrotask(this.start.bind(this));return}return new Promise((e,r)=>{this._readyQ.push(i),this.start();const n=this._current[0].server;function i(o,s,a){o?r(o):e(n),C.nextTick(a)}})};H.prototype.prettyPrint=function(){return this.pluginTree.prittyPrint()};H.prototype.toJSON=function(){return this.pluginTree.toJSON()};function Un(){}function Ui(){if(this.booted){Je("thenify returning null because we are already booted");return}if(this[ir]){this[ir]=!1;return}return Je("thenify"),(t,e)=>this._loadRegistered().then(()=>(this[ir]=!0,t(this._server)),e)}function Vi(t,e){const r=this._server,n=this._error;let i;if(this._error=null,t.length===0)this._error=n,i=t(),i&&!i[Pt]&&typeof i.then=="function"?i.then(()=>C.nextTick(e),o=>C.nextTick(e,o)):C.nextTick(e);else if(t.length===1)i=t(n),i&&!i[Pt]&&typeof i.then=="function"?i.then(()=>C.nextTick(e),o=>C.nextTick(e,o)):C.nextTick(e);else if(this._timeout===0){const o=s=>{this._error=s,e(this._error)};t.length===2?t(n,o):t(n,r,o)}else Ac.call(this,t,n,r,e)}function Ac(t,e,r,n){const i=t.name;Je("setting up ready timeout",i,this._timeout);let o=setTimeout(()=>{Je("timed out",i),o=null;const a=new yc(i);a.fn=t,this._error=a,n(a)},this._timeout);t.length===2?t(e,s.bind(this)):t(e,r,s.bind(this));function s(a){o&&(clearTimeout(o),this._error=a,n(this._error))}}function wc(t,e){const r=this._server,n=t[this._isOnCloseHandlerKey];if(t.length===0||t.length===1){let i;n?i=t(r):i=t(this._error),i&&typeof i.then=="function"?(Je("resolving close/onClose promise"),i.then(()=>C.nextTick(e),o=>C.nextTick(e,o))):C.nextTick(e)}else t.length===2?t(n?r:this._error,e):n?t(r,e):t(this._error,r,e)}function Ec(t,e){return r.bind(e);function r(n,i){let o;t.length===0?(o=t(),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t.length===1?(o=t(this),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t(this,i)}}function or(t,e){return r.bind(e);function r(n,i){let o;t?t.length===0?(o=t(),o&&o.then?o.then(function(){C.nextTick(i,n)},i):C.nextTick(i,n)):t.length===1?(o=t(n),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t.length===2?t(n,i):t(n,this,i):C.nextTick(i)}}Ir.exports=H;Ir.exports.express=function(t){return H(t,{expose:{use:"load"}})};var Ic=Ir.exports;const Oc=ea(Ic);(function(){if(window.requestAnimationFrame&&window.cancelAnimationFrame)return;const t=["webkit","moz","ms","o"];for(const e of t)window.requestAnimationFrame=window.requestAnimationFrame||window[`${e}RequestAnimationFrame`],window.cancelAnimationFrame=window.cancelAnimationFrame||window[`${e}CancelAnimationFrame`]||window[`${e}CancelRequestAnimationFrame`];if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){let e=0;const r=!!(window.performance&&window.performance.now);window.requestAnimationFrame=function(n){const i=r?window.performance.now():new Date().getTime(),o=Math.max(0,16-(i-e)),s=window.setTimeout(function(){n(i+o)},o);return e=i+o,s},window.cancelAnimationFrame=clearTimeout}})();function kc(t,e=!0,r=!0,n={friendsTab:"enabled"}){const i=e?"https://grpc-sdk.streamlayer.io:443":"https://grpc-sdk.next.streamlayer.io:443",o=e?"https://grpc.streamlayer.io:443":"https://grpc.next.streamlayer.io:443",s=Oc(Object.create({}),{autostart:!1});return s.use(os,{hideFriends:n.hideFriends,skipOnboarding:n.skipOnboarding,betPack:n.betPack,friendsTab:n.friendsTab,theme:n.theme,themeMode:n.themeMode}),s.use(Xo,{onDeepLinkHandled:n?.onDeepLinkHandled}),s.use(rs,{videoPlayerController:n?.videoPlayerController}),s.use(is,{onContentActivate:n?.onContentActivate,withAd:n?.withAd,withAdNotification:n?.withAdNotification}),s.use(bo,{sdkKey:t,host:i,analyticsHost:o,version:n?.version,webOS:n?.webOS}),s.use(wo),s.use(ts),s.use(gs),s.use(Go),s.use(Zs),s.use(Ts),s.use($s),s.after((a,u,c)=>{if(a)throw a;u.ready(),c()}),r&&s.after(async(a,u,c)=>{if(a)throw a;await u.sdk.initializeApp(),c()}),s.onClose(()=>{console.log("close StreamLayer instance")}),s}exports.StreamLayer=kc;
|
|
14
|
+
`+o.map(function(u,c){var l=c===o.length-1,d=u.nodes&&u.nodes.length,p=r+(l?" ":i("│"))+" ";return r+i(l?"└":"├")+i("─")+i(d?"┬":"─")+" "+t(u,p,n).slice(r.length+2)}).join("")};const Ju=Xu,Pn=Symbol("avvio.TimeTree.untrackNode"),er=Symbol("avvio.TimeTree.trackNode"),Ln=Symbol("avvio.TimeTree.getParent"),Rn=Symbol("avvio.TimeTree.getNode"),_n=Symbol("avvio.TimeTree.addNode");let Zu=class{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[er](e){this.tableId.set(e.id,e),this.tableLabel.has(e.label)?this.tableLabel.get(e.label).push(e):this.tableLabel.set(e.label,[e])}[Pn](e){this.tableId.delete(e.id);const r=this.tableLabel.get(e.label);if(r.id){this.tableLabel.delete(e.label);return}r.pop(),r.length===0&&this.tableLabel.delete(e.label)}[Ln](e){if(e===null)return this.root;const r=this.tableLabel.get(e);return r.id?r:r[r.length-1]}[Rn](e){return this.tableId.get(e)}[_n](e,r,n){if(e===null)return this.root={id:"root",label:r,start:n,nodes:[]},this[er](this.root),this.root.id;const o=this[Ln](e),s=`${r}-${Math.random()}`,a={id:s,parent:e,start:n,label:r,nodes:[]};return o.nodes.push(a),this[er](a),s}start(e,r,n=Date.now()){return this[_n](e,r,n)}stop(e,r=Date.now()){const n=this[Rn](e);n&&(n.stop=r,n.diff=n.stop-n.start||0,this[Pn](n))}toJSON(){return Object.assign({},this.root)}prittyPrint(){const e=n=>(n.label=`${n.label} ${n.diff} ms`,n.nodes.length>0&&(n.nodes=n.nodes.map(i=>e(i))),n),r=e(this.toJSON());return Ju(r)}};var ec=Zu,Ur={exports:{}},Tr={exports:{}},tr,Dn;function tc(){if(Dn)return tr;Dn=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,o=n*365.25;tr=function(l,d){d=d||{};var p=typeof l;if(p==="string"&&l.length>0)return s(l);if(p==="number"&&isFinite(l))return d.long?u(l):a(l);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(l))};function s(l){if(l=String(l),!(l.length>100)){var d=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(l);if(d){var p=parseFloat(d[1]),g=(d[2]||"ms").toLowerCase();switch(g){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*i;case"days":case"day":case"d":return p*n;case"hours":case"hour":case"hrs":case"hr":case"h":return p*r;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function a(l){var d=Math.abs(l);return d>=n?Math.round(l/n)+"d":d>=r?Math.round(l/r)+"h":d>=e?Math.round(l/e)+"m":d>=t?Math.round(l/t)+"s":l+"ms"}function u(l){var d=Math.abs(l);return d>=n?c(l,d,n,"day"):d>=r?c(l,d,r,"hour"):d>=e?c(l,d,e,"minute"):d>=t?c(l,d,t,"second"):l+" ms"}function c(l,d,p,g){var T=d>=p*1.5;return Math.round(l/p)+" "+g+(T?"s":"")}return tr}function rc(t){r.debug=r,r.default=r,r.coerce=u,r.disable=s,r.enable=i,r.enabled=a,r.humanize=tc(),r.destroy=c,Object.keys(t).forEach(l=>{r[l]=t[l]}),r.names=[],r.skips=[],r.formatters={};function e(l){let d=0;for(let p=0;p<l.length;p++)d=(d<<5)-d+l.charCodeAt(p),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=e;function r(l){let d,p=null,g,T;function y(...E){if(!y.enabled)return;const O=y,w=Number(new Date),I=w-(d||w);O.diff=I,O.prev=d,O.curr=w,d=w,E[0]=r.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let P=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(q,_)=>{if(q==="%%")return"%";P++;const oe=r.formatters[_];if(typeof oe=="function"){const se=E[P];q=oe.call(O,se),E.splice(P,1),P--}return q}),r.formatArgs.call(O,E),(O.log||r.log).apply(O,E)}return y.namespace=l,y.useColors=r.useColors(),y.color=r.selectColor(l),y.extend=n,y.destroy=r.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(g!==r.namespaces&&(g=r.namespaces,T=r.enabled(l)),T),set:E=>{p=E}}),typeof r.init=="function"&&r.init(y),y}function n(l,d){const p=r(this.namespace+(typeof d>"u"?":":d)+l);return p.log=this.log,p}function i(l){r.save(l),r.namespaces=l,r.names=[],r.skips=[];const d=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of d)p[0]==="-"?r.skips.push(p.slice(1)):r.names.push(p)}function o(l,d){let p=0,g=0,T=-1,y=0;for(;p<l.length;)if(g<d.length&&(d[g]===l[p]||d[g]==="*"))d[g]==="*"?(T=g,y=p,g++):(p++,g++);else if(T!==-1)g=T+1,y++,p=y;else return!1;for(;g<d.length&&d[g]==="*";)g++;return g===d.length}function s(){const l=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),l}function a(l){for(const d of r.skips)if(o(l,d))return!1;for(const d of r.names)if(o(l,d))return!0;return!1}function u(l){return l instanceof Error?l.stack||l.message:l}function c(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var nc=rc;(function(t,e){e.formatArgs=n,e.save=i,e.load=o,e.useColors=r,e.storage=s(),e.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let u;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(u=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(u[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const c="color: "+this.color;u.splice(1,0,c,"color: inherit");let l=0,d=0;u[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(l++,p==="%c"&&(d=l))}),u.splice(d,0,c)}e.log=console.debug||console.log||(()=>{});function i(u){try{u?e.storage.setItem("debug",u):e.storage.removeItem("debug")}catch{}}function o(){let u;try{u=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!u&&typeof C<"u"&&"env"in C&&(u=C.env.DEBUG),u}function s(){try{return localStorage}catch{}}t.exports=nc(e);const{formatters:a}=t.exports;a.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(Tr,Tr.exports);var Fi=Tr.exports;const ic=ui,oc=yi.EventEmitter,sc=Ft.inherits,W=Fi("avvio"),{AVV_ERR_READY_TIMEOUT:ac}=Di,rr=Symbol.for("plugin-meta");function uc(t,e){return t[rr]&&t[rr].name?t[rr].name:typeof e<"u"&&typeof e!="function"&&e.name?e.name:t.name?t.name:t.toString().split(`
|
|
15
|
+
`).slice(0,2).map(r=>r.trim()).join(" -- ")}function cc(){const t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function Ze(t,e,r,n,i){this.started=!1,this.func=e,this.opts=r,this.onFinish=null,this.parent=t,this.timeout=i===void 0?t._timeout:i,this.name=uc(e,r),this.isAfter=n,this.q=ic(t,lc,1),this.q.pause(),this._error=null,this.loaded=!1,this._promise=null}sc(Ze,oc);Ze.prototype.exec=function(t,e){const r=this.func;let n=!1;const i=this.name;if(this.parent._error&&!this.isAfter){W("skipping loading of plugin as parent errored and it is not an after",i),C.nextTick(e);return}if(this.isAfter)this.server=t;else try{this.server=this.parent.override(t,r,this.opts)}catch(u){return W("override errored",i),e(u)}this.opts=typeof this.opts=="function"?this.opts(this.server):this.opts,W("exec",i);let o;const s=u=>{if(n){W("loading complete",i);return}this._error=u,W(u?"exec errored":"exec completed",i),n=!0,o&&clearTimeout(o),e(u)};this.timeout>0&&(W("setting up timeout",i,this.timeout),o=setTimeout(function(){W("timed out",i),o=null;const u=new ac(i);u.fn=r,s(u)},this.timeout)),this.started=!0,this.emit("start",this.server?this.server.name:null,this.name,Date.now());const a=r(this.server,this.opts,s);a&&typeof a.then=="function"&&(W("exec: resolving promise",i),a.then(()=>C.nextTick(s),u=>C.nextTick(s,u)))};Ze.prototype.loadedSoFar=function(){if(this.loaded)return Promise.resolve();const t=()=>{this.server.after((r,n)=>{this._error=r,this.q.pause(),r?(W("rejecting promise",this.name,r),this._promise.reject(r)):(W("resolving promise",this.name),this._promise.resolve()),this._promise=null,C.nextTick(n,r)}),this.q.resume()};let e;return this._promise?e=Promise.resolve():(this._promise=cc(),e=this._promise.promise,this.server?t():this.on("start",t)),e};Ze.prototype.enqueue=function(t,e){W("enqueue",this.name,t.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.q.push(t,e)};Ze.prototype.finish=function(t,e){W("finish",this.name,t);const r=()=>{this.loaded||(W("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,e(t))};if(t){this._promise&&(this._promise.reject(t),this._promise=null),r();return}const n=()=>{if(W("check",this.name,this.q.length(),this.q.running(),this._promise),this.q.length()===0&&this.q.running()===0)if(this._promise){const i=()=>{W("wrap"),queueMicrotask(n)};this._promise.resolve(),this._promise.promise.then(i,i),this._promise=null}else r();else W("delayed",this.name),this.q.drain=()=>{W("drain",this.name),this.q.drain=dc,queueMicrotask(n)}};queueMicrotask(n),this.q.resume()};function lc(t,e){const r=this;C.nextTick(Vr.bind(r),t,e)}function Vr(t,e){if(typeof t.func.then=="function"){t.func.then(n=>{typeof n.default=="function"&&(n=n.default),t.func=n,Vr.call(this,t,e)},e);return}const r=this._current[0];this._current.unshift(t),t.exec(r&&r.server||this._server,n=>{t.finish(n,i=>{this._current.shift(),e(i)})})}function dc(){}Ur.exports=Ze;Ur.exports.loadPlugin=Vr;var pc=Ur.exports;const Fn=ui,fc=yi.EventEmitter,hc=Ft.inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:nr,AVV_ERR_CALLBACK_NOT_FN:nt,AVV_ERR_PLUGIN_NOT_VALID:mc,AVV_ERR_ROOT_PLG_BOOTED:gc,AVV_ERR_READY_TIMEOUT:yc}=Di,bc=ec,Sr=pc,Xe=Fi("avvio"),Lt=Symbol("kAvvio"),ir=Symbol("kThenifyDoNotWrap");function vc(t,e,r){const n=e.expose||{},i=n.use||"use",o=n.after||"after",s=n.ready||"ready",a=n.onClose||"onClose",u=n.close||"close";if(t[i])throw new nr(i);if(t[o])throw new nr(o);if(t[s])throw new nr(s);t[i]=function(c,l){return r.use(c,l),this},Object.defineProperty(t,"then",{get:Ui.bind(r)}),t[Lt]=!0,t[o]=function(c){return typeof c!="function"?r._loadRegistered():(r.after(or(c,this)),this)},t[s]=function(c){if(c&&typeof c!="function")throw new nt(s,typeof c);return r.ready(c?or(c,this):void 0)},t[a]=function(c){if(typeof c!="function")throw new nt(a,typeof c);return r.onClose(Ec(c,this)),this},t[u]=function(c){if(c&&typeof c!="function")throw new nt(u,typeof c);return c?(r.close(or(c,this)),this):r.close()}}function H(t,e,r){if(typeof t=="function"&&arguments.length===1&&(r=t,e={},t=null),typeof e=="function"&&(r=e,e={}),e=e||{},!(this instanceof H)){const n=new H(t,e,r);return t&&vc(t,e,n),n}e.autostart!==!1&&(e.autostart=!0),t=t||this,this._timeout=Number(e.timeout)||0,this._server=t,this._current=[],this._error=null,this._isOnCloseHandlerKey=Symbol("isOnCloseHandler"),this._lastUsed=null,this.setMaxListeners(0),r&&this.once("start",r),this.started=!1,this.booted=!1,this.pluginTree=new bc,this._readyQ=Fn(this,Vi,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=Un},this._closeQ=Fn(this,wc,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=Un},this._doStart=null,this._root=new Sr(this,Tc.bind(this),e,!1,0),this._root.once("start",(n,i,o)=>{const s=this.pluginTree.start(null,i,o);this._root.once("loaded",(a,u,c)=>{this.pluginTree.stop(s,c)})}),Sr.loadPlugin.call(this,this._root,n=>{Xe("root plugin ready");try{this.emit("preReady"),this._root=null}catch(i){n=n||this._error||i}if(n){if(this._error=n,this._readyQ.length()===0)throw n}else this.booted=!0;this._readyQ.resume()})}function Tc(t,e,r){this._doStart=r,e.autostart&&this.start()}hc(H,fc);H.prototype.start=function(){return this.started=!0,C.nextTick(this._doStart),this};H.prototype.override=function(t,e,r){return t};function Sc(t){if(t&&typeof t=="object"&&typeof t.default=="function"&&(t=t.default),!(t&&(typeof t=="function"||typeof t.then=="function")))throw new mc(typeof t);return t}H.prototype[Lt]=!0;H.prototype.use=function(t,e){return this._lastUsed=this._addPlugin(t,e,!1),this};H.prototype._loadRegistered=function(){const t=this._current[0];return!this.started&&!this.booted&&C.nextTick(()=>this._root.q.resume()),t?t.loadedSoFar():Promise.resolve()};Object.defineProperty(H.prototype,"then",{get:Ui});H.prototype._addPlugin=function(t,e,r){if(t=Sc(t),e=e||{},this.booted)throw new gc;const n=this._current[0],i=new Sr(this,t,e,r);if(i.once("start",(o,s,a)=>{const u=this.pluginTree.start(n.name,s,a);i.once("loaded",(c,l,d)=>{this.pluginTree.stop(u,d)})}),n.loaded)throw new Error(i.name,n.name);return n.enqueue(i,o=>{o&&(this._error=o)}),i};H.prototype.after=function(t){if(!t)return this._loadRegistered();this._addPlugin(e.bind(this),{},!0);function e(r,n,i){Vi.call(this,t,i)}return this};H.prototype.onClose=function(t){if(typeof t!="function")throw new Error("not a function");t[this._isOnCloseHandlerKey]=!0,this._closeQ.unshift(t,e.bind(this));function e(r){r&&(this._error=r)}return this};H.prototype.close=function(t){let e;if(t){if(typeof t!="function")throw new nt("close",typeof t)}else e=new Promise(function(r,n){t=function(i){if(i)return n(i);r()}});return this.ready(()=>{this._error=null,this._closeQ.push(t),C.nextTick(this._closeQ.resume.bind(this._closeQ))}),e};H.prototype.ready=function(t){if(t){if(typeof t!="function")throw new nt("ready",typeof t);this._readyQ.push(t),queueMicrotask(this.start.bind(this));return}return new Promise((e,r)=>{this._readyQ.push(i),this.start();const n=this._current[0].server;function i(o,s,a){o?r(o):e(n),C.nextTick(a)}})};H.prototype.prettyPrint=function(){return this.pluginTree.prittyPrint()};H.prototype.toJSON=function(){return this.pluginTree.toJSON()};function Un(){}function Ui(){if(this.booted){Xe("thenify returning null because we are already booted");return}if(this[ir]){this[ir]=!1;return}return Xe("thenify"),(t,e)=>this._loadRegistered().then(()=>(this[ir]=!0,t(this._server)),e)}function Vi(t,e){const r=this._server,n=this._error;let i;if(this._error=null,t.length===0)this._error=n,i=t(),i&&!i[Lt]&&typeof i.then=="function"?i.then(()=>C.nextTick(e),o=>C.nextTick(e,o)):C.nextTick(e);else if(t.length===1)i=t(n),i&&!i[Lt]&&typeof i.then=="function"?i.then(()=>C.nextTick(e),o=>C.nextTick(e,o)):C.nextTick(e);else if(this._timeout===0){const o=s=>{this._error=s,e(this._error)};t.length===2?t(n,o):t(n,r,o)}else Ac.call(this,t,n,r,e)}function Ac(t,e,r,n){const i=t.name;Xe("setting up ready timeout",i,this._timeout);let o=setTimeout(()=>{Xe("timed out",i),o=null;const a=new yc(i);a.fn=t,this._error=a,n(a)},this._timeout);t.length===2?t(e,s.bind(this)):t(e,r,s.bind(this));function s(a){o&&(clearTimeout(o),this._error=a,n(this._error))}}function wc(t,e){const r=this._server,n=t[this._isOnCloseHandlerKey];if(t.length===0||t.length===1){let i;n?i=t(r):i=t(this._error),i&&typeof i.then=="function"?(Xe("resolving close/onClose promise"),i.then(()=>C.nextTick(e),o=>C.nextTick(e,o))):C.nextTick(e)}else t.length===2?t(n?r:this._error,e):n?t(r,e):t(this._error,r,e)}function Ec(t,e){return r.bind(e);function r(n,i){let o;t.length===0?(o=t(),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t.length===1?(o=t(this),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t(this,i)}}function or(t,e){return r.bind(e);function r(n,i){let o;t?t.length===0?(o=t(),o&&o.then?o.then(function(){C.nextTick(i,n)},i):C.nextTick(i,n)):t.length===1?(o=t(n),o&&o.then?o.then(function(){C.nextTick(i)},i):C.nextTick(i)):t.length===2?t(n,i):t(n,this,i):C.nextTick(i)}}Ir.exports=H;Ir.exports.express=function(t){return H(t,{expose:{use:"load"}})};var Ic=Ir.exports;const Oc=ea(Ic);(function(){if(window.requestAnimationFrame&&window.cancelAnimationFrame)return;const t=["webkit","moz","ms","o"];for(const e of t)window.requestAnimationFrame=window.requestAnimationFrame||window[`${e}RequestAnimationFrame`],window.cancelAnimationFrame=window.cancelAnimationFrame||window[`${e}CancelAnimationFrame`]||window[`${e}CancelRequestAnimationFrame`];if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){let e=0;const r=!!(window.performance&&window.performance.now);window.requestAnimationFrame=function(n){const i=r?window.performance.now():new Date().getTime(),o=Math.max(0,16-(i-e)),s=window.setTimeout(function(){n(i+o)},o);return e=i+o,s},window.cancelAnimationFrame=clearTimeout}})();function kc(t,e=!0,r=!0,n={friendsTab:"enabled"}){const i=e?"https://grpc-sdk.streamlayer.io:443":"https://grpc-sdk.next.streamlayer.io:443",o=e?"https://grpc.streamlayer.io:443":"https://grpc.next.streamlayer.io:443",s=Oc(Object.create({}),{autostart:!1});return s.use(os,{hideFriends:n.hideFriends,skipOnboarding:n.skipOnboarding,betPack:n.betPack,friendsTab:n.friendsTab,theme:n.theme,themeMode:n.themeMode}),s.use(Jo,{onDeepLinkHandled:n?.onDeepLinkHandled}),s.use(rs,{videoPlayerController:n?.videoPlayerController}),s.use(is,{onContentActivate:n?.onContentActivate,withAd:n?.withAd,withAdNotification:n?.withAdNotification}),s.use(bo,{sdkKey:t,host:i,analyticsHost:o,version:n?.version,webOS:n?.webOS}),s.use(wo),s.use(ts),s.use(gs),s.use(Go),s.use(Zs),s.use(Ts),s.use($s),s.after((a,u,c)=>{if(a)throw a;u.ready(),c()}),r&&s.after(async(a,u,c)=>{if(a)throw a;await u.sdk.initializeApp(),c()}),s.onClose(()=>{console.log("close StreamLayer instance")}),s}exports.StreamLayer=kc;
|