@streamlayer/sdk-web 1.18.6 → 1.18.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +1 -1
- package/lib/es/index.js +1 -1
- package/lib/{index-BoZVPkJu.js → index-Bqs5eyxf.js} +2839 -2673
- package/lib/{index-B15M-YGv.cjs → index-C05fK_bk.cjs} +1 -1
- package/lib/{index-CfSdnrfA.js → index-D8wyDNJD.js} +1 -1
- package/lib/index-_D2y5RqC.cjs +15 -0
- package/package.json +13 -13
- package/lib/index-Bc5bp7_1.cjs +0 -15
package/lib/index-Bc5bp7_1.cjs
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";const vi=require("pino"),O=require("@streamlayer/sl-eslib/interactive/interactive.common_pb"),ie=require("@streamlayer/sl-eslib/interactive/feed/interactive.feed_pb"),Y=require("@streamlayer/sl-eslib/sdkSettings/sdkSettings.common_pb"),$e=require("@streamlayer/sl-eslib/analytics/v1/invitations/invitations_pb"),ae=require("nanostores"),De=require("uuid"),J=require("@connectrpc/connect"),mr=require("@connectrpc/connect-web"),yr=require("@nanostores/query"),Un=require("@streamlayer/sl-eslib/sports/events/events_pb"),Ge=require("@streamlayer/sl-eslib/sdkSettings/client/client_pb"),sr=require("@streamlayer/sl-eslib/users/users_pb"),Vn=require("@streamlayer/sl-eslib/interactive/leaderboard/interactive.leaderboard_pb"),Me=require("@streamlayer/sl-eslib/sdkSettings/organization/webhooks/organization.webhooks_pb"),bi=require("@streamlayer/sl-eslib/shortLinks/linksClient_pb"),gr=require("@streamlayer/sl-eslib/polymarket/sportsClient_pb"),w=require("@streamlayer/sl-eslib/analytics/v1/common/analytics.common_pb"),xn=require("@streamlayer/sl-eslib/analytics/v2/streaming/streaming_pb"),vr=require("@streamlayer/sl-eslib/analytics/v1/interactions/interactions_pb"),pe=require("@streamlayer/sl-eslib/analytics/v1/notifications/notifications_pb");function Ti(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Bn={exports:{}},ee=Bn.exports={},me,ye;function er(){throw new Error("setTimeout has not been defined")}function tr(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?me=setTimeout:me=er}catch{me=er}try{typeof clearTimeout=="function"?ye=clearTimeout:ye=tr}catch{ye=tr}})();function qn(t){if(me===setTimeout)return setTimeout(t,0);if((me===er||!me)&&setTimeout)return me=setTimeout,setTimeout(t,0);try{return me(t,0)}catch{try{return me.call(null,t,0)}catch{return me.call(this,t,0)}}}function Ai(t){if(ye===clearTimeout)return clearTimeout(t);if((ye===tr||!ye)&&clearTimeout)return ye=clearTimeout,clearTimeout(t);try{return ye(t)}catch{try{return ye.call(null,t)}catch{return ye.call(this,t)}}}var we=[],Ve=!1,Ne,it=-1;function Si(){!Ve||!Ne||(Ve=!1,Ne.length?we=Ne.concat(we):it=-1,we.length&&Mn())}function Mn(){if(!Ve){var t=qn(Si);Ve=!0;for(var e=we.length;e;){for(Ne=we,we=[];++it<e;)Ne&&Ne[it].run();it=-1,e=we.length}Ne=null,Ve=!1,Ai(t)}}ee.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];we.push(new jn(t,e)),we.length===1&&!Ve&&qn(Mn)};function jn(t,e){this.fun=t,this.array=e}jn.prototype.run=function(){this.fun.apply(null,this.array)};ee.title="browser";ee.browser=!0;ee.env={};ee.argv=[];ee.version="";ee.versions={};function Ie(){}ee.on=Ie;ee.addListener=Ie;ee.once=Ie;ee.off=Ie;ee.removeListener=Ie;ee.removeAllListeners=Ie;ee.emit=Ie;ee.prependListener=Ie;ee.prependOnceListener=Ie;ee.listeners=function(t){return[]};ee.binding=function(t){throw new Error("process.binding is not supported")};ee.cwd=function(){return"/"};ee.chdir=function(t){throw new Error("process.chdir is not supported")};ee.umask=function(){return 0};var wi=Bn.exports;const M=Ti(wi),Ei=vi.pino({level:"trace",enabled:typeof window<"u"&&!!window.localStorage.getItem("SL_DEBUG"),browser:{write:t=>{console.log(t)}}}),ue=(t,e)=>Ei.child({name:t},e);class Ii extends Event{slEventBus;constructor(e,n){super(e),this.slEventBus=n}}const Oi=ue("event-bus");class ki{name;listeners;constructor(e="sl-event-bus"){this.name=e,this.listeners=new Set}emit=(e,n)=>{const r=new Ii(this.name,{...n,type:e});Oi.debug(r,"Emitting event"),window.dispatchEvent(r)};listen(e){return window.addEventListener(this.name,e),this.listeners.add(e),()=>{this.off(e)}}off(e){window.removeEventListener(this.name,e),this.listeners.delete(e)}destroy=()=>{this.listeners.forEach(e=>{window.removeEventListener(this.name,e),this.listeners.delete(e)}),this.listeners.clear()}}class Ni{}var Ee;(function(t){t[t.ONBOARDING=1]="ONBOARDING",t[t.QUESTION=2]="QUESTION",t[t.QUESTION_RESOLVED=3]="QUESTION_RESOLVED"})(Ee||(Ee={}));window.slStore=Object.create(null);class ut{store;name;constructor(e,n){this.store=e,this.name=n}getStore(){return this.store}}const Ci=t=>{const e=Object.keys(t);return ae.computed(e.map(n=>t[n].getStore()),(...n)=>Object.fromEntries(e.map((r,i)=>[r,n[i]])))};class Ce extends ut{getValues=()=>this.getStore().get();getValue=e=>this.getStore().get()[e];setValue=(e,n)=>this.getStore().setKey(e,n);subscribe=(...e)=>this.getStore().subscribe(...e);unsubscribe=()=>this.getStore().off()}const se=t=>ae.map(t);var Te;(function(t){t.ORGANIZATION="ORGANIZATION",t.STREAM="STREAM"})(Te||(Te={}));const Ri={[Y.SdkOverlayType.BETTING]:"betting",[Y.SdkOverlayType.GAMES]:"games",[Y.SdkOverlayType.PUBLIC_CHAT]:"publicChat",[Y.SdkOverlayType.TWITTER]:"twitter"};var ke;(function(t){t.Ready="ready",t.Suspended="suspended"})(ke||(ke={}));const Pi=new Set(["equals","clone","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","getType"]);class Qn{status;listeners=new Set;constructor(){this.status=ae.atom(ke.Suspended)}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(ke.Ready)};disable=()=>{this.status.set(ke.Suspended)};fireEvent(e){for(const n of this.listeners.values())try{n.onEvent(e)}catch(r){console.error(r)}}}class Gn{status;source;config;settings;listeners=new Set;settingsKey;constructor({settings:e,...n},r){this.settingsKey=Ri[n.type],this.status=ae.atom(ke.Suspended),this.config=new Ce(se(n),`feature:config:${this.settingsKey}`),this.settingsKey!==void 0&&e?.overlaySettings.case===this.settingsKey?this.settings=new Ce(se(e.overlaySettings.value),`feature:settings:${this.settingsKey}`):this.settings=new Ce(se({}),`feature:settings:${this.settingsKey}`),this.source=r}get featureConfig(){return this.config.getStore()}get featureSettings(){return this.settings.getStore()}registerEventListener(e){this.listeners.add(e)}enable=()=>{this.status.set(ke.Ready)};disable=()=>{this.status.set(ke.Suspended)};setFeatureConfig=({settings:e,...n})=>{let r;for(r in n)this.config.setValue(r,n[r]);if(e?.overlaySettings?.case!==void 0&&e?.overlaySettings.case===this.settingsKey){const i=e.overlaySettings.value;if(i!==void 0){let o;for(o in i)!Pi.has(o)&&i[o]&&this.settings.setValue(o,i[o])}}};update=(e,n)=>{this.source===Te.STREAM&&n===Te.ORGANIZATION||(this.setFeatureConfig(e),this.source=n)};fireEvent(e){for(const n of this.listeners.values())try{n.onEvent(e)}catch(r){console.error(r)}}}class le extends ut{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 Z=t=>ae.atom(t);class fe extends ut{atomStore;pendingGetValue=null;constructor(e,n,r){super(e,`api:${n}`),this.atomStore=ae.atom(),r&&e.subscribe(i=>{const o=this.atomStore.get(),s=r(i,o);o!==s&&this.atomStore.set(s)})}getAtomStore=()=>this.atomStore;isEnabled=()=>this.getStore().key!==void 0;getValue=()=>{const e=this.getStore(),n=async()=>(await e.fetch())?.data??e.get().data;return e.key?n():this.pendingGetValue?this.pendingGetValue:(this.pendingGetValue=new Promise((r,i)=>{let o=!1,s=null;const a=setTimeout(()=>{o||(o=!0,s?.(),this.pendingGetValue=null,console.warn(`[ApiStore.getValue] ${this.name}: timed out waiting for store key`),r(void 0))},1e3);s=e.listen(()=>{!e.key||o||(o=!0,clearTimeout(a),s?.(),this.pendingGetValue=null,n().then(r,i))}),o?s():e.key&&(o=!0,clearTimeout(a),s(),this.pendingGetValue=null,n().then(r,i))}),this.pendingGetValue)};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 K=new ki;async function*Li(t,e){for await(const n of e){t.response.message=n,t.received_at=Date.now(),t.id=Date.now();const r={type:"__GRPC_DEVTOOLS_EXTENSION__",data:t};window.postMessage(r),yield n}}const _i=()=>t=>async e=>{const n={id:Date.now(),name:e.url,stream:e.stream,sent_at:Date.now(),request:{header:Object.fromEntries(e.header.entries()),message:e.message},response:{}};try{window.postMessage({type:"__GRPC_DEVTOOLS_EXTENSION__",data:n})}catch(r){console.log("devtools error",r)}try{const r=await t(e);if(n.received_at=Date.now(),n.response.header=Object.fromEntries(r.header.entries()),n.response.trailer=Object.fromEntries(r.trailer.entries()),e.stream){const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:{...n,stream:!0}};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}return{...r,message:Li(n,r.message)}}else{n.response.message=r.message,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}}return r}catch(r){n.received_at=Date.now(),n.response.trailer={"grpc-status":r.code,"grpc-message":r.rawMessage},n.response.message=r.rawMessage,n.latency=n.received_at-n.sent_at;const i={type:"__GRPC_DEVTOOLS_EXTENSION__",data:n};try{window.postMessage(i)}catch(o){console.log("devtools error",o)}throw r}};window.dispatchEvent(new CustomEvent("grpc_devtools_loaded"));function Wn(t){return t instanceof DOMException&&(t.code===22||t.code===1014||t.name==="QuotaExceededError"||t.name==="NS_ERROR_DOM_QUOTA_REACHED")}class Be{delimiter=":";prefix;storage;constructor(e="main",n=window.localStorage){this.prefix=`sl-sdk${this.delimiter}${e}`,this.storage=n}clear=()=>{for(const e in window.localStorage)e.startsWith(this.prefix)&&this.storage.removeItem(e)};generateKey=e=>`${this.prefix}${this.delimiter}${e.join(this.delimiter)}`;write=(...e)=>{const n=e.pop()||"",r=this.generateKey(e);try{this.storage.setItem(r,n)}catch(i){Wn(i)&&this.storage===window.sessionStorage&&(window.sessionStorage.removeItem("slstreamlogs"),this.storage.setItem(r,n))}};read=(...e)=>{const n=this.storage.getItem(this.generateKey(e));return n===null?void 0:n};remove=(...e)=>{this.storage.removeItem(this.generateKey(e))}}var de;(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"})(de||(de={}));const br=ue("grpc:stream");class Di{params;streamCancel;method;options;headers;listeners;state;store;paramsListener;reconnectTimeout;attempt=0;constructor(e,n,r,i){const o={status:de.Init,ts:new Date,log:[]};this.state=new Ce(se(o),`subscription:${i.name}:state`),this.options={...i,reconnectDelay:i.reconnectDelay??1e3,reconnectMaxDelay:i.reconnectMaxDelay??3e4,reconnectMaxAttempts:i.reconnectMaxAttempts??10,withStore:i.withStore??!1},this.headers=e,this.listeners=new Map,this.params=r,this.method=n,i.withStore&&(this.store=new le(Z(null),`subscription:${i.name}:store`)),"subscribe"in r&&typeof r.subscribe=="function"&&(this.paramsListener=r.subscribe(s=>{this.state.getValue("status")===de.Connected&&(this.addStateLog(`params updated, reconnect => ${JSON.stringify(s)}`),this.reconnect())})),this.updateState(de.Ready)}updateState=e=>{this.state.setValue("status",e),this.state.setValue("ts",new Date),this.addStateLog(`status => ${e}`)};addStateLog=e=>{const n=this.state.getStore().get().log,r=`${this.options.name} ${new Date().toISOString()}: ${e}`;if(n.push(r),this.state.setValue("log",n),localStorage.getItem("SL_DEBUG")){e.startsWith("received data")?br.trace({name:this.options.name,attempt:this.attempt},"received data"):br.trace({name:this.options.name,attempt:this.attempt},e);try{window.sessionStorage.setItem("slstreamlogs",window.sessionStorage.getItem("slstreamlogs")+`
|
|
2
|
-
`+r)}catch(i){Wn(i)&&window.sessionStorage.removeItem("slstreamlogs"),window.sessionStorage.setItem("slstreamlogs",r)}}};addListener=(e,n)=>this.listeners.has(e)?(this.addStateLog(`listener '${e}' not added, already exists`),()=>{}):(this.listeners.set(e,n),this.addStateLog(`listener '${e}' added`),()=>this.removeListener(e));removeListener=e=>{this.listeners.delete(e),this.addStateLog(`listener '${e}' removed`)};connect=()=>{this.updateState(de.Connecting),this.streamCancel&&(this.addStateLog("disconnect prev connection"),this.streamCancel.abort(),this.streamCancel=void 0);const e="get"in this.params&&typeof this.params.get=="function"?this.params.get():this.params;(async()=>{this.streamCancel=new AbortController;try{const r={headers:this.headers.getValues(),signal:this.streamCancel.signal},i=this.method(e,r);for await(const o of i)this.attempt=0,this.onData(o)}catch(r){r instanceof J.ConnectError&&r.code!=J.Code.Canceled&&this.onStreamError(r)}})(),this.updateState(de.Connected)};disconnect=()=>{this.streamCancel&&this.streamCancel.abort(),this.listeners.clear(),this.paramsListener?.(),clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.updateState(de.Disconnected)};reconnect=()=>{if(this.reconnectTimeout)this.addStateLog("already reconnecting");else if(this.attempt<this.options.reconnectMaxAttempts){this.updateState(de.Reconnect);const e=Math.min(this.options.reconnectMaxDelay,Math.pow(2,this.attempt)*this.options.reconnectDelay),n=Math.round(e*(1+Math.random())/2);this.reconnectTimeout=setTimeout(()=>{this.attempt++,this.updateState(de.Reconnecting),this.addStateLog(`reconnect attempt ${this.attempt} after ${n}ms`),this.connect(),this.reconnectTimeout=void 0},n)}else this.addStateLog("max reconnect attempts reached"),this.disconnect()};getStore=()=>this.store?.getStore();onData=e=>{try{this.addStateLog(`received data => ${JSON.stringify(e)}`),this.store&&this.store.setValue(e);for(const[,n]of this.listeners)n(e);this.addStateLog(`data routed to ${this.listeners.size} listeners`)}catch(n){this.addStateLog(`error process data => ${n}`)}};onStreamError=e=>{if(this.addStateLog(`error => ${e?JSON.stringify(e):"undefined"}}`),e!==void 0){if(e instanceof J.ConnectError&&e.code!==J.Code.Canceled){this.updateState(de.Failed),this.state.setValue("error",e),e.code===J.Code.Unknown&&e.cause==="missing trailer"&&(this.attempt=0),this.reconnect();return}this.disconnect()}}}const Fi=new Set([J.Code.Unknown,J.Code.Internal,J.Code.DeadlineExceeded,J.Code.ResourceExhausted,J.Code.FailedPrecondition,J.Code.Unavailable,J.Code.DataLoss]),Ui=new Set(["An attempt was made to perform an operation that is not permitted: HttpStatusError: invalid SDK key"]),Tr=ue("grpc:retry"),Vi=t=>async e=>{const n=e.contextValues.get(rr.retryAttempts),r=300,i=e.contextValues.get(rr.retryDelay);if(e.stream||n===0)return t(e);Tr.trace({url:e.url,attempts:n,maxDelay:i},"retry options");for(let o=0;;o++)try{return await t(e)}catch(s){Tr.trace({attempt:o,error:s,url:e.url},"retry attempt");const a=J.ConnectError.from(s);if(o>=n||!(a instanceof J.ConnectError)||!Fi.has(a.code)||Ui.has(a.rawMessage))throw s;const u=Math.min(i,Math.pow(2,o)*r),c=Math.round(u*(1+Math.random())/2);await new Promise(l=>setTimeout(l,c))}},rr={retryAttempts:J.createContextKey(10,{description:"Number of attempts to retry"}),retryDelay:J.createContextKey(3e4,{description:"Max delay between retries in milliseconds"})},xi=()=>{const t=localStorage.getItem("sl-device-id");if(t)return t;const e=De.v4();return localStorage.setItem("sl-device-id",e),e},Bi=()=>navigator.userAgentData?.platform||navigator.platform,qi=t=>t?"webOS":navigator.userAgentData&&navigator.userAgentData.mobile||"ontouchstart"in window||navigator.maxTouchPoints>0?"mobile-web":"desktop-web";class Ar{toJsonOptions={emitDefaultValues:!1,enumAsInteger:!0,useProtoFieldName:!1};transport;streamTransport;nanoquery;host;$headers;storeCache;interceptors=[];clients;streamClients;subscriptions;opts;constructor(e,n){this.host=e,this.opts=n,this.$headers=new Ce(se({"sl-device-id":xi(),"sl-device-os":Bi(),"sl-platform":qi(n?.webOS)}),"transport:headers"),this.initInterceptors(),this.clients=new Map,this.streamClients=new Map,this.subscriptions=new Map,this.storeCache=new Map;const[r,i,o]=yr.nanoquery({dedupeTime:n?.dedupeTime,revalidateInterval:n?.refetchInterval});this.nanoquery={createFetcherStore:r,createMutatorStore:i,utils:o},this.transport=mr.createGrpcWebTransport({baseUrl:e,defaultTimeoutMs:1e4,interceptors:this.interceptors}),this.streamTransport=mr.createGrpcWebTransport({baseUrl:e,interceptors:this.interceptors})}addSubscription=(e,n,r)=>{const i=this.subscriptions.get(n);if(i)return i;const o=new Di(this.$headers,e,n,r);return this.subscriptions.set(n,o),o};removeSubscription=e=>{e.disconnect(),this.subscriptions.delete(e.params)};disconnect=()=>{for(const[i,o]of this.subscriptions)o.disconnect(),this.subscriptions.delete(i);this.clients.clear(),this.streamClients.clear(),this.subscriptions.clear();const[e,n,r]=yr.nanoquery({dedupeTime:this.opts?.dedupeTime,revalidateInterval:this.opts?.refetchInterval});this.nanoquery={createFetcherStore:e,createMutatorStore:n,utils:r}};registerInterceptor=e=>{this.interceptors.push(e)};removeInterceptor=e=>{this.interceptors=this.interceptors.filter(n=>n!==e)};getClient=e=>{const n=e.typeName;if(this.clients.has(n))return this.clients.get(n);const r=J.createClient(e,this.transport);return this.clients.set(n,r),r};getStreamClient=e=>{const n=`stream-${e.typeName}`;if(this.clients.has(n))return this.clients.get(n);const r=J.createClient(e,this.streamTransport);return this.clients.set(n,r),r};createPromiseClient=(e,{params:n=[],method:r})=>{const i=this.getClient(e),o=r.toString(),s=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1),...Array.isArray(n)?n:[n]],a=[e.typeName,o.charAt(0).toLowerCase()+o.slice(1)];return{client:i,createRequestOptions:c=>{const l=J.createContextValues();for(const p in c){const d=rr[p];l.set(d,c[p])}return l},queryKey:s,queryKeyStr:a.join("")}};createStreamClient=e=>({client:this.getStreamClient(e)});setSdkKey=e=>{this.$headers.setValue("sdk",e)};setAuth=(e,n)=>{this.$headers.setValue("authorization",e),this.$headers.setValue("sl-user-id",n)};setHeader=(e,n)=>this.$headers.setValue(e,n);getHeader=e=>this.$headers.getValue(e);getHeaders=()=>this.$headers.getValues();initInterceptors=()=>{if(this.interceptors.length!==0)return;const e=n=>r=>{const i=this.$headers.getValues();for(const o in i)r.header.set(o,i[o]);return n(r)};this.interceptors.push(e),window.localStorage.getItem("SL_GRPC_DEVTOOLS")==="true"?this.interceptors.push(_i()):console.warn("SL GRPC DevTools is disabled. To enable, set SL_GRPC_DEVTOOLS to true in localStorage."),this.opts?.retryable&&this.interceptors.push(Vi)}}const Mi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Un.Events,{method:"retrieveEventId",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s||typeof s!="string")return"";try{return(await n.retrieveEventId({id:s})).data?.id||""}catch{return""}}})},ji=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ge.Client,{method:"getStream",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.getStream({id:s})).data?.attributes:void 0})},Qi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Un.Events,{method:"summary",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>s?(await n.summary({id:s})).data?.attributes:void 0})},Gi=(t,e)=>{const{queryKey:n,client:r}=e.createPromiseClient(sr.Users,{method:"me",params:[t]});return e.nanoquery.createFetcherStore(n,{fetcher:async()=>{if(!e.getHeader("authorization"))return{data:void 0};const{data:o}=await r.me({});return{data:o}}})},Wi=t=>{const{client:e,createRequestOptions:n}=t.createPromiseClient(sr.Users,{method:"bypassAuth"}),r=n({retryAttempts:0});return({userKey:i,schema:o,init:s,inviterKey:a})=>e.bypassAuth({userKey:i,schema:o,init:s,inviterKey:a},{contextValues:r})},Ki=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ge.Client,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.get({})).data?.attributes})},Hi=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ge.Client,{method:"getOrganization",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>{const i=await n.getOrganization({});return i.data?{...i.data.attributes,id:i.data.id}:void 0}})},$i=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(Ge.Client,{method:"getOrganizationAdvertising",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async()=>(await n.getOrganizationAdvertising({})).data?.attributes})},zi=(t,e,n)=>{t.transport=new Ar(e.host,{dedupeTime:1e3*60*5,refetchInterval:1e3*60*5,retryable:!0,webOS:e.webOS}),t.analyticsTransport=new Ar(e.analyticsHost),t.sdk.host=t.transport.host,t.transport.setSdkKey(e.sdkKey),t.transport.setHeader("sl-sdk-version",e.version||"-"),t.transport.$headers.subscribe(r=>{t.analyticsTransport.$headers.getStore().set(r)}),t.sdk.onMount({name:"transport"},()=>()=>{t.transport.disconnect(),t.analyticsTransport.disconnect()}),n()};var be;(function(t){t.SCHEMA="schema",t.EXTERNAL_TOKEN="eToken",t.TOKEN="token"})(be||(be={}));class Fe extends Be{constructor(){super("user")}setSchema=e=>{this.write(be.SCHEMA,e)};getSchema=()=>this.read(be.SCHEMA);setToken=e=>{this.write(be.TOKEN,e)};getToken=()=>this.read(be.TOKEN);setExternalToken=e=>{this.write(be.EXTERNAL_TOKEN,e)};getExternalToken=()=>this.read(be.EXTERNAL_TOKEN);removeToken=()=>{this.remove(be.TOKEN)}}var Ae;(function(t){t.DISABLED="disabled",t.INITIALIZATION="initialization",t.READY="ready",t.FAILED="failed",t.SUSPENDED="suspended"})(Ae||(Ae={}));const Yi=t=>{const e=new Fe,n=new le(Z(e.getExternalToken()),"userKey"),r=new le(Z(e.getToken()),"userToken"),i=new fe(Gi(r.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 fe(Ki(r.getStore(),t),"userSettings");return{userKey:n,userToken:r,user:i,userSettings:o}},Xi=t=>{const e=new le(Z(void 0),"providerStreamId"),n=new fe(Mi(e.getStore(),t),"slStreamId",o=>o?.data),r=new fe(ji(n.getAtomStore(),t),"streamSettings"),i=new fe(Qi(n.getAtomStore(),t),"streamSettings");return n.getAtomStore().listen(o=>{(o===""||o===void 0)&&(r.getStore().mutate(void 0),i.getStore().mutate(void 0))}),{providerStreamId:e,slStreamId:n,streamSettings:r,streamSummary:i}},Ji=t=>{const e=new le(Z(void 0),"enabled"),n=new le(Z(Ae.DISABLED),"status"),r=new fe(Hi(e.getStore(),t),"organizationSettings",a=>a?.data?.id),i=new fe($i(r.getAtomStore(),t),"organizationAdvertising"),o=Yi(t),s=Xi(t);return{enabled:e,status:n,providerStreamId:s.providerStreamId,slStreamId:s.slStreamId,streamSettings:s.streamSettings,streamSummary:s.streamSummary,user:o.user,userKey:o.userKey,userToken:o.userToken,userSettings:o.userSettings,organizationSettings:r,organizationAdvertising:i}};class Zi extends ut{stores;constructor(e){const n=Ji(e),r=Ci(n);super(r,"core"),this.stores=n}getValue(){throw new Error("Not implemented")}getValues(){return this.stores}setValue(){throw new Error("Not implemented")}subscribe=e=>{let n;for(n in this.stores){const r=e[n];n in e&&r!==void 0&&this.stores[n].subscribe(e[n])}};unsubscribe=()=>this.getStore().off()}const eo=(t,e,n)=>{t.store=new Zi(t.transport),t.stores=t.store.getValues(),t.sdk.enabled=t.stores.enabled.getStore(),t.sdk.status=t.stores.status.getStore(),t.sdk.sdkStore=Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getStore()])),t.sdk.organizationStore=()=>t.stores.organizationSettings.getStore(),t.sdk.streamStore=()=>t.stores.streamSettings.getStore(),t.sdk.streamSummary=()=>t.stores.streamSummary.getStore(),t.storeUnsubscribe=()=>{t.store.unsubscribe()},n()},to=t=>{const{client:e}=t.createPromiseClient(Vn.Leaderboard,{method:"list"});return n=>e.list(n)},Kn=t=>{const{client:e}=t.createPromiseClient(Vn.Leaderboard,{method:"summary"});return n=>e.summary(n)},ro=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(sr.Users,{method:"getFriends",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return[];try{return(await n.getFriends({})).data}catch{return[]}}})},no=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(ie.Feed,{method:"get",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>(await n.get({eventId:s})).data?.attributes,revalidateInterval:0,dedupeTime:1e3*60*60})},io=(t,e,n)=>{const{client:r,queryKey:i}=n.createPromiseClient(ie.Feed,{method:"syncQuestion",params:[t,e?"true":""]});return n.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(!a||u)return;const c=await r.syncQuestion({filter:{eventId:a}});if(c.data?.attributes?.question?.type!==O.QuestionType.PROMOTION)return c.data?.attributes},dedupeTime:1e3*60*10,revalidateInterval:0})},oo=async(t,e)=>{const{client:n}=e.createPromiseClient(ie.Feed,{method:"item",params:[t]});return(await n.item({id:t})).data},so=(t,e)=>{const{client:n}=e.createStreamClient(ie.Feed),r=ae.atom({eventId:t.get()||"",feedId:""});return t.subscribe((o="")=>{r.set({eventId:o,feedId:""})}),e.addSubscription(n.subscription,r,{name:"feedSubscription"})},ao=(t,e)=>{const{client:n}=e.createStreamClient(ie.Feed);return e.addSubscription(n.questionSubscription,{questionId:t},{name:"questionSubscription"})},Hn=async(t,e)=>{const{client:n}=e.createPromiseClient(ie.Feed,{method:"questionByUser",params:[t]});return(await n.questionByUser({questionId:t})).data?.attributes?.question},ot=(t,e)=>{const{client:n,queryKey:r,queryKeyStr:i}=e.createPromiseClient(ie.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(r,{fetcher:async(a,u,c)=>(await n.questionByUser({questionId:c})).data?.attributes?.question,dedupeTime:1/0,revalidateInterval:0});return e.storeCache.set(o,s),s}},$n=async(t,e)=>{if(!t)return;const{client:n}=e.createPromiseClient(ie.Feed,{method:"getQuestion",params:[t]}),r=await n.getQuestion({id:t});if(!r.data?.attributes)return;const{options:i,notification:o,...s}=r.data.attributes,a=i?.options.case==="promotion"?i?.options.value:void 0;return{id:s.id,question:s,promotion:a,notification:o}},uo=(t,e,n,r,i,o,s,a)=>{const{client:u,queryKey:c}=a.createPromiseClient(ie.Feed,{method:"list",params:[t,e,o?"true":"",s]});return a.nanoquery.createFetcherStore(c,{fetcher:async(l,p,d,f,h,m)=>{if(!d||h||!m)return[];const T=await u.list({eventId:d,filter:{types:f===Oe.ALLOWED?[]:[O.QuestionType.FACTOID,O.QuestionType.PROMOTION,O.QuestionType.TWEET],statuses:[O.QuestionStatus.ACTIVE,O.QuestionStatus.RESOLVED]}}),E={eventId:d,userId:n.get(),organizationId:r.get()};for(const g of T.data)i.isQuestionReceived(E,g.id)||(K.emit("poll",{action:"received",payload:{isAd:g.attributes?.adUnit!=O.AdUnit.UNSET,questionId:g.id,questionType:g.attributes?.type}}),i.saveQuestionReceived(E,g.id));return T.data},dedupeTime:1/0,revalidateInterval:0})},co=(t,e)=>{const{client:n,queryKey:r}=e.createPromiseClient(ie.Feed,{method:"list",params:[t]});return e.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s)=>{if(!s)return;const u=(await n.list({eventId:s,filter:{types:[O.QuestionType.PROMOTION],statuses:[O.QuestionStatus.ACTIVE]},pagination:{page:0,pageSize:1}})).data?.[0];if(u?.type==="promotion")return $n(u.id,e)},dedupeTime:1/0,revalidateInterval:0})},lo=(t,e,n,r,i)=>{const{client:o,queryKey:s}=i.createPromiseClient(ie.Feed,{method:"betPack",params:[t,e,n]});return i.nanoquery.createFetcherStore(s,{fetcher:async(a,u,c,l,p)=>{if(!c||!l||!p)return{timestamp:Date.now(),data:null};const d=await o.betPack({eventId:c,types:[O.QuestionType.PREDICTION],statuses:[O.QuestionStatus.ACTIVE,O.QuestionStatus.RESOLVED],limit:5,sort:{field:"activated_at",order:"asc"}});return!d.data||!d.data.length?{timestamp:Date.now(),data:null}:{timestamp:Date.now(),data:d.data?.reduce((f,h)=>{const m=h?.attributes?.question;if(!m?.id)return f;const T={eventId:c,userId:l,organizationId:p};return r.isQuestionReceived(T,m.id)||(K.emit("poll",{action:"received",payload:{isAd:m?.adUnit!=O.AdUnit.UNSET,questionId:m.id,questionType:m.type}}),r.saveQuestionReceived(T,m.id)),m.answers=m.answers.sort((E,g)=>E.id>g.id?1:-1),{...f,[m.id]:m}},{})}},dedupeTime:1/0,revalidateInterval:0})},po=(t,e,n)=>{const r=new Map,i=(l,p)=>{r.has(l)||r.set(l,new Set),r.get(l)?.add(p)},o=(l,p)=>r.get(l)?.has(p)??!1,s=ae.batched([e,n],()=>{const l=e.get();if(!l)return;const p=n.get().data?.find(h=>h.id===l?.questionId),d=l?.question?.openedFrom,f=l.questionId;if(p)return p.openedFrom=d,Object.assign(p,{fireEvent:h=>i(f,h),isEventFired:h=>o(f,h)});if(l.question)return Object.assign(l.question,{fireEvent:h=>i(f,h),isEventFired:h=>o(f,h)})}),a=ae.batched(s,l=>l?.id),u=ot(a,t);return{$store:s,$extendedStore:u,updateExtendedQuestion:l=>{const p=u.get().data,d=(f,h)=>{if(!f||!h)return(f||h||[]).sort((g,S)=>g.id>S.id?1:-1);const m=f.sort((g,S)=>g.id>S.id?1:-1),T=h.sort((g,S)=>g.id>S.id?1:-1),E=[];for(let g=0;g<m.length;g++)E.push({...m[g],...T[g],correct:m[g].correct,youVoted:m[g].youVoted,pointsEarned:m[g].pointsEarned});return E};u.mutate({...l,options:p?.options,subject:p?.subject,appearance:p?.appearance,answers:d(p?.answers,l?.answers)})}}};var Ue;(function(t){t.SHOWED="showed",t.EVENT="ev"})(Ue||(Ue={}));class fo extends Be{constructor(){super("advertisement")}setShowed=e=>{this.write(Ue.SHOWED,e,"true")};isViewed=e=>this.read(Ue.SHOWED,e);fireEvent=(e,n)=>{this.write(Ue.EVENT,n,e,"true")};isEventFired=(e,n)=>this.read(Ue.EVENT,n,e)==="true"}const ho=t=>{const e=t.data?.attributes?.question;if((t.data?.attributes?.feedItem?.type==="promotion"?t.data.attributes.feedItem:void 0)===void 0||!e)return;const{options:r,notification:i,...o}=e,s=r?.options.case==="promotion"?r.options.value:void 0;return{id:o.id,question:o,notification:i,promotion:s}},ze=t=>t.startsWith("http://")||t.startsWith("https://")?new URL(t).toString():t,mo=({gamOptions:t,gamBaseUrl:e})=>{const n=`${e}?`,r=[];for(const i in t){const o=i.replace(/([a-zA-Z])(?=[A-Z])/g,"$1_").toLowerCase(),s=t[i];if(s)if(typeof s=="string")r.push(`${o}=${ze(s)}`);else if(Array.isArray(s))r.push(`${o}=${s.map(ze).join(",")}`);else{const a=Object.entries(s).map(([u,c])=>Array.isArray(c)?`${u}=${c.map(ze).join(",")}`:typeof c=="string"?`${u}=${ze(c)}`:`${u}=${c}`).join("&").replaceAll("=","%3D").replaceAll("&","%26").replaceAll(",","%2C");r.push(`${o}=${a}`)}}return n+r.join("&")},Le=t=>(t?.promotion?.type===O.PromotionType.INGAME_IAB11_LBAR||t?.promotion?.type===O.PromotionType.INGAME_IAB21_LBAR)&&!!t.promotion.additionalBanner?.imageUrl,yo=(t,e,n)=>{let r=!1;const i=n.transport,o=ue("advertisement"),s=new fo,a=(g,S)=>{s.fireEvent(g,S)},u=(g,S)=>s.isEventFired(g,S),c=se({}),l=co(t,i),p=g=>{const S=c.get(),v=S.data?.question.id,I=S.data?.promotion?.type;if(!v)return;c.get()?.isOpened||(c.setKey("isOpened",!0),K.emit("advertisement",{action:"opened",payload:{id:v,type:I,hasBanner:Le(S.data),openedFrom:g?.fromNotification?"notification":"auto"}})),g?.fromNotification&&(c.setKey("hasNotification",!1),K.emit("advertisement",{action:"notification-opened",payload:{id:v,type:I,hasBanner:Le(S.data)}}))},d=()=>{const g=c.get(),S=g.data?.question.id,v=g.data?.promotion?.type,I=c.get()?.isOpened;S&&!I&&(o.debug({id:S},"markAsViewed: %o"),s.setShowed(S),c.setKey("isOpened",!0),K.emit("advertisement",{action:"viewed",payload:{id:S,type:v,hasBanner:Le(g.data)}}))},f=(g,S)=>{S?c.set({loading:!1,error:void 0,data:S,hasNotification:S?.notification?.enabled===O.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>h(S.question.id),togglePause:v=>m(S.question.id,v),toggleMute:v=>T(S.question.id,v),isViewed:!!s.isViewed(S.question.id),fireEvent:v=>a(g,v),isEventFired:v=>u(g,v)}):(c.setKey("loading",!0),$n(g,i).then(v=>c.set({loading:!1,error:void 0,data:v,hasNotification:v?.notification?.enabled===O.NotificationEnabled.NOTIFICATION_ENABLED,close:()=>h(v?.question.id),togglePause:I=>m(v?.question.id,I),toggleMute:I=>T(v?.question.id,I),isViewed:v&&!!s.isViewed(v.question.id),fireEvent:I=>a(g,I),isEventFired:I=>u(g,I)})).catch(v=>c.set({loading:!1,error:v,data:void 0,fireEvent:()=>{},isEventFired:()=>!1})))};c.subscribe((g,S)=>{if(!(g.data?.id===S?.data?.id&&g.isPaused!==S?.isPaused)){if(g.data?.promotion?.type===O.PromotionType.EXTERNAL_AD&&!g?.externalAd&&g.data.promotion.adCampaigns?.desktopWebSettings){const v=mo(g.data.promotion.adCampaigns.desktopWebSettings);c.setKey("externalAd",{type:"gam",url:v})}g.data?.promotion&&!g.isOpened&&(K.emit("advertisement",{action:"received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!!g.hasNotification,hasBanner:Le(g.data),isViewed:!!s.isViewed(g.data.question.id)},skipAnalytics:g.data.question.id===S?.data?.question.id}),g.data.question.id!==S?.data?.question.id&&!s.isViewed(g.data.question.id)&&K.emit("advertisement",{action:"notification-received",payload:{id:g.data.question.id,type:g.data.promotion.type,hasNotification:!0,hasBanner:Le(g.data),isViewed:!1}})),!g?.data&&S?.data&&K.emit("advertisement",{action:"closed",payload:{id:S.data.question.id,type:S.data.promotion?.type,hasNotification:!!S.hasNotification,hasBanner:Le(S.data),isViewed:!!s.isViewed(S.data.question.id)}})}});const h=g=>{(!g||c.get()?.data?.question.id===g)&&c.set({})},m=(g,S)=>{c.get()?.data?.question.id===g&&c.setKey("isPaused",S)},T=(g,S)=>{c.get()?.data?.question.id===g&&c.setKey("isMuted",S)};return{connect:()=>{r||(r=!0,l.subscribe((g,S)=>{g.data&&(!S?.data||g.data.id!==S.data.id)&&f(g.data.question.id,g.data)}),e.addListener("promotion",g=>{const S=ho(g);if(S){if(S.question.status===O.QuestionStatus.RESOLVED){h(S.question.id),o.debug({promotion:S},"resolved: %o");return}if(S.question.status===O.QuestionStatus.ACTIVE){o.debug({promotion:S},"active: %o"),f(S.question.id,S);return}o.debug({promotion:S},"skip: %o")}}))},hide:h,show:f,open:p,markAsViewed:d,$store:c}};var he;(function(t){t.ONBOARDING="onboarding",t.ONBOARDING_IO="onboarding_io",t.QUESTION_RECEIVED="q-received",t.QUESTION_OPENED="q-opened"})(he||(he={}));class go extends Be{constructor(){super("gamification-session",window.sessionStorage)}writeValue=(e,n)=>{this.write(...e,n)};readValue=e=>this.read(...e)}class vo extends Be{sessionStorage;constructor(){super("gamification"),this.sessionStorage=new go}saveQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>{this.write(he.QUESTION_RECEIVED,r,e,n,i,"1")};isQuestionReceived=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(he.QUESTION_RECEIVED,r,e,n,i);saveQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>{this.write(he.QUESTION_OPENED,r,e,n,i,"1")};isQuestionOpened=({userId:e,eventId:n,organizationId:r},i)=>!!this.read(he.QUESTION_OPENED,r,e,n,i);saveOnboardingStatus=({userId:e,eventId:n,organizationId:r},i)=>{this.write(he.ONBOARDING,r,e,n,i)};getOnboardingStatus=({userId:e,eventId:n,organizationId:r})=>this.read(he.ONBOARDING,r,e,n);setOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>{this.sessionStorage.writeValue([he.ONBOARDING_IO,r,e,n],"1")};getOnboardingInstantOpen=({userId:e,eventId:n,organizationId:r})=>this.sessionStorage.readValue([he.ONBOARDING_IO,r,e,n])}var Oe;(function(t){t.ALLOWED="allowed",t.DISALLOWED="disallowed"})(Oe||(Oe={}));class bo{slStreamId;organizationId;userId;interactiveAllowed;openedQuestionId;openedQuestion;activeQuestionId;feedList;betPack;moderationId;moderation;feedSubscription;questionSubscription;advertisement;withPickHistory;storage;notifications;log;transport;cancels=new Set;constructor(e){this.transport=e.transport,this.log=ue("gamification-background"),this.storage=new vo,this.slStreamId=e.stores.slStreamId.getAtomStore(),this.organizationId=e.stores.organizationSettings.getAtomStore(),this.userId=e.stores.user.getAtomStore(),this.moderationId=new le(Z(void 0),"moderationId").getStore(),this.interactiveAllowed=new le(Z(Oe.DISALLOWED),"interactiveAllowed").getStore(),this.openedQuestionId=new le(Z(void 0),"openedQuestionId").getStore(),this.withPickHistory=Z(!1),this.notifications=e.notifications,this.moderation=new fe(no(this.slStreamId,e.transport),"gamification:moderation");const n=!!e.sdk.options.get().betPack;this.feedList=new fe(uo(this.slStreamId,this.interactiveAllowed,this.userId,this.organizationId,this.storage,n,this.withPickHistory,e.transport),"gamification:feedList"),this.betPack=new fe(lo(this.slStreamId,this.userId,this.organizationId,this.storage,e.transport),"gamification:betPack"),this.activeQuestionId=io(this.slStreamId,n,e.transport),this.openedQuestion=po(e.transport,this.openedQuestionId,this.feedList.getStore()),this.cancels.add(this.openedQuestionId.listen(r=>{this.log.debug({item:r},"received question"),r?.questionId?(this.log.info("cleanup on close question"),this.questionSubscription!==void 0&&(e.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0),this.questionSubscription=ao(r.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===O.QuestionType.PREDICTION&&(o.status===O.QuestionStatus.ACTIVE||o.status===O.QuestionStatus.RESOLVED)){const s=this.betPack.getValues().data?.data||{},a=s?.[o.id];if(a){const u=[],c=a.answers.sort((p,d)=>p.id>d.id?1:-1),l=o.answers.sort((p,d)=>p.id>d.id?1:-1);for(let p=0;p<c.length;p++)u.push({...c[p],...l[p],correct:c[p].correct,youVoted:c[p].youVoted,pointsEarned:c[p].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=so(this.slStreamId,e.transport),this.cancels.add(this.feedSubscription.addListener("bet-pack-update",async r=>{const i=r.data?.attributes?.question;if(this.betPack&&i?.type===O.QuestionType.PREDICTION&&(i.status===O.QuestionStatus.ACTIVE||i.status===O.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",r=>{const i=this.activeQuestionId.get().data?.question?.id,o=r.data?.attributes?.question;if(!(!o||o.type===O.QuestionType.PROMOTION)){if(o.status===O.QuestionStatus.RESOLVED){i===o.id&&this.activeQuestionId.mutate(void 0);return}window.requestAnimationFrame(()=>{this.activeQuestionId.mutate(r.data?.attributes)})}})),this.cancels.add(this.feedSubscription.addListener("moderation update",r=>{window.requestAnimationFrame(()=>{r.data?.attributes?.question===void 0&&r.data?.attributes?.moderation&&this.moderation.invalidate()})})),this.cancels.add(this.activeQuestionId.subscribe((r,i)=>{if(r.data?.feedItem&&r.data?.feedItem?.id!==i?.data?.feedItem?.id){const o=r.data.feedItem,s={eventId:this.slStreamId.get(),userId:this.userId.get(),organizationId:this.organizationId.get()};K.emit("poll",{action:"received",payload:{isAd:o?.attributes?.adUnit!=O.AdUnit.UNSET,questionId:o.id,questionType:o.attributes?.type}}),this.storage.saveQuestionReceived(s,o.id),e.onQuestionActivate({stage:"activate",id:r.data.feedItem.id,isViewed:!!this.notifications.isViewed(this.getCurrentSessionId({prefix:"notification",entity:r.data.feedItem.id})),hasNotification:r.data?.question?.notification?.enabled===O.NotificationEnabled.NOTIFICATION_ENABLED,type:r.data.feedItem.type})}!r.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:i.data?.question?.notification?.enabled===O.NotificationEnabled.NOTIFICATION_ENABLED,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 r of this.cancels)r(),this.cancels.delete(r)}),n||(this.advertisement=yo(this.slStreamId,this.feedSubscription,e))}getCurrentSessionId=e=>{const n=e.eventId||this.slStreamId.get()||"",r=e.userId||this.userId.get()||"",i=e.organizationId||this.organizationId.get()||"",o=e.entity||"",s=e.prefix||"";return[i,n,r,s,o].join(":")};disconnect=()=>{this.feedSubscription?.disconnect(),this.questionSubscription!==void 0&&(this.transport.removeSubscription(this.questionSubscription),this.questionSubscription=void 0)};openQuestion=(e,n)=>{this.openedQuestionId.set({questionId:e,question:n}),this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))};closeQuestion=e=>{this.openedQuestionId.set(void 0),e&&this.notifications.markAsViewed(this.getCurrentSessionId({prefix:"notification",entity:e}))}}class To{notificationsList;store;timeouts;waitingQueue;activeQueue;options;logger;constructor(e){this.options=e,this.logger=ue("notifications"),this.store=new Map,this.timeouts=new Map,this.waitingQueue=new Set,this.activeQueue=new Set,this.notificationsList=Z(new Map)}addToQueue=e=>{if(this.store.has(e.id)){this.logger.debug({notification:e},"skip existed notification: %o");return}const n=e.close,r=e.action;if(this.store.set(e.id,{...e,close:(...i)=>{n&&n(...i),this.closeNotification(e.id)},action:(...i)=>{r&&r(...i),this.closeNotification(e.id,{animateHiding:!1})}}),this.waitingQueue.add(e.id),this.activeQueue.size===this.options.concurrency){const[i]=this.activeQueue;if(this.store.get(i)?.persistent!==!0)this.closeNotification(i);else{const[s]=this.waitingQueue;this.waitingQueue.size>1&&this.closeNotification(s),this.tickWaitingQueue()}}else this.tickWaitingQueue()};tickWaitingQueue=()=>{if(this.activeQueue.size<this.options.concurrency){const[e]=this.waitingQueue;if(!e)return;this.activeQueue.add(e),this.waitingQueue.delete(e),this.logger.debug({job:e},"waiting queue tick"),this.tickActiveQueue(e)}else this.logger.debug({queueSize:this.activeQueue.size,concurrency:this.options.concurrency},"waiting queue tick skipped")};tickActiveQueue=e=>{if(!e)return;const n=this.store.get(e);if(!n){this.logger.debug({notificationId:e},"active queue tick skipped, notification not exist");return}K.emit("notification",{action:"received",payload:{type:n.type,questionId:n.data.questionId,questionType:n.data.questionType}});const r=setTimeout(()=>{const i=e,o=new Map(this.notificationsList.get());o.set(n.id,n),this.notificationsList.set(o);const s=setTimeout(()=>{this.logger.debug({notificationId:i,delay:n.autoHideDuration||5e3},"notification hiding by autoHideDuration"),this.closeNotification(i)},n.autoHideDuration||5e3);this.timeouts.set(i,s),this.logger.debug({notificationId:i,queue:[...o.values()]},"notification displayed")},n.delay||0);this.timeouts.set(e,r),this.logger.debug({notificationId:e},"active queue tick completed"),this.tickWaitingQueue()};closeNotification=(e,{animateHiding:n=!0}={})=>{const r=new Map(this.notificationsList.get()),i=r.get(e);if(i){const o=!(this.waitingQueue.size>=this.options.concurrency)&&n;i.hiding=o,this.notificationsList.set(r);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"),K.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 at;(function(t){t.OPENED="opened"})(at||(at={}));class Ao extends Be{constructor(){super("notification")}setOpened=e=>{this.write(at.OPENED,e,"true")};isOpened=e=>this.read(at.OPENED,e);clearNotification=()=>{this.clear()}}class So{queue;storage;constructor(e={}){this.storage=new Ao,this.queue=new To({concurrency:1,animationDelay:1600,...e})}isViewed=e=>this.storage.isOpened(e);add=e=>{if(!this.isViewed(e.id)){if(e.data&&e.emitEvent){const r=e.action;e.action=(...i)=>{r&&r(...i),K.emit("notification",{action:"opened",payload:{questionId:e.data.questionId,questionType:e.data.questionType}})}}this.queue.addToQueue(e)}};close=(e,{markAsViewed:n=!0,animateHiding:r}={})=>{this.queue.closeNotification(e,{animateHiding:r}),n&&this.markAsViewed(e)};update=(e,n)=>{const r=this.queue.notificationsList.get()?.get(e);n(r)};getActiveNotification=()=>{const e=this.queue.notificationsList.get();if(!e?.size)return null;for(const r of e.values())if(r.type===Ee.ONBOARDING)return r;return e.values().next().value};getQueueStore=()=>this.queue.notificationsList;markAsViewed=e=>{this.storage.setOpened(e)}}const wo=(t,e,n)=>{t.notifications=new So(void 0),t.addNotification=t.notifications.add,t.sdk.getNotificationsStore=()=>t.notifications.getQueueStore(),t.sdk.getActiveNotification=()=>t.notifications.getActiveNotification(),t.sdk.onMount({name:"notifications"},()=>()=>{t.notifications.queue.drain()}),n()};var xe;(function(t){t.UNKNOWN="unknown",t.ALREADY_VOTED="already_voted"})(xe||(xe={}));const Sr=async(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(ie.Feed,{method:"submitAnswer"}),i=r({retryAttempts:0});try{return await n.submitAnswer({data:e},{contextValues:i})}catch(o){throw J.ConnectError.from(o)?.code===J.Code.AlreadyExists?new Error(xe.ALREADY_VOTED):new Error(xe.UNKNOWN)}},zn=(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(ie.Feed,{method:"submitInplay"}),i=r({retryAttempts:0});return n.submitInplay({data:{eventId:+e}},{contextValues:i})},Eo=t=>{switch(t){case O.UserAccountInfo.PHONE:return Me.WebhookNotificationType.PHONE;case O.UserAccountInfo.EMAIL:return Me.WebhookNotificationType.MAIL;default:return Me.WebhookNotificationType.UNSET}},Io=(t,e)=>{const{client:n,createRequestOptions:r}=t.createPromiseClient(Me.OrganizationWebhooks,{method:"sendWebhookEvent"}),i=r({retryAttempts:0});return n.sendWebhookEvent({eventId:e.eventId,questionId:e.questionId,data:{event:Me.WebhookEvent.CLICK_BUTTON,notificationType:Eo(e.userAccountInfo),userId:e.userId,description:"",metadata:{},customFields:{}}},{contextValues:i})},Oo={pageSize:10},ko=(t,e,n,r,i)=>{let o=0;const s=Z({pageSize:Oo.pageSize,page:0}),a=se({data:[],key:Date.now(),hasMore:!0,loading:void 0,error:void 0}),u=to(t),c=async()=>{const d=e.get(),f=r?.getStore().get().data?.map(h=>h.slId)||[];if(d&&f?.length){const h=n.get();h&&f.push(h),a.setKey("loading",!0),a.setKey("data",[]);const T=await u({eventId:d,usersIds:f,leaderboardId:""});a.set({data:T.data.map((E,g)=>({...E.attributes,friendsRank:g+1})),hasMore:!1,key:Date.now(),loading:!1}),T.meta&&(o=Math.round(T.meta.count/T.meta.pageSize))}},l=()=>{c()},p=d=>{const f=s.get(),h=d||f.page+1;h<=o&&s.set({...f,page:h})};return ae.onMount(a,()=>{const d=e.listen(c),f=r?.listen(c);return()=>{d(),f?.()}}),{$store:a,fetchMore:p,invalidate:l}};class No extends Be{get=this.read;set=this.write;del=this.remove;constructor(){super("deep-link-context",window.sessionStorage)}}const wr="sldl",ct="sldl_uid",Yn="sldl_eid",Xn="sldl_e_eid",Co=new Set([ct,Yn,Xn]),Er=t=>{const e={},n={};for(const[r,i]of t)Co.has(r)?e[r]=i:n[r]=i;return{result:e,remain:n}},Ro=({hash:t,search:e})=>{if(t&&t.includes(wr)){const n=new URLSearchParams(t.substr(1));return{hash:Er(n)}}if(e&&e.includes(wr)){const n=new URLSearchParams(e);return{search:Er(n)}}return null},Ir=ue("deep_link"),ge={debug:(...t)=>{Ir.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Ir.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Po=(t,e)=>{const{hash:n,search:r}=window.location;if(ge.debug({hash:n,search:r},"get deep link data from"),n||r){const i=Ro({hash:n,search:r});if(ge.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()}`,ge.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()}`,ge.debug({updatedSearch:l},"update search")),window.history.replaceState(null,"",window.location.pathname+l+window.location.hash)}e(a)}}}t.setValue("parsed",!0)},Lo=(t,e,n)=>{const r=new No,i=r.get("sl-deep-link-store");let o={};if(i)try{o=JSON.parse(i)}catch(a){ge.debug(a)}t.deepLink={$store:new Ce(se(o),"deep-link-context"),getDeepLinkData:()=>{const{data:a,used:u}=t.deepLink.$store.getValues();return{data:a,used:u}},deepLinkUsed:a=>{ge.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?.[ct]:void 0},t.sdk.inviteDisplayed=()=>{t.deepLink.$store.getStore().set({}),t.deepLink.$store.getStore().off(),r.del("sl-deep-link-store")},t.deepLink.$store.subscribe(a=>r.set("sl-deep-link-store",JSON.stringify(a))),t.sdk.addDeepLinkHandler=a=>{localStorage.getItem("SL_DEBUG")&&ge.trace("adding deep link handler"),t.deepLink.onDeepLinkHandlers.add(a)},e.onDeepLinkHandled&&t.sdk.addDeepLinkHandler(e.onDeepLinkHandled),t.sdk.removeDeepLinkHandler=a=>{ge.trace("removing deep link handler"),t.deepLink.onDeepLinkHandlers.delete(a)};const s=a=>{t.deepLink.$store.setValue("handled",!0),ge.trace({size:t.deepLink.onDeepLinkHandlers.size},"deep link handled, call callbacks");for(const u of t.deepLink.onDeepLinkHandlers)try{ge.trace("called handler"),u(a)}catch(c){console.error(c)}};Po(t.deepLink.$store,s),n()},_o=ue("bypass");class Do extends Ni{$coreStore;deepLink;transport;bypassLogin;constructor(e,n,r){super(),this.$coreStore=e,this.deepLink=r,this.transport=n,this.bypassLogin=Wi(this.transport),this.connect()}me=async()=>(this.$coreStore.getValues().user.invalidate(),(await this.$coreStore.getValues().user.getValue())?.data);login=async(e,n)=>{this.$coreStore.getValues().userKey.setValue(n);const{used:r,data:i}=this.deepLink?.getDeepLinkData()||{},o=r?"":i?.[ct];_o.debug({inviterKey:o},"login with inviterKey");const s=await this.bypassLogin({schema:e,userKey:n,inviterKey:o,init:!1}),a=s.meta?.jwt,u=s.data?.id;if(!a||!u)throw new Error("internal: token missing");return s.meta?.inviterKey&&this.deepLink&&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 Fe().clear()};softLogout=()=>{const e=new Fe;this.transport.setAuth("",""),e.setToken(""),this.reLogin()};reLogin=({skipLogin:e}={skipLogin:!1})=>{const n=new Fe,r=n.getToken(),i=n.getExternalToken();if(this.$coreStore.getValues().userKey.setValue(i),r)return this.saveUser(r,""),this.me().then(o=>{if(o?.id){const s=o.id;this.saveUser(r,s)}return o});if(i&&!r&&!e){const o=n.getSchema();o&&i&&this.login(o,i).catch(()=>{this.logout()})}};saveUser=(e,n)=>{this.transport.setAuth(e,n),this.$coreStore.getValues().userToken.setValue(e),new Fe().setToken(e)};connect=()=>{this.transport.registerInterceptor(e=>async n=>{try{return await e(n)}catch(r){throw r.code&&(r.code===7||r.code===16)&&this.transport.getHeader("authorization")&&this.softLogout(),r}})}}const qe=new Fe,Fo=(t,e,n)=>{t.auth=new Do(t.store,t.transport,t.deepLink),t.stores.status.listen(r=>{r===Ae.READY&&t.auth.reLogin()}),t.sdk.userId=t.stores.user.getAtomStore,t.sdk.authorizationBypass=async(r,i)=>{if(!(qe.getSchema()===r&&qe.getExternalToken()===i&&t.transport.getHeader("authorization")))try{console.log("login",r,i),await t.auth.login(r,i),qe.setSchema(r),qe.setExternalToken(i)}catch(o){console.log("login error",o),t.sdk.logout()}},t.sdk.logout=()=>{t.auth.logout(),qe.clear()},t.sdk.getUserStore=()=>t.stores.user.getStore(),t.sdk.isUserAuthorized=()=>t.auth.isAuthenticated(),n()},Or=ue("video_player"),Ye={debug:(...t)=>{Or.debug(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)},trace:(...t)=>{Or.trace(...t),localStorage.getItem("SL_DEBUG")&&console.log(...t)}},Uo=(t,e,n)=>{t.videoPlayer={controllers:new Set},t.sdk.addVideoPlayerController=r=>{Ye.trace("adding video player controller"),t.videoPlayer.controllers.add(r)},e.videoPlayerController&&t.sdk.addVideoPlayerController(e.videoPlayerController),t.sdk.removeVideoPlayerController=r=>{Ye.trace("removing video player controller"),t.videoPlayer.controllers.delete(r)},t.sdk.controlVideoPlayer=r=>{Ye.trace("controlling video player");for(const i of t.videoPlayer.controllers){Ye.trace("calling video player controller");try{i(r)}catch(o){console.error(o)}}},n()},Vo={[O.QuestionType.FACTOID]:"insight",[O.QuestionType.POLL]:"poll",[O.QuestionType.TRIVIA]:"trivia",[O.QuestionType.PREDICTION]:"prediction",[O.QuestionType.TWEET]:"tweet"},_e=t=>t===O.PromotionType.INGAME_IAB11||t===O.PromotionType.INGAME_IAB21||t===O.PromotionType.NFL_SHOP_OVERLAY||t===O.PromotionType.SHOP_OVERLAY,xo=(t,e,n)=>{t.sdk.uiState=se({}),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 r=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&&Vo[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===Ee.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:p,isViewed:d,type:f}=u.payload;switch(u.action){case"notification-opened":t.sdk.uiState.set({promotionExternalAd:f===O.PromotionType.EXTERNAL_AD,promotionBanner:l,promotionNotification:!1,promotionOverlay:_e(f),promotionSidebar:!_e(f)});break;case"received":if(t.sdk.closeFeature(),r({stage:"activate",id:p,hasNotification:c,hasBanner:l,isViewed:d}),!e.withAdNotification){t.sdk.uiState.set({promotionBanner:l,onboardingNotification:t.sdk.uiState.get().onboardingNotification,promotionOverlay:_e(f),promotionSidebar:!_e(f),promotionExternalAd:f===O.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:_e(f),promotionSidebar:!_e(f),promotionExternalAd:f===O.PromotionType.EXTERNAL_AD});break;case"closed":t.sdk.uiState.set({...t.sdk.uiState.get(),promotionNotification:!1,promotionBanner:!1,promotionOverlay:!1,promotionExternalAd:!1,promotionSidebar:!1}),r({stage:"deactivate",id:p,hasNotification:c,hasBanner:l,isViewed:d});break}}},o=K.listen(i),s=t.activeFeature.subscribe(a=>{a||t.ui.disableApp()});return()=>{o(),s()}}),n()},Bo=(t,e,n)=>{const r={onMountedFired:!1},i=new Map,o=new Map;t.sdk=Object.create(null),t.sdk.options=se(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"&&r.onMountedFired===!1&&(i.forEach(({cb:a},u)=>o.set(u,a())),r.onMountedFired=!0),s!=="on"&&r.onMountedFired===!0&&(o.forEach(a=>a()),o.clear(),i.forEach(({clear:a},u)=>a&&i.delete(u)),r.onMountedFired=!1)})},t.sdk.initializeApp=s=>(t.contextConfig=s,t.stores.enabled.get()==="on"?Promise.resolve({enabled:!0}):(t.storeSubscribe(),t.stores.enabled.setValue("on"),t.stores.status.setValue(Ae.INITIALIZATION),t.stores.organizationSettings.getValue().then(a=>a?(t.stores.status.setValue(Ae.READY),{enabled:!!a}):(t.stores.status.setValue(Ae.FAILED),{err:"failed"}),a=>(t.stores.enabled.setValue(),t.stores.status.setValue(Ae.FAILED),{err:`${a}`})))),t.sdk.disableApp=()=>{t.stores.enabled.get()==="on"&&(t.stores.enabled.setValue(),t.stores.status.setValue(Ae.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)},n()},qo=(t,e)=>{const{client:n,queryKey:r}=t.createPromiseClient(Ge.Client,{method:"generateDeepLink",params:e});return t.nanoquery.createFetcherStore(r,{fetcher:async(i,o,s,a)=>{if(!s)return{};try{return(await n.generateDeepLink({data:{gamification:!0,externalEventId:a,eventId:s}})).data?.attributes}catch{return}},dedupeTime:1e3*60*60*24,revalidateInterval:0})},Mo=(t,{web:e,mobile:n})=>{const{client:r}=t.createPromiseClient(bi.LinksClient,{method:"generate"});return r.generate({web:e,mobile:n})},kr=(t,e)=>{const n=new URLSearchParams(t);for(const[r,i]of Object.entries(e))n.append(r,i);return n.toString()},jo=(t,e,n,r)=>{const i=se({});return ae.onMount(i,()=>qo(t,[e,n]).subscribe(async({data:a,loading:u})=>{const c=a===void 0&&u===!1?"https://streamlayer.io":a?.url,l=r.get()||"",p=e.get()||"",d=n.get()||"",f={[ct]:l,[Yn]:p,[Xn]:d};if(!u&&c){i.setKey("loading",!0);let h=window.location.search,m=window.location.hash;h&&m||m?h=`?${kr(h,f)}`:m=`#${kr("",f)}`;const T=window.location.origin+window.location.pathname+h+m;try{const E=await Mo(t,{web:T,mobile:c});i.set({data:E.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 ne;(function(t){t.Unset="unset",t.Required="required",t.Optional="optional",t.Completed="completed",t.Disabled="disabled",t.Unavailable="unavailable"})(ne||(ne={}));const Qo=(t,e,n,r)=>{const{inplayGame:i}=t.featureSettings.get(),o=e.getCurrentSessionId({prefix:"onboarding"});i&&n.add({type:Ee.ONBOARDING,id:o,action:t.openFeature,close:()=>{t.onboardingProcessed.set(!0)},persistent:!0,autoHideDuration:1e6,data:{questionId:"onboarding",questionType:O.QuestionType.UNSET,onboarding:{...i,instantOpen:!r.getOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),markIstantOpen:()=>{r.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}),n.update(o,s=>{s?.data?.onboarding&&(s.data.onboarding.instantOpen=!0)})}}}})},Xe=(t,e,n,r,i,o,s,a)=>{try{const u=e.userId.get(),c=e.organizationId.get(),l=e.slStreamId.get();if(!u||!c||!l)return;const p=i.getOnboardingStatus({userId:u,organizationId:c,eventId:l});if(p===ne.Completed||a?.skipOnboarding){t.set(ne.Completed);for(const T of o)T();a?.skipOnboarding&&p!==ne.Completed&&(i.saveOnboardingStatus({organizationId:c,userId:u,eventId:l},ne.Completed),zn(s,l));return}const d=e.moderation.getStore().value?.data,f=n.featureSettings.get().inplayGame;if(d===void 0||f===void 0)return;const h=d?.options?.onboardingEnabled,m=f?.titleCard?.optIn;h?m?t.set(ne.Required):t.set(ne.Optional):(m?t.set(ne.Unavailable):t.set(ne.Disabled),r.close(e.getCurrentSessionId({prefix:"onboarding"}),{markAsViewed:!1}))}catch(u){console.error(u)}},Nr=(t,e,n,r,i)=>{let o=!!i?.skipOnboarding;const s=e.storage,a=Z(ne.Unset);a.subscribe(l=>{l!==ne.Unset&&(l===ne.Optional||l===ne.Required?o===!1&&(Qo(t,e,r,s),o=!0):t.onboardingProcessed.set(!0),s.setOnboardingInstantOpen({userId:e.userId.get()||"",organizationId:e.organizationId.get()||"",eventId:e.slStreamId.get()||""}))});const u=[];return a.get()!==ne.Completed&&(u.push(e.userId.listen(l=>{l&&Xe(a,e,t,r,s,u,n,i)})),u.push(e.moderation.listen(l=>{l.data&&Xe(a,e,t,r,s,u,n,i)})),u.push(t.featureSettings.listen(l=>{l&&Xe(a,e,t,r,s,u,n,i)}))),Xe(a,e,t,r,s,u,n,i),{$store:a,submitInplay:async()=>{const l=e.slStreamId.get();if(l){await zn(n,l),a.set(ne.Completed),s.saveOnboardingStatus({organizationId:e.organizationId.get()||"",userId:e.userId.get()||"",eventId:l},ne.Completed),K.emit("poll",{action:"onboardingPassed",payload:{}}),t.openFeature();const p=e.getCurrentSessionId({prefix:"onboarding"});r.close(p)}}}},Go=(t,e,n,r)=>{const i=se(void 0),o=Kn(r),s=async()=>{const u=t.get(),c=e.get(),l=n?n.getStore().get().data?.map(f=>f.slId):[];if(!l||!u||!c)return;const p={eventId:u,userId:c,leaderboardId:"",usersIds:[...l,c]},d=await o(p);i.set(d.data?.attributes)},a=()=>{s()};return ae.onMount(i,()=>{a();const u=t.listen(s),c=n?.listen(s),l=e.listen(s);return()=>{u(),c?.(),l()}}),{$store:i,invalidate:a}},Wo=async(t,e,n,r,i)=>{const o=Kn(i),s=t.get(),a=e.get(),u=n?.getStore().get().data?.map(d=>d.slId)||[],c={eventId:s,userId:r,leaderboardId:"",usersIds:[...u,a]};return(await o(c)).data?.attributes?.summary},Cr=new Set([O.QuestionType.POLL,O.QuestionType.PREDICTION,O.QuestionType.TRIVIA]);class Ko extends Gn{userSummary;feedList;betPack;friends;leaderboardId;leaderboardList;deepLink;onboardingStatus;openedQuestion;currentUserId;openedUser;closeFeature;openFeature;feedSubscription;activeQuestionId;openedQuestionId;advertisement;withPickHistory;onboardingProcessed;friendsTabEnabled;skipOnboarding;notifications;transport;background;storage;submitAnswerTimeout;cancels=new Set;onQuestionActivate;constructor(e,n,r){if(super(e,n),this.background=new bo(r),this.advertisement=this.background.advertisement,this.onQuestionActivate=r.onQuestionActivate,this.feedSubscription=this.background.feedSubscription,this.activeQuestionId=this.background.activeQuestionId,this.openedQuestionId=this.background.openedQuestionId,this.storage=this.background.storage,this.feedList=this.background.feedList,this.betPack=this.background.betPack,this.currentUserId=this.background.userId,this.withPickHistory=this.background.withPickHistory,this.onboardingProcessed=Z(!r.sdk.withAuth),this.leaderboardId=new le(Z(this.settings.getValue("pinnedLeaderboardId")),"pinnedLeaderboardId").getStore(),this.notifications=r.notifications,this.transport=r.transport,this.closeFeature=(i=!0)=>r.sdk.closeFeature(i),this.openFeature=()=>r.sdk.openFeature(Y.SdkOverlayType.GAMES),this.openedQuestion=this.background.openedQuestion,this.deepLink=jo(this.transport,this.background.slStreamId,r.stores.providerStreamId.getStore(),this.background.userId),this.userSummary=Go(this.background.slStreamId,this.background.userId,this.friends,this.transport),!r.sdk.options.get().hideFriends){this.friends=new fe(ro(this.background.userId,r.transport),"gamification:friends"),this.openedUser=Z(void 0);const i=this.leaderboardList=ko(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=!!r.sdk.options.get().skipOnboarding,this.onboardingStatus=Nr(this,this.background,r.transport,r.notifications,{skipOnboarding:r.sdk.options.get().skipOnboarding}),r.sdk.options.get().skipOnboarding||(this.onboardingStatus=Nr(this,this.background,r.transport,r.notifications,{skipOnboarding:r.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.background.activeQuestionId.listen(this.showInApp),this.friendsTabEnabled=Z(!1),this.cancels.add(r.sdk.options.subscribe(i=>{i.friendsTab==="disabled"?this.friendsTabEnabled.set(!1):i.friendsTab==="enabled"&&this.friendsTabEnabled.set(!0)})),this.cancels.add(this.settings.subscribe(i=>{r.sdk.options.get().friendsTab==="activatedGame"&&this.friendsTabEnabled.set(!!i.inplayGame?.titleCard?.optIn)})),r.sdk.onMount({name:"gamification",clear:!0},()=>()=>{for(const i of this.cancels)i(),this.cancels.delete(i)})}get isInteractiveAllowed(){return this.background.interactiveAllowed.get()===Oe.ALLOWED}checkInteractiveFlag=()=>{if(this.skipOnboarding)this.background.interactiveAllowed.set(Oe.ALLOWED);else{const e=this.onboardingStatus.$store.get(),n=this.background.moderation.getStore().value?.data?.options?.onboardingEnabled,r=this.settings.getValues().inplayGame?.titleCard?.optIn,i=e===ne.Completed,o=!n||i||r!==!0;this.background.interactiveAllowed.set(o?Oe.ALLOWED:Oe.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 n=e.data?.attributes?.question,r=e.data?.attributes?.feedItem;if(!n||!r?.attributes)return;const{status:i,type:o,id:s,answers:a}=n;if(i===O.QuestionStatus.RESOLVED&&o===O.QuestionType.PREDICTION){const u=this.background.getCurrentSessionId({prefix:`notification-id:${s}`}),c=[...this.feedList.getValues().data||[]],l=c.findIndex(S=>S.id===s),p=c[l];let d=p?.attributes?.attributes?.value?.answerId;const f=ot(s,this.transport),h=f.subscribe(()=>{});await f.fetch();let m=f.get().data;m||(m=await Hn(s,this.transport),f.mutate(m)),h(),window.requestAnimationFrame(()=>{f.invalidate()}),d||(d=m?.answers.find(({youVoted:S})=>S)?.id);const T=a.find(({correct:S})=>S),E=d?a.find(({id:S})=>S===d):void 0,g=!!E?.correct;if(p&&c[l]?.attributes?.attributes.case==="question"){try{c[l].attributes.attributes.value.answerId=d,c[l].attributes.attributes.value.openForVoting=!1,d&&(c[l].attributes.attributes.value.status=g?ie.PickHistoryStatus.WON:ie.PickHistoryStatus.LOST)}catch{}this.feedList.getStore().mutate(c)}if(!E||!T)return;this.openedQuestionId.get()?.questionId!==n.id&&this.notifications.add({type:Ee.QUESTION_RESOLVED,action:()=>this.openQuestion(n.id,r),close:()=>this.closeQuestion(s),autoHideDuration:g?15e3:14e3,id:u,emitEvent:!1,data:{questionId:s,questionType:O.QuestionType.PREDICTION,question:{title:g?`Congratulations! You answered correctly! You won ${T.points} pts!`:`Better luck next time! Correct: ${T?.text}!`,votedAnswer:{title:E?.text,points:E?.points},correctAnswerTitle:T?.text,correct:!!g,predictionResult:!0,questionTitle:n?.subject},inApp:{notification:n.notification,appearance:n.appearance,sponsorship:n.sponsorship,adUnit:n?.adUnit,sponsorLogo:n.promotion?.sponsor?.logo}}}),this.userSummary.invalidate()}})),ae.onStart(this.feedList.getStore(),()=>{this.cancels.add(this.feedList.subscribe(()=>{}))}),this.cancels.add(this.background.feedSubscription.addListener("feed-subscription-questions-list",e=>{const n=[...this.feedList.getStore().value?.data||[]],r=e.data?.attributes?.feedItem,i=n.findIndex(o=>o.id===r?.id);if(r?.attributes&&r.attributes.attributes.case!=="promotion"&&!(r.attributes.status!==O.QuestionStatus.ACTIVE&&r.attributes.status!==O.QuestionStatus.RESOLVED)&&!(!this.isInteractiveAllowed&&Cr.has(r.attributes.type)&&r?.attributes?.adUnit!==O.AdUnit.STANDART)){if(i!==-1)if(r.attributes.attributes.case==="question"&&n[i].attributes?.attributes.case==="question"){const o=n[i];o.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value,answerId:o.attributes.attributes.value.answerId,status:o.attributes.attributes.value.status,openForVoting:o.attributes.attributes.value.openForVoting===!1?!1:r.attributes.attributes.value.openForVoting}}}})}else{const o=n[i];o.attributes&&r.attributes&&(n[i]={...n[i],attributes:{...o.attributes,attributes:{...o.attributes.attributes,value:{...o.attributes.attributes.value,...r.attributes.attributes.value}}}})}i===-1&&this.feedList.isEnabled()&&n.unshift(r),this.feedList.isEnabled()&&this.feedList.getStore().mutate(n)}}))};disconnect=()=>{this.background.feedSubscription.removeListener("feed-subscription-prediction-close"),this.background.feedSubscription.removeListener("feed-subscription-questions-list")};betPackVote=async(e,n)=>{if(!this.betPack)return;try{await Sr(this.transport,{questionId:e,answerId:n})}catch(o){if(o.message===xe.ALREADY_VOTED){const s=ot(e,this.transport),a=s.subscribe(()=>{});s.invalidate(),a()}throw o}const r={...this.betPack.getValues().data?.data},i=r?.[e];i&&(K.emit("poll",{action:"voted",payload:{questionId:e,isAd:i?.adUnit==O.AdUnit.STANDART||i?.promotion?.adUnit==O.AdUnit.STANDART,questionType:i.type}}),i.answers=i.answers.map(o=>o.id===n?{...o,youVoted:!0}:o),this.betPack.getStore().mutate({data:r,timestamp:Date.now()}))};submitAnswer=async(e,n)=>{const r=ot(e,this.transport),i=r.subscribe(()=>{}),o={...r.get().data||{}},s=()=>{const a=this.feedList.getValues().data,u=a?.findIndex(f=>f.id===e),c=u&&u>=0&&a?a[u]:void 0,l=c?.attributes?.attributes.case==="question"&&c?.attributes?.attributes.value||o,p=c?.attributes?.adUnit==O.AdUnit.STANDART||c?.attributes?.adPromotion?.adUnit==O.AdUnit.STANDART||o?.adUnit==O.AdUnit.STANDART||o?.promotion?.adUnit==O.AdUnit.STANDART,d=c?.attributes?.type||o?.type;if(l){K.emit("poll",{action:"voted",payload:{isAd:p,questionId:e,questionType:d}});const f=r.get().data;if(i(),f){const h=f.answers.find(g=>g.correct===!0),m=f.answers.findIndex(g=>g.id===n),T=f.answers[m],E=f.answers.every(({percentageDecimal:g},S)=>g===o?.answers[S].percentageDecimal);a&&u&&u>=0&&(a[u].attributes.attributes.value.answerId=n,a[u].attributes.attributes.value.openForVoting=!1,a[u].attributes.attributes.value.text=T?.text||"",h&&(a[u].attributes.attributes.value.status=h.id===n?ie.PickHistoryStatus.WON:ie.PickHistoryStatus.LOST),this.feedList.getStore().mutate([...a])),f.answers[m].correct=h?.id===n,f.answers[m].youVoted=!0,E&&f.answers.forEach(g=>{g.percentageDecimal=0}),h?.id===n&&(f.answers[m].pointsEarned=f.status===O.QuestionStatus.RESOLVED?0:h.points),r.mutate({...f})}this.submitAnswerTimeout&&clearTimeout(this.submitAnswerTimeout),this.submitAnswerTimeout=setTimeout(()=>{this.userSummary.invalidate()},1e3)}};try{await Sr(this.transport,{questionId:e,answerId:n}),s()}catch(a){if(a.message===xe.ALREADY_VOTED){this.userSummary.invalidate();const u=r.subscribe(()=>{});r.invalidate(),u()}throw a}};openQuestion=(e,n)=>{if(!e)return()=>{};const r=n?.openedFrom==="bet-pack";this.notifications.close(this.background.getCurrentSessionId({prefix:"notification",entity:e}),{animateHiding:!1});let i=n?.attributes?.type,o=(n?.attributes?.adUnit===O.AdUnit.STANDART||n?.attributes?.adPromotion?.adUnit===O.AdUnit.STANDART)&&!!n?.attributes?.adPromotion?.banner?.imageUrl;if(!i&&!r){const u=(this.feedList.getStore().value?.data||[]).find(c=>c.id===e)?.attributes;i=u?.type,o=(u?.adUnit===O.AdUnit.STANDART||u?.adPromotion?.adUnit===O.AdUnit.STANDART)&&!!u?.adPromotion?.banner?.imageUrl}const s={eventId:this.background.slStreamId.get()||"",userId:this.background.userId.get()||"",organizationId:this.background.organizationId.get()||""};return K.emit("poll",{action:"opened",payload:{questionId:e,questionType:i,isAd:n?.attributes?.adUnit!=O.AdUnit.UNSET,questionOpenedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom,hasBanner:o}}),this.storage.isQuestionOpened(s,e)||(K.emit("poll",{action:"viewed",payload:{questionId:e,questionType:i,isAd:n?.attributes?.adUnit!=O.AdUnit.UNSET,questionOpenedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}}),this.storage.saveQuestionOpened(s,e)),r||this.openFeature(),this.background.openQuestion(e,n?{...n,openedFrom:n?.openedFrom==="bet-pack"?"list":n?.openedFrom}:void 0)};getFeedItem=e=>oo(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}))}),K.emit("poll",{action:"closed",payload:{questionId:e}})),this.background.closeQuestion(e));openUser=async e=>{if(!this.leaderboardList)return;const n=this.leaderboardList?.$store.get().data?.find(i=>i.userId===e);if(!n){this.openedUser?.set(n);return}if(n.summaryLoaded){this.openedUser?.set(n);return}const r={...n};try{const i=await Wo(this.background.slStreamId,this.background.userId,this.friends,e,this.transport);i?.inTop!==void 0&&(this.leaderboardList?.$store.setKey("data",this.leaderboardList.$store.get().data?.map(o=>(o.userId===e&&(o.inTop=i.inTop),o))),r.inTop=i.inTop)}catch(i){console.error(i)}this.openedUser.set(r)};closeUser=()=>{this.openedUser?.set(void 0)};openOnboarding=()=>{this.openFeature(),K.emit("poll",{action:"onboardingOpen",payload:{}})};sendWebhookEvent=(e,n)=>Io(this.transport,{eventId:this.background.slStreamId.get(),questionId:e,userId:this.background.userId.get(),userAccountInfo:n});showInApp=e=>{if(e.loading)return;const n=this.onboardingStatus.$store.get(),r=e?.data?.question?.adUnit===O.AdUnit.STANDART;if(e&&e.data&&(r||n&&n!==ne.Unset)&&e.data.question?.id!==void 0&&e.data.question?.bypassNotifications?.inAppSilence!==O.SilenceSetting.ON&&e.data.question.status===O.QuestionStatus.ACTIVE&&!e.data.question.marketClosed){if(Cr.has(e.data.question.type))(this.isInteractiveAllowed||r)&&e.data.question.notification!==void 0&&(e.data.question.notification.enabled===O.NotificationEnabled.NOTIFICATION_ENABLED?this.notifications.add({type:Ee.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}}}):this.openQuestion(e.data?.question?.id,e.data?.feedItem));else if(e.data.question.type===O.QuestionType.FACTOID){const i=e.data.question.options?.options.value,o=e.data.question.notification?.useContentTexts===O.NotificationUseContentTexts.ENABLED?e.data.question.subject:e.data.question.notification?.title||"",s=e.data.question.notification?.useContentTexts===O.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:Ee.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===O.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===O.FactoidMediaMode.VIDEO}}})}else if(e.data.question.type===O.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:Ee.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 Ho={[Y.SdkOverlayType.GAMES]:!0};class $o extends Gn{constructor(e,n){super(e,n)}}const zo=(t,e,n)=>t.type===Y.SdkOverlayType.GAMES?new Ko(t,e,n):new $o(t,e),Yo=(t,e,n)=>{t.features=new Map,t.sdk.featuresList=new le(Z(new Set),"features-list"),t.activeFeature=new le(Z(Y.SdkOverlayType.UNSET),"activeFeature"),t.sdk.getFeatures=()=>t.features,t.sdk.getFeature=r=>t.features.get(r),t.sdk.getActiveFeature=()=>t.activeFeature.getStore(),t.sdk.openFeature=r=>{t.sdk.initializeApp().then(()=>{t.activeFeature.setValue(r)})},t.sdk.closeFeature=(r=!1)=>{const i=t.activeFeature.getValue();if(t.activeFeature.setValue(Y.SdkOverlayType.UNSET),r&&i){t.features.delete(i);const o=t.sdk.featuresList.getValue();o&&o.delete(i),t.sdk.featuresList.setValue(o)}},t.initFeature=(r,i=Te.ORGANIZATION)=>{if(r.type in Ho&&!t.features.has(r.type)){const o=zo(r,i,t);t.features.set(r.type,o);let s=t.sdk.featuresList.getValue();s?s.add(r.type):s=new Set([r.type]),t.sdk.featuresList.setValue(new Set(s))}},t.updateFeature=(r,i)=>{t.features.get(r.type)?.update(r,i)},t.destroyFeature=r=>{t.features.delete(r.type);const i=t.sdk.featuresList.getValue();i&&i.delete(r.type),t.sdk.featuresList.setValue(new Set(i))},t.reinitializeFeatures=async()=>{const r=await t.stores.organizationSettings.getValue();t.features.clear(),t.sdk.featuresList.setValue(new Set);for(const i of r?.overlays||[])t.initFeature(i,Te.ORGANIZATION)},t.stores.providerStreamId.listen(r=>{r||t.reinitializeFeatures()}),t.storeSubscribe=()=>{const r=(o,s)=>{if(s?.overlays&&!(t.contextConfig?.skipOrganizationSettings&&o===Te.ORGANIZATION))for(const a of s.overlays)a.sdkEnable===!0&&(t.features.has(a.type)?t.updateFeature(a,o):t.initFeature(a,o))},i={organizationSettings:o=>{if(o.data)try{r(Te.ORGANIZATION,o.data)}catch(s){console.log(s)}},streamSettings:o=>{if(o.data)try{r(Te.STREAM,o.data)}catch(s){console.log(s)}}};t.store.subscribe(i)},n()},Xo=(t,e,n)=>{const{client:r,queryKey:i}=n.createPromiseClient(gr.PolymarketSportsClient,{method:"getMarketWithSeries",params:[t,e]});return n.nanoquery.createFetcherStore(i,{fetcher:async(o,s,a,u)=>{if(u)try{return(await r.getMarketWithSeries({eventId:a,timeframe:gr.Timeframe.TIMEFRAME_ALL})).event}catch{return}}})},Jo=t=>{const e=t.stores.slStreamId.getAtomStore(),n=t.stores.user.getAtomStore();return Xo(e,n,t.transport)};class Zo extends Qn{marketWithSeries;log;constructor(e){super(),this.log=ue("polymarket"),this.marketWithSeries=Jo(e)}connect=()=>{this.log.debug("connect")};disconnect=()=>{this.marketWithSeries.off(),this.log.debug("disconnect")}}const es=(t,e,n)=>{t.sdk.polymarket=new Zo(t),t.sdk.onMount({name:"polymarket"},()=>(t.sdk.polymarket.connect(),()=>{t.sdk.polymarket.disconnect()})),n()};function ar(){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 ts=["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 Rr(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=[],i=Zn(t);!e.ERRORCODE||n.isCustomCode||/^[0-9]{3}$/.test(e.ERRORCODE)||(e.ERRORCODE=900),e.CACHEBUSTING=ri(Math.round(1e8*Math.random())),e.TIMESTAMP=new Date().toISOString(),e.RANDOM=e.random=e.CACHEBUSTING;for(const o in e)e[o]=ti(e[o]);for(const o in i){const s=i[o];typeof s=="string"&&r.push(Jn(s,e))}return r}function Jn(t,e){const n=(t=Pr(t,e)).match(/[^[\]]+(?=])/g);if(!n)return t;let r=n.filter((i=>ts.indexOf(i)>-1));return r.length===0?t:(r=r.reduce(((i,o)=>(i[o]=-1,i)),{}),Pr(t,r))}function Pr(t,e){let n=t;for(const r in e){const i=e[r];n=n.replace(new RegExp("(?:\\[|%%)(".concat(r,")(?:\\]|%%)"),"g"),i)}return n}function Zn(t){return Array.isArray(t)?t.map((e=>e&&e.hasOwnProperty("url")?e.url:e)):t}function Lr(t){return/^(https?:\/\/|\/\/)/.test(t)}function _r(t,e){for(let n=0;n<e.length;n++)if(ei(e[n],t))return!0;return!1}function ei(t,e){if(t&&e){const n=Object.getOwnPropertyNames(t),r=Object.getOwnPropertyNames(e);return n.length===r.length&&t.id===e.id&&t.url===e.url}return!1}function ti(t){return encodeURIComponent(t).replace(/[!'()*]/g,(e=>"%".concat(e.charCodeAt(0).toString(16))))}function ri(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:8;return t.toString().padStart(e,"0")}const Re={track:function(t,e,n){Rr(t,e,n).forEach((r=>{typeof window<"u"&&window!==null&&(new Image().src=r)}))},resolveURLTemplates:Rr,extractURLsFromTemplates:Zn,filterUrlTemplates:function(t){return t.reduce(((e,n)=>{const r=n.url||n;return Lr(r)?e.validUrls.push(r):e.invalidUrls.push(r),e}),{validUrls:[],invalidUrls:[]})},containsTemplateObject:_r,isTemplateObjectEqual:ei,encodeURIComponentRFC3986:ti,replaceUrlMacros:Jn,isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)},flatten:function t(e){return e.reduce(((n,r)=>n.concat(Array.isArray(r)?t(r):r)),[])},joinArrayOfUniqueTemplateObjs:function(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];const n=Array.isArray(t)?t:[],r=Array.isArray(e)?e:[];return n.concat(r).reduce(((i,o)=>(_r(o,i)||i.push(o),i)),[])},isValidTimeValue:function(t){return Number.isFinite(t)&&t>=-2},addLeadingZeros:ri,isValidUrl:Lr,isBrowserEnvironment:function(){return typeof window<"u"},formatMacrosValues:function(t){return typeof t!="object"?t:JSON.stringify(t)}};function Dr(t){return["true","TRUE","True","1"].includes(t)}function rs(t){if(t==null)return-1;if(Re.isNumeric(t))return parseInt(t);const e=t.split(":");if(e.length!==3)return-1;const n=e[2].split(".");let r=parseInt(n[0]);n.length===2&&(r+=parseFloat("0.".concat(n[1])));const i=parseInt(60*e[1]),o=parseInt(60*e[0]*60);return isNaN(o)||isNaN(i)||isNaN(r)||i>3600||r>60?-1:o+i+r}const A={childByName:function(t,e){return Array.from(t.childNodes).find((n=>n.nodeName===e))},childrenByName:function(t,e){return Array.from(t.childNodes).filter((n=>n.nodeName===e))},resolveVastAdTagURI:function(t,e){if(!e)return t;if(t.startsWith("//")){const{protocol:n}=location;return"".concat(n).concat(t)}if(!t.includes("://")){const n=e.slice(0,e.lastIndexOf("/"));return"".concat(n,"/").concat(t)}return t},parseBoolean:Dr,parseNodeText:function(t){return t&&(t.textContent||t.text||"").trim()},copyNodeAttribute:function(t,e,n){const r=e.getAttribute(t);r&&n.setAttribute(t,r)},parseAttributes:function(t){return Array.from(t.attributes).reduce(((e,n)=>(e[n.nodeName]=n.nodeValue,e)),{})},parseDuration:rs,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((n=>{let{nodeName:r,nodeValue:i}=n;if(r&&i&&e.hasOwnProperty(r)){let o=i;typeof e[r]=="boolean"&&(o=Dr(o)),e[r]=o}}))},mergeWrapperAdData:function(t,e){var n;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 r=(e.creatives||[]).filter((a=>a&&a.type==="companion")),i=r.reduce(((a,u)=>((u.variations||[]).forEach((c=>{(c.companionClickTrackingURLTemplates||[]).forEach((l=>{Re.containsTemplateObject(l,a)||a.push(l)}))})),a)),[]);t.creatives=r.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=Re.joinArrayOfUniqueTemplateObjs(u.companionClickTrackingURLTemplates,i)}))})),e.adVerifications&&(t.adVerifications=t.adVerifications.concat(e.adVerifications)),e.blockedAdCategories&&(t.blockedAdCategories=t.blockedAdCategories.concat(e.blockedAdCategories)),(n=e.creatives)!==null&&n!==void 0&&n.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 ns(t,e){const n=(function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=ar(r);return{id:i,adId:o,sequence:s,apiFramework:a,type:"companion",required:null,variations:[]}})(e);return n.required=t.getAttribute("required")||null,n.variations=A.childrenByName(t,"Companion").map((r=>{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:{}}})(A.parseAttributes(r));i.htmlResources=A.childrenByName(r,"HTMLResource").reduce(((a,u)=>{const c=A.parseNodeText(u);return c?a.concat(c):a}),[]),i.iframeResources=A.childrenByName(r,"IFrameResource").reduce(((a,u)=>{const c=A.parseNodeText(u);return c?a.concat(c):a}),[]),i.staticResources=A.childrenByName(r,"StaticResource").reduce(((a,u)=>{const c=A.parseNodeText(u);return c?a.concat({url:c,creativeType:u.getAttribute("creativeType")||null}):a}),[]),i.altText=A.parseNodeText(A.childByName(r,"AltText"))||null;const o=A.childByName(r,"TrackingEvents");o&&A.childrenByName(o,"Tracking").forEach((a=>{const u=a.getAttribute("event"),c=A.parseNodeText(a);u&&c&&(Array.isArray(i.trackingEvents[u])||(i.trackingEvents[u]=[]),i.trackingEvents[u].push(c))})),i.companionClickTrackingURLTemplates=A.childrenByName(r,"CompanionClickTracking").map((a=>({id:a.getAttribute("id")||null,url:A.parseNodeText(a)}))),i.companionClickThroughURLTemplate=A.parseNodeText(A.childByName(r,"CompanionClickThrough"))||null;const s=A.childByName(r,"AdParameters");return s&&(i.adParameters={value:A.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),i})),n}function is(t,e){let n;const r=(function(){let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:c,adId:l,sequence:p,apiFramework:d}=ar(u);return{id:c,adId:l,sequence:p,apiFramework:d,type:"linear",duration:0,skipDelay:null,mediaFiles:[],mezzanine:null,interactiveCreativeFile:null,closedCaptionFiles:[],videoClickThroughURLTemplate:null,videoClickTrackingURLTemplates:[],videoCustomClickURLTemplates:[],adParameters:null,icons:[],trackingEvents:{}}})(e);r.duration=A.parseDuration(A.parseNodeText(A.childByName(t,"Duration")));const i=t.getAttribute("skipoffset");if(i==null)r.skipDelay=null;else if(i.charAt(i.length-1)==="%"&&r.duration!==-1){const u=parseInt(i,10);r.skipDelay=r.duration*(u/100)}else r.skipDelay=A.parseDuration(i);const o=A.childByName(t,"VideoClicks");if(o){const u=A.childByName(o,"ClickThrough");r.videoClickThroughURLTemplate=u?{id:u.getAttribute("id")||null,url:A.parseNodeText(u)}:null,A.childrenByName(o,"ClickTracking").forEach((c=>{r.videoClickTrackingURLTemplates.push({id:c.getAttribute("id")||null,url:A.parseNodeText(c)})})),A.childrenByName(o,"CustomClick").forEach((c=>{r.videoCustomClickURLTemplates.push({id:c.getAttribute("id")||null,url:A.parseNodeText(c)})}))}const s=A.childByName(t,"AdParameters");s&&(r.adParameters={value:A.parseNodeText(s),xmlEncoded:s.getAttribute("xmlEncoded")||null}),A.childrenByName(t,"TrackingEvents").forEach((u=>{A.childrenByName(u,"Tracking").forEach((c=>{let l=c.getAttribute("event");const p=A.parseNodeText(c);if(l&&p){if(l==="progress"){if(n=c.getAttribute("offset"),!n)return;l=n.charAt(n.length-1)==="%"?"progress-".concat(n):"progress-".concat(A.parseDuration(n))}Array.isArray(r.trackingEvents[l])||(r.trackingEvents[l]=[]),r.trackingEvents[l].push(p)}}))})),A.childrenByName(t,"MediaFiles").forEach((u=>{A.childrenByName(u,"MediaFile").forEach((f=>{r.mediaFiles.push((function(h){const m={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};m.id=h.getAttribute("id"),m.fileURL=A.parseNodeText(h),m.deliveryType=h.getAttribute("delivery"),m.codec=h.getAttribute("codec"),m.mimeType=h.getAttribute("type"),m.mediaType=h.getAttribute("mediaType")||"2D",m.apiFramework=h.getAttribute("apiFramework"),m.fileSize=parseInt(h.getAttribute("fileSize")||0),m.bitrate=parseInt(h.getAttribute("bitrate")||0),m.minBitrate=parseInt(h.getAttribute("minBitrate")||0),m.maxBitrate=parseInt(h.getAttribute("maxBitrate")||0),m.width=parseInt(h.getAttribute("width")||0),m.height=parseInt(h.getAttribute("height")||0);const T=h.getAttribute("scalable");T&&typeof T=="string"&&(m.scalable=A.parseBoolean(T));const E=h.getAttribute("maintainAspectRatio");return E&&typeof E=="string"&&(m.maintainAspectRatio=A.parseBoolean(E)),m})(f))}));const c=A.childByName(u,"InteractiveCreativeFile");c&&(r.interactiveCreativeFile=(function(f){const h=(function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:m.type||null,apiFramework:m.apiFramework||null,variableDuration:A.parseBoolean(m.variableDuration),fileURL:null}})(A.parseAttributes(f));return h.fileURL=A.parseNodeText(f),h})(c));const l=A.childByName(u,"ClosedCaptionFiles");l&&A.childrenByName(l,"ClosedCaptionFile").forEach((f=>{const h=(function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return{type:m.type||null,language:m.language||null,fileURL:null}})(A.parseAttributes(f));h.fileURL=A.parseNodeText(f),r.closedCaptionFiles.push(h)}));const p=A.childByName(u,"Mezzanine"),d=(function(f,h){const m={};let T=!1;return h.forEach((E=>{f&&f.getAttribute(E)?m[E]=f.getAttribute(E):T=!0})),T?null:m})(p,["delivery","type","width","height"]);if(d){const f={id:null,fileURL:null,delivery:null,codec:null,type:null,width:0,height:0,fileSize:0,mediaType:"2D"};f.id=p.getAttribute("id"),f.fileURL=A.parseNodeText(p),f.delivery=d.delivery,f.codec=p.getAttribute("codec"),f.type=d.type,f.width=parseInt(d.width,10),f.height=parseInt(d.height,10),f.fileSize=parseInt(p.getAttribute("fileSize"),10),f.mediaType=p.getAttribute("mediaType")||"2D",r.mezzanine=f}}));const a=A.childByName(t,"Icons");return a&&A.childrenByName(a,"Icon").forEach((u=>{r.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(d){return["left","right"].indexOf(d)!==-1?d:parseInt(d||0)})(c.getAttribute("xPosition")),l.yPosition=(function(d){return["top","bottom"].indexOf(d)!==-1?d:parseInt(d||0)})(c.getAttribute("yPosition")),l.apiFramework=c.getAttribute("apiFramework"),l.pxratio=c.getAttribute("pxratio")||"1",l.offset=A.parseDuration(c.getAttribute("offset")),l.duration=A.parseDuration(c.getAttribute("duration")),l.altText=c.getAttribute("altText"),l.hoverText=c.getAttribute("hoverText"),A.childrenByName(c,"HTMLResource").forEach((d=>{l.type=d.getAttribute("creativeType")||"text/html",l.htmlResource=A.parseNodeText(d)})),A.childrenByName(c,"IFrameResource").forEach((d=>{l.type=d.getAttribute("creativeType")||0,l.iframeResource=A.parseNodeText(d)})),A.childrenByName(c,"StaticResource").forEach((d=>{l.type=d.getAttribute("creativeType")||0,l.staticResource=A.parseNodeText(d)}));const p=A.childByName(c,"IconClicks");if(p){l.iconClickThroughURLTemplate=A.parseNodeText(A.childByName(p,"IconClickThrough")),A.childrenByName(p,"IconClickTracking").forEach((f=>{l.iconClickTrackingURLTemplates.push({id:f.getAttribute("id")||null,url:A.parseNodeText(f)})}));const d=A.childByName(p,"IconClickFallbackImages");d&&A.childrenByName(d,"IconClickFallbackImage").forEach((f=>{l.iconClickFallbackImages.push({url:A.parseNodeText(f)||null,width:f.getAttribute("width")||null,height:f.getAttribute("height")||null})}))}return l.iconViewTrackingURLTemplate=A.parseNodeText(A.childByName(c,"IconViewTracking")),l})(u))})),r}function os(t,e){const n=(function(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{id:i,adId:o,sequence:s,apiFramework:a}=ar(r);return{id:i,adId:o,sequence:s,apiFramework:a,type:"nonlinear",variations:[],trackingEvents:{}}})(e);return A.childrenByName(t,"TrackingEvents").forEach((r=>{let i,o;A.childrenByName(r,"Tracking").forEach((s=>{i=s.getAttribute("event"),o=A.parseNodeText(s),i&&o&&(Array.isArray(n.trackingEvents[i])||(n.trackingEvents[i]=[]),n.trackingEvents[i].push(o))}))})),A.childrenByName(t,"NonLinear").forEach((r=>{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=r.getAttribute("id")||null,i.width=r.getAttribute("width"),i.height=r.getAttribute("height"),i.expandedWidth=r.getAttribute("expandedWidth"),i.expandedHeight=r.getAttribute("expandedHeight"),i.scalable=A.parseBoolean(r.getAttribute("scalable")),i.maintainAspectRatio=A.parseBoolean(r.getAttribute("maintainAspectRatio")),i.minSuggestedDuration=A.parseDuration(r.getAttribute("minSuggestedDuration")),i.apiFramework=r.getAttribute("apiFramework"),A.childrenByName(r,"HTMLResource").forEach((s=>{i.type=s.getAttribute("creativeType")||"text/html",i.htmlResource=A.parseNodeText(s)})),A.childrenByName(r,"IFrameResource").forEach((s=>{i.type=s.getAttribute("creativeType")||0,i.iframeResource=A.parseNodeText(s)})),A.childrenByName(r,"StaticResource").forEach((s=>{i.type=s.getAttribute("creativeType")||0,i.staticResource=A.parseNodeText(s)}));const o=A.childByName(r,"AdParameters");o&&(i.adParameters={value:A.parseNodeText(o),xmlEncoded:o.getAttribute("xmlEncoded")||null}),i.nonlinearClickThroughURLTemplate=A.parseNodeText(A.childByName(r,"NonLinearClickThrough")),A.childrenByName(r,"NonLinearClickTracking").forEach((s=>{i.nonlinearClickTrackingURLTemplates.push({id:s.getAttribute("id")||null,url:A.parseNodeText(s)})})),n.variations.push(i)})),n}function Fr(t){const e=[];return t.forEach((n=>{const r=ni(n);r&&e.push(r)})),e}function ni(t){if(t.nodeName==="#comment")return null;const e={name:null,value:null,attributes:{},children:[]},n=t.attributes,r=t.childNodes;if(e.name=t.nodeName,t.attributes){for(const o in n)if(n.hasOwnProperty(o)){const s=n[o];s.nodeName&&s.nodeValue&&(e.attributes[s.nodeName]=s.nodeValue)}}for(const o in r)if(r.hasOwnProperty(o)){const s=ni(r[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=A.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 ss(t){return t.getAttribute("AdID")||t.getAttribute("adID")||t.getAttribute("adId")||null}const st={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 Ur(t,e){if(!st[t.nodeName]||!st[t.nodeName].attributes)return;const n=st[t.nodeName].attributes.filter((r=>!t.getAttribute(r)));n.length>0&&Qe({name:t.nodeName,parentName:t.parentNode.nodeName,attributes:n},e)}function Vr(t,e,n){const r=st[t.nodeName],i=!n&&t.nodeName!=="Wrapper";if(!(!r||i)){if(r.subElements){const o=r.subElements.filter((s=>!A.childByName(t,s)));o.length>0&&Qe({name:t.nodeName,parentName:t.parentNode.nodeName,subElements:o},e)}!n||!r.oneOfinLineResources||r.oneOfinLineResources.some((o=>A.childByName(t,o)))||Qe({name:t.nodeName,parentName:t.parentNode.nodeName,oneOfResources:r.oneOfinLineResources},e)}}function xr(t){return t.children&&t.children.length!==0}function Qe(t,e){let{name:n,parentName:r,attributes:i,subElements:o,oneOfResources:s}=t,a="Element '".concat(n,"'");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:r,specVersion:4.1})}const as={verifyRequiredValues:function t(e,n,r){if(e&&e.nodeName)if(e.nodeName==="InLine"&&(r=!0),Ur(e,n),xr(e)){Vr(e,n,r);for(let i=0;i<e.children.length;i++)t(e.children[i],n,r)}else A.parseNodeText(e).length===0&&Qe({name:e.nodeName,parentName:e.parentNode.nodeName},n)},hasSubElements:xr,emitMissingValueWarning:Qe,verifyRequiredAttributes:Ur,verifyRequiredSubElements:Vr};function us(t,e){let{allowMultipleAds:n,followAdditionalWrappers:r}=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"||r!==!1&&s==="wrapper"}));for(const o of i){if(A.copyNodeAttribute("id",t,o),A.copyNodeAttribute("sequence",t,o),A.copyNodeAttribute("adType",t,o),o.nodeName==="Wrapper")return{ad:ls(o,e),type:"WRAPPER"};if(o.nodeName==="InLine")return{ad:cs(o,e,{allowMultipleAds:n}),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:n}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return n===!1&&t.getAttribute("sequence")?null:ii(t,e)}function ii(t,e){let n=[];e&&as.verifyRequiredValues(t,e);const r=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}})(A.parseAttributes(t));return r.forEach((o=>{switch(o.nodeName){case"Error":i.errorURLTemplates.push(A.parseNodeText(o));break;case"Impression":i.impressionURLTemplates.push({id:o.getAttribute("id")||null,url:A.parseNodeText(o)});break;case"Creatives":i.creatives=(function(s){const a=[];return s.forEach((u=>{const c={id:u.getAttribute("id")||null,adId:ss(u),sequence:u.getAttribute("sequence")||null,apiFramework:u.getAttribute("apiFramework")||null},l=[];let p;A.childrenByName(u,"UniversalAdId").forEach((f=>{const h={idRegistry:f.getAttribute("idRegistry")||"unknown",value:A.parseNodeText(f)};l.push(h)}));const d=A.childByName(u,"CreativeExtensions");d&&(p=Fr(A.childrenByName(d,"CreativeExtension")));for(const f in u.childNodes){const h=u.childNodes[f];let m;switch(h.nodeName){case"Linear":m=is(h,c);break;case"NonLinearAds":m=os(h,c);break;case"CompanionAds":m=ns(h,c)}m&&(l&&(m.universalAdIds=l),p&&(m.creativeExtensions=p),a.push(m))}})),a})(A.childrenByName(o,"Creative"));break;case"Extensions":{const s=A.childrenByName(o,"Extension");i.extensions=Fr(s),i.adVerifications.length||(n=(function(a){let u=null,c=[];return a.some((l=>u=A.childByName(l,"AdVerifications"))),u&&(c=Br(A.childrenByName(u,"Verification"))),c})(s));break}case"AdVerifications":i.adVerifications=Br(A.childrenByName(o,"Verification"));break;case"AdSystem":i.system={value:A.parseNodeText(o),version:o.getAttribute("version")||null};break;case"AdTitle":i.title=A.parseNodeText(o);break;case"AdServingId":i.adServingId=A.parseNodeText(o);break;case"Category":i.categories.push({authority:o.getAttribute("authority")||null,value:A.parseNodeText(o)});break;case"Expires":i.expires=parseInt(A.parseNodeText(o),10);break;case"ViewableImpression":i.viewableImpression.push((function(s){const a=(u,c)=>{const l=A.parseNodeText(c);return l&&u.push(l),u};return{id:s.getAttribute("id")||null,viewable:A.childrenByName(s,"Viewable").reduce(a,[]),notViewable:A.childrenByName(s,"NotViewable").reduce(a,[]),viewUndetermined:A.childrenByName(s,"ViewUndetermined").reduce(a,[])}})(o));break;case"Description":i.description=A.parseNodeText(o);break;case"Advertiser":i.advertiser={id:o.getAttribute("id")||null,value:A.parseNodeText(o)};break;case"Pricing":i.pricing={value:A.parseNodeText(o),model:o.getAttribute("model")||null,currency:o.getAttribute("currency")||null};break;case"Survey":i.survey={value:A.parseNodeText(o),type:o.getAttribute("type")||null};break;case"BlockedAdCategories":i.blockedAdCategories.push({authority:o.getAttribute("authority")||null,value:A.parseNodeText(o)})}})),n.length&&(i.adVerifications=i.adVerifications.concat(n)),i}function ls(t,e){const n=ii(t,e),r=t.getAttribute("followAdditionalWrappers"),i=t.getAttribute("allowMultipleAds"),o=t.getAttribute("fallbackOnNoAd");n.followAdditionalWrappers=!r||A.parseBoolean(r),n.allowMultipleAds=!!i&&A.parseBoolean(i),n.fallbackOnNoAd=o?A.parseBoolean(o):null;let s=A.childByName(t,"VASTAdTagURI");if(s?n.nextWrapperURL=A.parseNodeText(s):(s=A.childByName(t,"VASTAdTagURL"),s&&(n.nextWrapperURL=A.parseNodeText(A.childByName(s,"URL")))),n.creatives.forEach((a=>{if(["linear","nonlinear"].includes(a.type)){if(a.trackingEvents){n.trackingEvents||(n.trackingEvents={}),n.trackingEvents[a.type]||(n.trackingEvents[a.type]={});for(const u in a.trackingEvents){const c=a.trackingEvents[u];Array.isArray(n.trackingEvents[a.type][u])||(n.trackingEvents[a.type][u]=[]),c.forEach((l=>{n.trackingEvents[a.type][u].push(l)}))}}a.videoClickTrackingURLTemplates&&(Array.isArray(n.videoClickTrackingURLTemplates)||(n.videoClickTrackingURLTemplates=[]),a.videoClickTrackingURLTemplates.forEach((u=>{n.videoClickTrackingURLTemplates.push(u)}))),a.videoClickThroughURLTemplate&&(n.videoClickThroughURLTemplate=a.videoClickThroughURLTemplate),a.videoCustomClickURLTemplates&&(Array.isArray(n.videoCustomClickURLTemplates)||(n.videoCustomClickURLTemplates=[]),a.videoCustomClickURLTemplates.forEach((u=>{n.videoCustomClickURLTemplates.push(u)})))}})),n.nextWrapperURL)return n}function Br(t){const e=[];return t.forEach((n=>{const r={resource:null,vendor:null,browserOptional:!1,apiFramework:null,type:null,parameters:null,trackingEvents:{}},i=Array.from(n.childNodes);A.assignAttributes(n.attributes,r),i.forEach((s=>{let{nodeName:a,textContent:u,attributes:c}=s;switch(a){case"JavaScriptResource":case"ExecutableResource":r.resource=u.trim(),A.assignAttributes(c,r);break;case"VerificationParameters":r.parameters=u.trim()}}));const o=A.childByName(n,"TrackingEvents");o&&A.childrenByName(o,"Tracking").forEach((s=>{const a=s.getAttribute("event"),u=A.parseNodeText(s);a&&u&&(Array.isArray(r.trackingEvents[a])||(r.trackingEvents[a]=[]),r.trackingEvents[a].push(u))})),e.push(r)})),e}class ds{constructor(){this._handlers=[]}on(e,n){if(typeof n!="function")throw new TypeError("The handler argument must be of type Function. Received type ".concat(typeof n));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:n}),this}once(e,n){return this.on(e,(function(r,i,o){const s={fired:!1,wrapFn:void 0};function a(){s.fired||(r.off(i,s.wrapFn),s.fired=!0,o.bind(r)(...arguments))}return s.wrapFn=a,a})(this,e,n))}off(e,n){return this._handlers=this._handlers.filter((r=>r.event!==e||r.handler!==n)),this}emit(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];let o=!1;return this._handlers.forEach((s=>{s.event==="*"&&(o=!0,s.handler(e,...r)),s.event===e&&(o=!0,s.handler(...r))})),o}removeAllListeners(e){return e?(this._handlers=this._handlers.filter((n=>n.event!==e)),this):(this._handlers=[],this)}listenerCount(e){return this._handlers.filter((n=>n.event===e)).length}listeners(e){return this._handlers.reduce(((n,r)=>(r.event===e&&n.push(r.handler),n)),[])}eventNames(){return this._handlers.map((e=>e.event))}}let qr=0,nr=0;const oi=(t,e)=>{!t||!e||t<=0||e<=0||(nr=(nr*qr+8*t/e)/++qr)},ps={ERRORCODE:900,extensions:[]},Mr="VAST response version not supported";class fs extends ds{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,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];this.emit("VAST-error",Object.assign({},ps,n,...i)),Re.track(e,n)}getErrorURLTemplates(){return this.rootErrorURLTemplates.concat(this.errorURLTemplates)}getEstimatedBitrate(){return nr}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(),oi(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 n=e?this.remainingAds:[this.remainingAds.shift()];return this.errorURLTemplates=[],this.resolveAds(n,{wrapperDepth:0,url:this.rootURL}).then((r=>this.buildVASTResponse(r)))}parseVAST(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.initParsingStatus(n),n.isRootVAST=!0,this.parse(e,n).then((r=>this.buildVASTResponse(r)))}buildVASTResponse(e){const n=(function(r){let{ads:i,errorURLTemplates:o,version:s}=r;return{ads:i||[],errorURLTemplates:o||[],version:s||null}})({ads:e,errorURLTemplates:this.getErrorURLTemplates(),version:this.vastVersion});return this.completeWrapperResolving(n),n}parseVastXml(e,n){let{isRootVAST:r=!1,url:i=null,wrapperDepth:o=0,allowMultipleAds:s,followAdditionalWrappers:a}=n;if(!e||!e.documentElement||e.documentElement.nodeName!=="VAST"){var u;this.emit("VAST-ad-parsed",{type:"ERROR",url:i,wrapperDepth:o});const d=(e==null||(u=e.documentElement)===null||u===void 0?void 0:u.nodeName)==="VideoAdServingTemplate";throw new Error(d?Mr:"Invalid VAST XMLDocument")}const c=[],l=e.documentElement.childNodes,p=e.documentElement.getAttribute("version");r&&p&&(this.vastVersion=p);for(const d in l){const f=l[d];if(f.nodeName==="Error"){const h=A.parseNodeText(f);r?this.rootErrorURLTemplates.push(h):this.errorURLTemplates.push(h)}else if(f.nodeName==="Ad"){if(this.vastVersion&&parseFloat(this.vastVersion)<3)s=!0;else if(s===!1&&c.length>1)break;const h=us(f,this.emit.bind(this),{allowMultipleAds:s,followAdditionalWrappers:a});h.ad?(c.push(h.ad),this.emit("VAST-ad-parsed",{type:h.type,url:i,wrapperDepth:o,adIndex:c.length-1,vastVersion:p})):this.trackVastError(this.getErrorURLTemplates(),{ERRORCODE:101})}}return c}parse(e){let{url:n=null,resolveAll:r=!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:n,wrapperDepth:s,allowMultipleAds:c,followAdditionalWrappers:u})}catch(p){return Promise.reject(p)}if(l.length===1&&i!=null&&(l[0].sequence=i),r===!1){const p=A.getSortedAdPods(l),d=A.getStandAloneAds(l);p.length?l=p:d.length&&(l=[d.shift()]),this.remainingAds=d}return this.resolveAds(l,{wrapperDepth:s,previousUrl:o,url:n})}resolveAds(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],{wrapperDepth:n,previousUrl:r,url:i}=arguments.length>1?arguments[1]:void 0;const o=[];return r=i,e.forEach((s=>{const a=this.resolveWrappers(s,n,r);o.push(a)})),Promise.all(o).then((s=>Re.flatten(s)))}resolveWrappers(e,n,r){const i={...e};return new Promise((o=>{var s;if(n++,!i.nextWrapperURL)return delete i.nextWrapperURL,o(i);if(!this.fetcher)return i.VASTAdTagURI=i.nextWrapperURL,delete i.nextWrapperURL,o(i);if(n>=this.maxWrapperDepth)return i.errorCode=302,delete i.nextWrapperURL,o(i);i.nextWrapperURL=A.resolveVastAdTagURI(i.nextWrapperURL,r);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:r,wrapperSequence:u,wrapperDepth:n,followAdditionalWrappers:i.followAdditionalWrappers,allowMultipleAds:a}).then((l=>{if(delete i.nextWrapperURL,l.length===0)return i.creatives=[],o(i);l.forEach((p=>{p&&A.mergeWrapperAdData(p,i)})),o(l)})))).catch((c=>{i.errorCode=c.message===Mr?102:301,i.errorMessage=c.message,o(i)}))}))}completeWrapperResolving(e){if(e.ads.length===0)this.trackVastError(e.errorURLTemplates,{ERRORCODE:303});else for(let n=e.ads.length-1;n>=0;n--){const r=e.ads[n],i=!r.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}));!r.errorCode&&!i||r.VASTAdTagURI||(this.trackVastError(r.errorURLTemplates.concat(e.errorURLTemplates),{ERRORCODE:r.errorCode||303},{ERRORMESSAGE:r.errorMessage||""},{extensions:r.extensions},{system:r.system}),this.keepFailedAdPod&&r.sequence?r.hasFailed=!0:e.ads.splice(n,1))}}}let ve=null;const hs={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 ms{constructor(){this.storage=this.initStorage()}initStorage(){if(ve)return ve;try{ve=typeof window<"u"&&window!==null?window.localStorage||window.sessionStorage:null}catch{ve=null}return ve&&!this.isStorageDisabled(ve)||(ve=hs,ve.clear()),ve}isStorageDisabled(e){const n="__VASTStorage__";try{if(e.setItem(n,n),e.getItem(n)!==n)return e.removeItem(n),!0}catch{return!0}return e.removeItem(n),!1}getItem(e){return this.storage.getItem(e)}setItem(e,n){return this.storage.setItem(e,n)}removeItem(e){return this.storage.removeItem(e)}clear(){return this.storage.clear()}}const ir=12e4,ys={get:async function(t,e){try{const n=new AbortController,r=setTimeout((()=>{throw n.abort(),new Error("URLHandler: Request timed out after ".concat(e.timeout||ir," ms (408)"))}),e.timeout||ir),i=await fetch(t,{...e,signal:n.signal,credentials:e.withCredentials?"include":"omit"}).finally((()=>{clearTimeout(r)})),o=(function(s){return Re.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=Re.isBrowserEnvironment()?new DOMParser:new(await Promise.resolve().then(()=>require("./index-B15M-YGv.cjs")).then(c=>c.index)).DOMParser,{xml:u.parseFromString(a,"text/xml"),details:{byteLength:a.length,statusCode:s.status,rawXml:a}}})(i)}catch(n){return{error:n,statusCode:n.name==="AbortError"?408:null}}}};class gs{constructor(){this.URLTemplateFilters=[]}setOptions(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.urlHandler=e.urlHandler||e.urlhandler||ys,this.fetchingOptions={...e.fetchOptions,timeout:e.timeout||ir,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 n;let{url:r,maxWrapperDepth:i,emitter:o,wrapperDepth:s=0,previousUrl:a=null,wrapperAd:u=null}=e;const c=Date.now();this.URLTemplateFilters.forEach((d=>{r=d(r)})),o("VAST-resolving",{url:r,previousUrl:a,wrapperDepth:s,maxWrapperDepth:i,timeout:this.fetchingOptions.timeout,wrapperAd:u});const l=await this.urlHandler.get(r,this.fetchingOptions),p=Math.round(Date.now()-c);if(o("VAST-resolved",{url:r,previousUrl:a,wrapperDepth:s,error:l?.error||null,duration:p,statusCode:l?.statusCode||null,...l?.details}),oi(l==null||(n=l.details)===null||n===void 0?void 0:n.byteLength,p),l.error)throw new Error(l.error);return l.xml}}class vs{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:new ms;this.cappingFreeLunch=e,this.cappingMinimumTimeInterval=n,this.fetcher=new gs,this.vastParser=new fs({fetcher:this.fetcher}),this.storage=r,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 n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.fetcher.setOptions(n),this.vastParser.parseVAST(e,n)}get(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=Date.now();return n.hasOwnProperty("resolveAll")||(n.resolveAll=!1),this.totalCallsTimeout<r?(this.totalCalls=1,this.totalCallsTimeout=r+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=r-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(n),this.fetcher.setOptions(n),this.vastParser.rootURL=e,this.fetcher.fetchVAST({url:e,emitter:this.vastParser.emit.bind(this.vastParser),maxWrapperDepth:this.vastParser.maxWrapperDepth}).then((a=>(n.previousUrl=e,n.isRootVAST=!0,n.url=e,this.vastParser.parse(a,n).then((u=>{const c=this.vastParser.buildVASTResponse(u);i(c)}))))).catch((a=>o(a)))}))}}const bs=new vs,ft=ue("ui:gam-static"),jr=t=>new Promise((e,n)=>{const r=new Image;r.onload=()=>e(t),r.onerror=()=>n(),r.src=t}),Ts=t=>(e,n,r)=>t.transport.nanoquery.createFetcherStore([e,n],{dedupeTime:r.prefetch?r.refetchInterval:1/0,revalidateInterval:r.refetchInterval>0?r.refetchInterval:0,fetcher:async i=>{if(!i||typeof i!="string")throw new Error("ad url is empty");K.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||"";ft.debug(s,"validAd");const u=s.creatives.find(d=>d.type==="nonlinear");if(u){const d=u.adId||u.id||a;ft.debug(u,"nonlinear");const f=u.variations?.[0]?.staticResource,h=u.variations?.[0]?.nonlinearClickThroughURLTemplate;if(f)return await jr(f),K.emit("exposedPauseAd",{action:"loaded",payload:{id:d,parentId:a}}),{id:d,parentId:a,url:i,imageSrc:f,adUrl:h}}const c=s.creatives.find(d=>d.type==="companion");ft.debug(c,"companion");const l=c?.variations?.[0]?.staticResources?.[0]?.url,p=c?.variations?.[0]?.companionClickThroughURLTemplate;if(l){const d=c.adId||c.id||a;return await jr(l),K.emit("exposedPauseAd",{action:"loaded",payload:{id:d,parentId:a}}),{id:d,parentId:a,url:i,imageSrc:l,adUrl:p}}}throw new Error("no_valid_ad")}catch(o){throw o.message!=="no_valid_ad"&&o.message!=="ad url is empty"&&console.error(o),o}}});class As extends Qn{getExternalPauseAd;externalPauseAdStores=new Map;externalPauseAdEnabled=new Map;log;constructor(e){super(),this.log=ue("advertisement");const n=Ts(e);this.getExternalPauseAd=(r,i)=>{if(this.externalPauseAdStores.has(r)){const a=this.externalPauseAdEnabled.get(r),u=this.externalPauseAdStores.get(r),c=a.get()===!1&&i.$enabled===!0;return a.set(i.$enabled),c&&window.requestAnimationFrame(()=>{u.revalidate()}),[u,r]}const o=Z(i.$enabled),s=n(r,o,i);return this.externalPauseAdEnabled.set(r,o),this.externalPauseAdStores.set(r,s),[s,r]}}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 Ss=(t,e,n)=>{t.sdk.advertisement=new As(t),t.sdk.onMount({name:"advertisement"},()=>(t.sdk.advertisement.connect(),()=>{t.sdk.advertisement.disconnect()})),n()};class ws{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{r.slEventBus?.type==="invitation"&&r.slEventBus.action==="sent"&&this.sent(r.slEventBus.payload)};return K.listen(n)})}accepted=()=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.INVITATION_ACCEPTED},category:$e.InvitationCategory.GAMES,from:$e.InvitationFrom.UNSET})};sent=({from:e})=>{this.analytics.write("invitation",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.INVITATION_SENT},category:$e.InvitationCategory.GAMES,from:e||$e.InvitationFrom.UNSET})}}class Es{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="interactions")switch(r.slEventBus.action){case"tap":this.tap();break;case"scroll":this.scroll();break}};return K.listen(n)})}tap=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.INTERACTIONS},actionType:vr.InteractionActionType.TAP})};scroll=()=>{this.analytics.write("interactions",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.INTERACTIONS},actionType:vr.InteractionActionType.SCROLL})}}const Is={[O.PromotionType.UNSET]:w.TopicSubType.UNSET,[O.PromotionType.INGAME_IAB21]:w.TopicSubType.PROMOTION_INGAME_IAB21,[O.PromotionType.INGAME_IAB21_SIDEBAR]:w.TopicSubType.PROMOTION_INGAME_IAB21,[O.PromotionType.INGAME_IAB11_LBAR]:w.TopicSubType.PROMOTION_INGAME_IAB11_LBAR,[O.PromotionType.INGAME_IAB11]:w.TopicSubType.PROMOTION_INGAME_IAB11,[O.PromotionType.INGAME_IAB11_SIDEBAR]:w.TopicSubType.PROMOTION_INGAME_IAB11,[O.PromotionType.INGAME_IAB21_LBAR]:w.TopicSubType.PROMOTION_INGAME_IAB21_LBAR,[O.PromotionType.INGAME_IAB61]:w.TopicSubType.PROMOTION_INGAME_IAB61,[O.PromotionType.INGAME_IAB61_SIDEBAR]:w.TopicSubType.PROMOTION_INGAME_IAB61,[O.PromotionType.EXTERNAL_AD]:w.TopicSubType.PROMOTION_GAM,[O.PromotionType.VIDEO_SIDE_BY_SIDE]:w.TopicSubType.PROMOTION_VIDEO_SIDE_BY_SIDE,[O.PromotionType.PICTURE_IN_PICTURE]:w.TopicSubType.PROMOTION_PICTURE_IN_PICTURE,[O.PromotionType.LOWER_THIRD]:w.TopicSubType.PROMOTION_LOWER_THIRD,[O.PromotionType.SHOP_LBAR]:w.TopicSubType.PROMOTION_SHOP_LBAR,[O.PromotionType.SHOP_OVERLAY]:w.TopicSubType.PROMOTION_SHOP_OVERLAY,[O.PromotionType.SHOP_SIDEBAR]:w.TopicSubType.PROMOTION_SHOP_SIDEBAR,[O.PromotionType.NFL_SHOP_LBAR]:w.TopicSubType.PROMOTION_SHOP_LBAR,[O.PromotionType.NFL_SHOP_OVERLAY]:w.TopicSubType.PROMOTION_SHOP_OVERLAY,[O.PromotionType.NFL_SHOP_SIDEBAR]:w.TopicSubType.PROMOTION_SHOP_SIDEBAR,[O.PromotionType.STATS]:w.TopicSubType.UNSET,[O.PromotionType.STANDARD]:w.TopicSubType.UNSET,[O.PromotionType.SHOP]:w.TopicSubType.UNSET,[O.PromotionType.NFL_SHOP]:w.TopicSubType.UNSET},or=t=>t?Is[t]:w.TopicSubType.UNSET,Os={25:w.Kind.AD_VIDEO_Q25,50:w.Kind.AD_VIDEO_Q50,75:w.Kind.AD_VIDEO_Q75};class ks{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(!r.slEventBus?.skipAnalytics){if(r.slEventBus?.type==="exposedPauseAd"){const i=r.slEventBus.payload;switch(r.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(r.slEventBus?.type==="advertisement"){const i=r.slEventBus.payload,o=or(i.type);switch(r.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:r.slEventBus.action==="videoMuted"});break;case"videoReplayed":this.videoReplayed(i,{topicSubType:o});break;case"quartileCompleted":this.quartileCompleted(i,{topicSubType:o});break}}}};return K.listen(n)})}exposedPauseAdEnabled=({id:e,parentId:n})=>{const r=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...r,kind:w.Kind.STREAM_PAUSED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};exposedPauseAdClosed=({id:e,parentId:n})=>{const r=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...r,kind:w.Kind.EXTERNAL_AD_CLOSED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};exposedPauseAdDisabled=({id:e,parentId:n})=>{const r=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...r,kind:w.Kind.STREAM_RESUMED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};exposedPauseAdOpened=({id:e,parentId:n})=>{const r=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...r,kind:w.Kind.EXTERNAL_AD_RENDERED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};exposedPauseAdNavigated=({id:e,parentId:n})=>{const r=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...r,kind:w.Kind.AD_INTERACTION_BANNER_NAVIGATED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};exposedPauseAdLoad=({id:e,parentId:n},r)=>{const i=this.analytics.commonStore.getValues();this.analytics.write("games",{common:{...i,kind:r?w.Kind.EXTERNAL_AD_LOADED:w.Kind.EXTERNAL_AD_REQUESTED,topicId:e,parentTopicId:n,topicType:w.TopicType.EXPOSED_PAUSED_AD},pollOpenedFrom:w.PollOpenedFrom.UNSET})};received=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.POLLS_RECEIVED,topicId:e,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};opened=({id:e,openedFrom:n},{topicSubType:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.POLLS_AD_OPENED,topicId:e,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:n==="notification"?w.PollOpenedFrom.IN_APP:w.PollOpenedFrom.UNSET})};viewed=({id:e},{topicSubType:n})=>{};videoMuted=({id:e},{topicSubType:n,muted:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:r?w.Kind.AD_VIDEO_MUTED:w.Kind.AD_VIDEO_UNMUTED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};quartileCompleted=({id:e,quartile:n},{topicSubType:r})=>{n&&this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:Os[n],topicType:w.TopicType.POLLS_PROMOTION,topicSubType:r},pollOpenedFrom:w.PollOpenedFrom.UNSET})};videoReplayed=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_VIDEO_REPLAYED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};videoPlay=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_VIDEO_PLAYED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};videoEnd=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_VIDEO_COMPLETE,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};videoRendered=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_VIDEO_RENDERED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};buttonSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_INTERACTION_BUTTON_NAVIGATED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};bannerSelect=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_INTERACTION_BANNER_NAVIGATED,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})};bannerShown=({id:e},{topicSubType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),topicId:e,kind:w.Kind.AD_BANNER_SHOWN,topicType:w.TopicType.POLLS_PROMOTION,topicSubType:n},pollOpenedFrom:w.PollOpenedFrom.UNSET})}}const je={[O.QuestionType.UNSET]:w.TopicType.UNSET,[O.QuestionType.FACTOID]:w.TopicType.POLLS_INSIGHT,[O.QuestionType.POLL]:w.TopicType.POLLS_POLL,[O.QuestionType.PREDICTION]:w.TopicType.POLLS_PREDICTION,[O.QuestionType.PROMOTION]:w.TopicType.POLLS_PROMOTION,[O.QuestionType.TRIVIA]:w.TopicType.POLLS_TRIVIA,[O.QuestionType.TWEET]:w.TopicType.POLLS_TWITTER};O.QuestionType.UNSET+"",pe.NotificationKind.UNSET,O.QuestionType.FACTOID+"",pe.NotificationKind.POLLS,O.QuestionType.POLL+"",pe.NotificationKind.POLLS,O.QuestionType.PREDICTION+"",pe.NotificationKind.POLLS,O.QuestionType.PROMOTION+"",pe.NotificationKind.POLLS,O.QuestionType.TRIVIA+"",pe.NotificationKind.POLLS,O.QuestionType.TWEET+"",pe.NotificationKind.POLLS;const Ns={[Y.SdkOverlayType.UNSET]:w.Category.UNSET,[Y.SdkOverlayType.INPLAY]:w.Category.INPLAY,[Y.SdkOverlayType.MESSAGING]:w.Category.MESSAGING,[Y.SdkOverlayType.STATISTICS]:w.Category.STATS,[Y.SdkOverlayType.BETTING]:w.Category.BETTING,[Y.SdkOverlayType.TWITTER]:w.Category.TWITTER,[Y.SdkOverlayType.MERCHANDISE]:w.Category.MERCHANDISE,[Y.SdkOverlayType.CONTESTS]:w.Category.CONTESTS,[Y.SdkOverlayType.VOICE_CHAT]:w.Category.CALLING,[Y.SdkOverlayType.TICKETS]:w.Category.TICKETS,[Y.SdkOverlayType.WHOIS_WATCHING]:w.Category.WHOISWATCHING,[Y.SdkOverlayType.PROFILE]:w.Category.PROFILE,[Y.SdkOverlayType.GAMES]:w.Category.POLLS,[Y.SdkOverlayType.GOLF_STATISTICS]:w.Category.STATS,[Y.SdkOverlayType.HIGHLIGHTS]:w.Category.HIGHLIGHTS,[Y.SdkOverlayType.PUBLIC_CHAT]:w.Category.PUBLIC_CHAT};class Cs{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="notification")switch(r.slEventBus.action){case"rendered":this.received(r.slEventBus.payload);break;case"opened":this.opened(r.slEventBus.payload);break}if(r.slEventBus?.type==="advertisement")switch(r.slEventBus.action){case"notification-received":this.received({questionId:r.slEventBus.payload.id,questionType:O.QuestionType.PROMOTION,topicSubType:or(r.slEventBus.payload.type)});break;case"notification-opened":this.opened({questionId:r.slEventBus.payload.id,questionType:O.QuestionType.PROMOTION,topicSubType:or(r.slEventBus.payload.type)});break}};return K.listen(n)})}received=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.NOTIFICATION_RECEIVED,topicId:e,topicType:n?je[n]:w.TopicType.UNSET,topicSubType:r},notificationKind:pe.NotificationKind.POLLS,notificationType:pe.NotificationType.IN_APP})};opened=({questionId:e,questionType:n,topicSubType:r})=>{this.analytics.write("notification",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.NOTIFICATION_OPENED,topicId:e,topicType:n?je[n]:w.TopicType.UNSET,topicSubType:r},notificationKind:pe.NotificationKind.POLLS,notificationType:pe.NotificationType.IN_APP})}}class Rs{analytics;constructor(e){this.analytics=e,this.analytics.onConnect(()=>{const n=r=>{if(r.slEventBus?.type==="poll")switch(r.slEventBus.action){case"voted":this.voted(r.slEventBus.payload);break;case"navigated":this.navigated();break;case"onboardingPassed":this.onboardingPassed();break;case"received":this.received(r.slEventBus.payload);break;case"viewed":this.viewed(r.slEventBus.payload);break}};return K.listen(n)})}received=({questionId:e,questionType:n})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.POLLS_RECEIVED,topicId:e,topicType:n?je[n]:w.TopicType.UNSET},pollOpenedFrom:w.PollOpenedFrom.UNSET})};viewed=({questionId:e,questionType:n,questionOpenedFrom:r,isAd:i})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:i?w.Kind.POLLS_AD_OPENED:w.Kind.POLLS_OPENED,topicId:e,topicType:n?je[n]:w.TopicType.UNSET},pollOpenedFrom:r==="list"?w.PollOpenedFrom.PICK_HISTORY:w.PollOpenedFrom.IN_APP})};voted=({questionId:e,questionType:n,isAd:r})=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:r?w.Kind.POLLS_AD_VOTE:w.Kind.POLLS_VOTE,topicId:e,topicType:n?je[n]:w.TopicType.UNSET},pollOpenedFrom:w.PollOpenedFrom.UNSET})};onboardingPassed=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.GAMES_JOINED},pollOpenedFrom:w.PollOpenedFrom.UNSET})};navigated=()=>{this.analytics.write("games",{common:{...this.analytics.commonStore.getValues(),kind:w.Kind.POLLS_NAVIGATED},pollOpenedFrom:w.PollOpenedFrom.UNSET})}}const Ps=({transport:t,$commonStore:e})=>{let n;const r=Z(!1),i=3e4,{client:o,queryKey:s}=t.createPromiseClient(xn.AnalyticsService,{method:"send",params:[r]}),a=t.nanoquery.createFetcherStore(s,{fetcher:async()=>{const d=e.getStore().get();try{await o.unary({message:{case:"heartbeat",value:{common:{...d,kind:w.Kind.SESSION_HEARTBEAT}}}})}catch(f){Se.error(f,"send heartbeat failed")}return Date.now()},revalidateInterval:i}),u=()=>{Se.debug("mounted heartbeat"),n=a.subscribe(()=>{})},c=()=>{Se.debug("enabled heartbeat"),r.set(!0),a.lc===0&&u()},l=()=>{Se.debug("disabled heartbeat"),r.set(!1)};return{enable:c,disable:l,mount:u,unmount:()=>{Se.debug("unmounted heartbeat"),a.off(),n?.(),n=void 0,l()}}},Se=ue("analytics");class Ls{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 Ce(se({}),"common-analytics"),this.connectToSDK(e),this.heartbeat=Ps({transport:e.analyticsTransport,$commonStore:this.commonStore}),this.notifications=new Cs(this),this.polls=new Rs(this),this.invitation=new ws(this),this.interactions=new Es(this),this.advertisement=new ks(this);const{client:n}=e.analyticsTransport.createPromiseClient(xn.AnalyticsService,{method:"send"});this.analyticsClient=n}connect=()=>{this.writeCommon("sessionId",De.v4()),this.heartbeat.enable(),this.listeners.forEach(e=>this.listenersCancels.add(e())),this.connected=!0,Se.debug("analytics connected")};disconnect=()=>{this.writeCommon("sessionId",""),this.writeCommon("overlaySessionId",""),this.heartbeat.unmount(),this.listenersCancels.forEach(e=>e()),this.connected=!1,Se.debug("analytics disconnected")};write=(e,n)=>{n&&this.analyticsClient.unary({message:{case:e,value:n}}).then(()=>{Se.trace({key:e,value:n},"send analytics success")}).catch(r=>{Se.error(r,"send analytics failed")})};writeCommonValues=(e,n,r)=>{const i=this.commonStore.getValue(n);setTimeout(()=>{if(this.connected&&i===this.commonStore.getValue(n))for(const[o,s]of Object.entries(e))this.commonStore.setValue(o,s)},r)};writeCommon=(e,n,r)=>{r?this.writeCommonValues({[e]:n},e,r):this.commonStore.setValue(e,n)};onConnect=e=>{this.listeners.add(e),this.connected&&this.listenersCancels.add(e())};connectToSDK=e=>{this.onConnect(()=>e.stores.slStreamId.getAtomStore().subscribe(n=>{this.writeCommon("eventId",n)})),this.onConnect(()=>e.sdk.getActiveFeature().subscribe(n=>{n&&this.writeCommon("category",Ns[n]),n!==Y.SdkOverlayType.UNSET?this.writeCommon("overlaySessionId",De.v4()):this.writeCommon("overlaySessionId","",200)})),this.onConnect(()=>{const n=r=>{if(!r.slEventBus)return;const i=r.slEventBus?.action;r.slEventBus?.type==="exposedPauseAd"&&((i==="disabled"||i==="closed")&&this.writeCommonValues({overlaySessionId:"",topicId:"",parentTopicId:"",topicType:w.TopicType.UNSET,category:w.Category.UNSET},"overlaySessionId",200),i==="enabled"&&(this.writeCommon("overlaySessionId",De.v4()),this.writeCommon("category",w.Category.EXPOSED_PAUSED_AD))),r.slEventBus?.type==="advertisement"&&(i==="opened"&&this.writeCommon("overlaySessionId",De.v4()),i==="closed"&&this.writeCommon("overlaySessionId","",200))};return K.listen(n)}),this.onConnect(()=>e.sdk.uiState.subscribe(r=>{Object.values(r).every(o=>o===!1)&&this.writeCommon("overlaySessionId","",200)})),this.onConnect(()=>{const n=window.matchMedia("(orientation: portrait)"),r=i=>{this.writeCommon("screenOrientation",i.matches?w.ScreenOrientation.PORTRAIT:w.ScreenOrientation.LANDSCAPE)};return n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}}),e.deepLink&&this.onConnect(()=>e.deepLink.$store.subscribe(n=>{n?.handled&&this.invitation.accepted()}))}}const _s=(t,e,n)=>{t.analytics=new Ls(t),t.sdk.onMount({name:"analytics"},()=>(t.analytics.connect(),t.sdk.writeOverlaySessionId=r=>{r===""?t.analytics.writeCommon("overlaySessionId","",200):t.analytics.writeCommon("overlaySessionId",De.v4())},()=>{t.analytics.disconnect()})),n()};var ur=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function si(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Je={exports:{}},Ze={exports:{}},ht,Qr;function Ds(){if(Qr)return ht;Qr=1;function t(e){var n=new e,r=n;function i(){var s=n;return s.next?n=s.next:(n=new e,r=n),s.next=null,s}function o(s){r.next=s,r=s}return{get:i,release:o}}return ht=t,ht}var Gr;function ai(){if(Gr)return Ze.exports;Gr=1;var t=Ds();function e(o,s,a){if(typeof o=="function"&&(a=s,s=o,o=null),!(a>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");var u=t(r),c=null,l=null,p=0,d=null,f={push:v,drain:n,saturated:n,pause:m,paused:!1,get concurrency(){return a},set concurrency(N){if(!(N>=1))throw new Error("fastqueue concurrency must be equal to or greater than 1");if(a=N,!f.paused)for(;c&&p<a;)p++,_()},running:h,resume:g,idle:S,length:T,getQueue:E,unshift:I,empty:n,kill:F,killAndDrain:y,error:R};return f;function h(){return p}function m(){f.paused=!0}function T(){for(var N=c,D=0;N;)N=N.next,D++;return D}function E(){for(var N=c,D=[];N;)D.push(N.value),N=N.next;return D}function g(){if(f.paused){if(f.paused=!1,c===null){p++,_();return}for(;c&&p<a;)p++,_()}}function S(){return p===0&&f.length()===0}function v(N,D){var L=u.get();L.context=o,L.release=_,L.value=N,L.callback=D||n,L.errorHandler=d,p>=a||f.paused?l?(l.next=L,l=L):(c=L,l=L,f.saturated()):(p++,s.call(o,L.value,L.worked))}function I(N,D){var L=u.get();L.context=o,L.release=_,L.value=N,L.callback=D||n,L.errorHandler=d,p>=a||f.paused?c?(L.next=c,c=L):(c=L,l=L,f.saturated()):(p++,s.call(o,L.value,L.worked))}function _(N){N&&u.release(N);var D=c;D&&p<=a?f.paused?p--:(l===c&&(l=null),c=D.next,D.next=null,s.call(o,D.value,D.worked),l===null&&f.empty()):--p===0&&f.drain()}function F(){c=null,l=null,f.drain=n}function y(){c=null,l=null,f.drain(),f.drain=n}function R(N){d=N}}function n(){}function r(){this.value=null,this.callback=n,this.next=null,this.release=n,this.context=null,this.errorHandler=null;var o=this;this.worked=function(a,u){var c=o.callback,l=o.errorHandler,p=o.value;o.value=null,o.callback=n,o.errorHandler&&l(a,p),c.call(o.context,a,u),o.release(o)}}function i(o,s,a){typeof o=="function"&&(a=s,s=o,o=null);function u(m,T){s.call(this,m).then(function(E){T(null,E)},T)}var c=e(o,u,a),l=c.push,p=c.unshift;return c.push=d,c.unshift=f,c.drained=h,c;function d(m){var T=new Promise(function(E,g){l(m,function(S,v){if(S){g(S);return}E(v)})});return T.catch(n),T}function f(m){var T=new Promise(function(E,g){p(m,function(S,v){if(S){g(S);return}E(v)})});return T.catch(n),T}function h(){if(c.idle())return new Promise(function(E){E()});var m=c.drain,T=new Promise(function(E){c.drain=function(){m(),E()}});return T}}return Ze.exports=e,Ze.exports.promise=i,Ze.exports}var et={exports:{}},Wr;function ui(){if(Wr)return et.exports;Wr=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(I,_,F){return Function.prototype.apply.call(I,_,F)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(I){return Object.getOwnPropertyNames(I).concat(Object.getOwnPropertySymbols(I))}:n=function(I){return Object.getOwnPropertyNames(I)};function r(v){console&&console.warn&&console.warn(v)}var i=Number.isNaN||function(I){return I!==I};function o(){o.init.call(this)}et.exports=o,et.exports.once=E,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function a(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(v){if(typeof v!="number"||v<0||i(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");s=v}}),o.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},o.prototype.setMaxListeners=function(I){if(typeof I!="number"||I<0||i(I))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+I+".");return this._maxListeners=I,this};function u(v){return v._maxListeners===void 0?o.defaultMaxListeners:v._maxListeners}o.prototype.getMaxListeners=function(){return u(this)},o.prototype.emit=function(I){for(var _=[],F=1;F<arguments.length;F++)_.push(arguments[F]);var y=I==="error",R=this._events;if(R!==void 0)y=y&&R.error===void 0;else if(!y)return!1;if(y){var N;if(_.length>0&&(N=_[0]),N instanceof Error)throw N;var D=new Error("Unhandled error."+(N?" ("+N.message+")":""));throw D.context=N,D}var L=R[I];if(L===void 0)return!1;if(typeof L=="function")e(L,this,_);else for(var U=L.length,$=h(L,U),F=0;F<U;++F)e($[F],this,_);return!0};function c(v,I,_,F){var y,R,N;if(a(_),R=v._events,R===void 0?(R=v._events=Object.create(null),v._eventsCount=0):(R.newListener!==void 0&&(v.emit("newListener",I,_.listener?_.listener:_),R=v._events),N=R[I]),N===void 0)N=R[I]=_,++v._eventsCount;else if(typeof N=="function"?N=R[I]=F?[_,N]:[N,_]:F?N.unshift(_):N.push(_),y=u(v),y>0&&N.length>y&&!N.warned){N.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+N.length+" "+String(I)+" listeners added. Use emitter.setMaxListeners() to increase limit");D.name="MaxListenersExceededWarning",D.emitter=v,D.type=I,D.count=N.length,r(D)}return v}o.prototype.addListener=function(I,_){return c(this,I,_,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(I,_){return c(this,I,_,!0)};function l(){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 p(v,I,_){var F={fired:!1,wrapFn:void 0,target:v,type:I,listener:_},y=l.bind(F);return y.listener=_,F.wrapFn=y,y}o.prototype.once=function(I,_){return a(_),this.on(I,p(this,I,_)),this},o.prototype.prependOnceListener=function(I,_){return a(_),this.prependListener(I,p(this,I,_)),this},o.prototype.removeListener=function(I,_){var F,y,R,N,D;if(a(_),y=this._events,y===void 0)return this;if(F=y[I],F===void 0)return this;if(F===_||F.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete y[I],y.removeListener&&this.emit("removeListener",I,F.listener||_));else if(typeof F!="function"){for(R=-1,N=F.length-1;N>=0;N--)if(F[N]===_||F[N].listener===_){D=F[N].listener,R=N;break}if(R<0)return this;R===0?F.shift():m(F,R),F.length===1&&(y[I]=F[0]),y.removeListener!==void 0&&this.emit("removeListener",I,D||_)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(I){var _,F,y;if(F=this._events,F===void 0)return this;if(F.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):F[I]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete F[I]),this;if(arguments.length===0){var R=Object.keys(F),N;for(y=0;y<R.length;++y)N=R[y],N!=="removeListener"&&this.removeAllListeners(N);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=F[I],typeof _=="function")this.removeListener(I,_);else if(_!==void 0)for(y=_.length-1;y>=0;y--)this.removeListener(I,_[y]);return this};function d(v,I,_){var F=v._events;if(F===void 0)return[];var y=F[I];return y===void 0?[]:typeof y=="function"?_?[y.listener||y]:[y]:_?T(y):h(y,y.length)}o.prototype.listeners=function(I){return d(this,I,!0)},o.prototype.rawListeners=function(I){return d(this,I,!1)},o.listenerCount=function(v,I){return typeof v.listenerCount=="function"?v.listenerCount(I):f.call(v,I)},o.prototype.listenerCount=f;function f(v){var I=this._events;if(I!==void 0){var _=I[v];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function h(v,I){for(var _=new Array(I),F=0;F<I;++F)_[F]=v[F];return _}function m(v,I){for(;I+1<v.length;I++)v[I]=v[I+1];v.pop()}function T(v){for(var I=new Array(v.length),_=0;_<I.length;++_)I[_]=v[_].listener||v[_];return I}function E(v,I){return new Promise(function(_,F){function y(N){v.removeListener(I,R),F(N)}function R(){typeof v.removeListener=="function"&&v.removeListener("error",y),_([].slice.call(arguments))}S(v,I,R,{once:!0}),I!=="error"&&g(v,y,{once:!0})})}function g(v,I,_){typeof v.on=="function"&&S(v,"error",I,_)}function S(v,I,_,F){if(typeof v.on=="function")F.once?v.once(I,_):v.on(I,_);else if(typeof v.addEventListener=="function")v.addEventListener(I,function y(R){F.once&&v.removeEventListener(I,y),_(R)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return et.exports}var mt={},yt={},gt,Kr;function ci(){return Kr||(Kr=1,gt=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},n=Symbol("test"),r=Object(n);if(typeof n=="string"||Object.prototype.toString.call(n)!=="[object Symbol]"||Object.prototype.toString.call(r)!=="[object Symbol]")return!1;var i=42;e[n]=i;for(n in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var o=Object.getOwnPropertySymbols(e);if(o.length!==1||o[0]!==n||!Object.prototype.propertyIsEnumerable.call(e,n))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,n);if(s.value!==i||s.enumerable!==!0)return!1}return!0}),gt}var vt,Hr;function lt(){if(Hr)return vt;Hr=1;var t=ci();return vt=function(){return t()&&!!Symbol.toStringTag},vt}var bt,$r;function Fs(){return $r||($r=1,bt=Error),bt}var Tt,zr;function Us(){return zr||(zr=1,Tt=EvalError),Tt}var At,Yr;function Vs(){return Yr||(Yr=1,At=RangeError),At}var St,Xr;function xs(){return Xr||(Xr=1,St=ReferenceError),St}var wt,Jr;function li(){return Jr||(Jr=1,wt=SyntaxError),wt}var Et,Zr;function dt(){return Zr||(Zr=1,Et=TypeError),Et}var It,en;function Bs(){return en||(en=1,It=URIError),It}var Ot,tn;function qs(){if(tn)return Ot;tn=1;var t=typeof Symbol<"u"&&Symbol,e=ci();return Ot=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},Ot}var kt,rn;function Ms(){if(rn)return kt;rn=1;var t={__proto__:null,foo:{}},e=Object;return kt=function(){return{__proto__:t}.foo===t.foo&&!(t instanceof e)},kt}var Nt,nn;function js(){if(nn)return Nt;nn=1;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,n=Math.max,r="[object Function]",i=function(u,c){for(var l=[],p=0;p<u.length;p+=1)l[p]=u[p];for(var d=0;d<c.length;d+=1)l[d+u.length]=c[d];return l},o=function(u,c){for(var l=[],p=c,d=0;p<u.length;p+=1,d+=1)l[d]=u[p];return l},s=function(a,u){for(var c="",l=0;l<a.length;l+=1)c+=a[l],l+1<a.length&&(c+=u);return c};return Nt=function(u){var c=this;if(typeof c!="function"||e.apply(c)!==r)throw new TypeError(t+c);for(var l=o(arguments,1),p,d=function(){if(this instanceof p){var E=c.apply(this,i(l,arguments));return Object(E)===E?E:this}return c.apply(u,i(l,arguments))},f=n(0,c.length-l.length),h=[],m=0;m<f;m++)h[m]="$"+m;if(p=Function("binder","return function ("+s(h,",")+"){ return binder.apply(this,arguments); }")(d),c.prototype){var T=function(){};T.prototype=c.prototype,p.prototype=new T,T.prototype=null}return p},Nt}var Ct,on;function cr(){if(on)return Ct;on=1;var t=js();return Ct=Function.prototype.bind||t,Ct}var Rt,sn;function Qs(){if(sn)return Rt;sn=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,n=cr();return Rt=n.call(t,e),Rt}var Pt,an;function We(){if(an)return Pt;an=1;var t,e=Fs(),n=Us(),r=Vs(),i=xs(),o=li(),s=dt(),a=Bs(),u=Function,c=function(q){try{return u('"use strict"; return ('+q+").constructor;")()}catch{}},l=Object.getOwnPropertyDescriptor;if(l)try{l({},"")}catch{l=null}var p=function(){throw new s},d=l?(function(){try{return arguments.callee,p}catch{try{return l(arguments,"callee").get}catch{return p}}})():p,f=qs()(),h=Ms()(),m=Object.getPrototypeOf||(h?function(q){return q.__proto__}:null),T={},E=typeof Uint8Array>"u"||!m?t:m(Uint8Array),g={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":f&&m?m([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":T,"%AsyncGenerator%":T,"%AsyncGeneratorFunction%":T,"%AsyncIteratorPrototype%":T,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":n,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":u,"%GeneratorFunction%":T,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":f&&m?m(m([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!f||!m?t:m(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":r,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!f||!m?t:m(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":f&&m?m(""[Symbol.iterator]()):t,"%Symbol%":f?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":d,"%TypedArray%":E,"%TypeError%":s,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet};if(m)try{null.error}catch(q){var S=m(m(q));g["%Error.prototype%"]=S}var v=function q(G){var H;if(G==="%AsyncFunction%")H=c("async function () {}");else if(G==="%GeneratorFunction%")H=c("function* () {}");else if(G==="%AsyncGeneratorFunction%")H=c("async function* () {}");else if(G==="%AsyncGenerator%"){var z=q("%AsyncGeneratorFunction%");z&&(H=z.prototype)}else if(G==="%AsyncIteratorPrototype%"){var te=q("%AsyncGenerator%");te&&m&&(H=m(te.prototype))}return g[G]=H,H},I={__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"]},_=cr(),F=Qs(),y=_.call(Function.call,Array.prototype.concat),R=_.call(Function.apply,Array.prototype.splice),N=_.call(Function.call,String.prototype.replace),D=_.call(Function.call,String.prototype.slice),L=_.call(Function.call,RegExp.prototype.exec),U=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,$=/\\(\\)?/g,X=function(G){var H=D(G,0,1),z=D(G,-1);if(H==="%"&&z!=="%")throw new o("invalid intrinsic syntax, expected closing `%`");if(z==="%"&&H!=="%")throw new o("invalid intrinsic syntax, expected opening `%`");var te=[];return N(G,U,function(b,k,P,V){te[te.length]=P?N(V,$,"$1"):k||b}),te},oe=function(G,H){var z=G,te;if(F(I,z)&&(te=I[z],z="%"+te[0]+"%"),F(g,z)){var b=g[z];if(b===T&&(b=v(z)),typeof b>"u"&&!H)throw new s("intrinsic "+G+" exists, but is not available. Please file an issue!");return{alias:te,name:z,value:b}}throw new o("intrinsic "+G+" does not exist!")};return Pt=function(G,H){if(typeof G!="string"||G.length===0)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof H!="boolean")throw new s('"allowMissing" argument must be a boolean');if(L(/^%?[^%]*%?$/,G)===null)throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var z=X(G),te=z.length>0?z[0]:"",b=oe("%"+te+"%",H),k=b.name,P=b.value,V=!1,j=b.alias;j&&(te=j[0],R(z,y([0,1],j)));for(var Q=1,B=!0;Q<z.length;Q+=1){var x=z[Q],W=D(x,0,1),re=D(x,-1);if((W==='"'||W==="'"||W==="`"||re==='"'||re==="'"||re==="`")&&W!==re)throw new o("property names with quotes must have matching quotes");if((x==="constructor"||!B)&&(V=!0),te+="."+x,k="%"+te+"%",F(g,k))P=g[k];else if(P!=null){if(!(x in P)){if(!H)throw new s("base intrinsic for "+G+" exists, but the property is not available.");return}if(l&&Q+1>=z.length){var ce=l(P,x);B=!!ce,B&&"get"in ce&&!("originalValue"in ce.get)?P=ce.get:P=P[x]}else B=F(P,x),P=P[x];B&&!V&&(g[k]=P)}}return P},Pt}var Lt={exports:{}},_t,un;function lr(){if(un)return _t;un=1;var t=We(),e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return _t=e,_t}var Dt,cn;function pt(){if(cn)return Dt;cn=1;var t=We(),e=t("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return Dt=e,Dt}var Ft,ln;function Gs(){if(ln)return Ft;ln=1;var t=lr(),e=li(),n=dt(),r=pt();return Ft=function(o,s,a){if(!o||typeof o!="object"&&typeof o!="function")throw new n("`obj` must be an object or a function`");if(typeof s!="string"&&typeof s!="symbol")throw new n("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new n("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new n("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new n("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new n("`loose`, if provided, must be a boolean");var u=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,p=arguments.length>6?arguments[6]:!1,d=!!r&&r(o,s);if(t)t(o,s,{configurable:l===null&&d?d.configurable:!l,enumerable:u===null&&d?d.enumerable:!u,value:a,writable:c===null&&d?d.writable:!c});else if(p||!u&&!c&&!l)o[s]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},Ft}var Ut,dn;function Ws(){if(dn)return Ut;dn=1;var t=lr(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},Ut=e,Ut}var Vt,pn;function Ks(){if(pn)return Vt;pn=1;var t=We(),e=Gs(),n=Ws()(),r=pt(),i=dt(),o=t("%Math.floor%");return Vt=function(a,u){if(typeof a!="function")throw new i("`fn` is not a function");if(typeof u!="number"||u<0||u>4294967295||o(u)!==u)throw new i("`length` must be a positive 32-bit integer");var c=arguments.length>2&&!!arguments[2],l=!0,p=!0;if("length"in a&&r){var d=r(a,"length");d&&!d.configurable&&(l=!1),d&&!d.writable&&(p=!1)}return(l||p||!c)&&(n?e(a,"length",u,!0,!0):e(a,"length",u)),a},Vt}var fn;function dr(){return fn||(fn=1,(function(t){var e=cr(),n=We(),r=Ks(),i=dt(),o=n("%Function.prototype.apply%"),s=n("%Function.prototype.call%"),a=n("%Reflect.apply%",!0)||e.call(s,o),u=lr(),c=n("%Math.max%");t.exports=function(d){if(typeof d!="function")throw new i("a function is required");var f=a(e,s,arguments);return r(f,1+c(0,d.length-(arguments.length-1)),!0)};var l=function(){return a(e,o,arguments)};u?u(t.exports,"apply",{value:l}):t.exports.apply=l})(Lt)),Lt.exports}var xt,hn;function pr(){if(hn)return xt;hn=1;var t=We(),e=dr(),n=e(t("String.prototype.indexOf"));return xt=function(i,o){var s=t(i,!!o);return typeof s=="function"&&n(i,".prototype.")>-1?e(s):s},xt}var Bt,mn;function Hs(){if(mn)return Bt;mn=1;var t=lt()(),e=pr(),n=e("Object.prototype.toString"),r=function(a){return t&&a&&typeof a=="object"&&Symbol.toStringTag in a?!1:n(a)==="[object Arguments]"},i=function(a){return r(a)?!0:a!==null&&typeof a=="object"&&typeof a.length=="number"&&a.length>=0&&n(a)!=="[object Array]"&&n(a.callee)==="[object Function]"},o=(function(){return r(arguments)})();return r.isLegacyArguments=i,Bt=o?r:i,Bt}var qt,yn;function $s(){if(yn)return qt;yn=1;var t=Object.prototype.toString,e=Function.prototype.toString,n=/^\s*(?:function)?\*/,r=lt()(),i=Object.getPrototypeOf,o=function(){if(!r)return!1;try{return Function("return function*() {}")()}catch{}},s;return qt=function(u){if(typeof u!="function")return!1;if(n.test(e.call(u)))return!0;if(!r){var c=t.call(u);return c==="[object GeneratorFunction]"}if(!i)return!1;if(typeof s>"u"){var l=o();s=l?i(l):!1}return i(u)===s},qt}var Mt,gn;function zs(){if(gn)return Mt;gn=1;var t=Function.prototype.toString,e=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,n,r;if(typeof e=="function"&&typeof Object.defineProperty=="function")try{n=Object.defineProperty({},"length",{get:function(){throw r}}),r={},e(function(){throw 42},null,n)}catch(g){g!==r&&(e=null)}else e=null;var i=/^\s*class\b/,o=function(S){try{var v=t.call(S);return i.test(v)}catch{return!1}},s=function(S){try{return o(S)?!1:(t.call(S),!0)}catch{return!1}},a=Object.prototype.toString,u="[object Object]",c="[object Function]",l="[object GeneratorFunction]",p="[object HTMLAllCollection]",d="[object HTML document.all class]",f="[object HTMLCollection]",h=typeof Symbol=="function"&&!!Symbol.toStringTag,m=!(0 in[,]),T=function(){return!1};if(typeof document=="object"){var E=document.all;a.call(E)===a.call(document.all)&&(T=function(S){if((m||!S)&&(typeof S>"u"||typeof S=="object"))try{var v=a.call(S);return(v===p||v===d||v===f||v===u)&&S("")==null}catch{}return!1})}return Mt=e?function(S){if(T(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;try{e(S,null,n)}catch(v){if(v!==r)return!1}return!o(S)&&s(S)}:function(S){if(T(S))return!0;if(!S||typeof S!="function"&&typeof S!="object")return!1;if(h)return s(S);if(o(S))return!1;var v=a.call(S);return v!==c&&v!==l&&!/^\[object HTML/.test(v)?!1:s(S)},Mt}var jt,vn;function di(){if(vn)return jt;vn=1;var t=zs(),e=Object.prototype.toString,n=Object.prototype.hasOwnProperty,r=function(u,c,l){for(var p=0,d=u.length;p<d;p++)n.call(u,p)&&(l==null?c(u[p],p,u):c.call(l,u[p],p,u))},i=function(u,c,l){for(var p=0,d=u.length;p<d;p++)l==null?c(u.charAt(p),p,u):c.call(l,u.charAt(p),p,u)},o=function(u,c,l){for(var p in u)n.call(u,p)&&(l==null?c(u[p],p,u):c.call(l,u[p],p,u))},s=function(u,c,l){if(!t(c))throw new TypeError("iterator must be a function");var p;arguments.length>=3&&(p=l),e.call(u)==="[object Array]"?r(u,c,p):typeof u=="string"?i(u,c,p):o(u,c,p)};return jt=s,jt}var Qt,bn;function Ys(){return bn||(bn=1,Qt=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]),Qt}var Gt,Tn;function pi(){if(Tn)return Gt;Tn=1;var t=Ys(),e=typeof globalThis>"u"?ur:globalThis;return Gt=function(){for(var r=[],i=0;i<t.length;i++)typeof e[t[i]]=="function"&&(r[r.length]=t[i]);return r},Gt}var Wt,An;function Xs(){if(An)return Wt;An=1;var t=di(),e=pi(),n=dr(),r=pr(),i=pt(),o=r("Object.prototype.toString"),s=lt()(),a=typeof globalThis>"u"?ur:globalThis,u=e(),c=r("String.prototype.slice"),l=Object.getPrototypeOf,p=r("Array.prototype.indexOf",!0)||function(T,E){for(var g=0;g<T.length;g+=1)if(T[g]===E)return g;return-1},d={__proto__:null};s&&i&&l?t(u,function(m){var T=new a[m];if(Symbol.toStringTag in T){var E=l(T),g=i(E,Symbol.toStringTag);if(!g){var S=l(E);g=i(S,Symbol.toStringTag)}d["$"+m]=n(g.get)}}):t(u,function(m){var T=new a[m],E=T.slice||T.set;E&&(d["$"+m]=n(E))});var f=function(T){var E=!1;return t(d,function(g,S){if(!E)try{"$"+g(T)===S&&(E=c(S,1))}catch{}}),E},h=function(T){var E=!1;return t(d,function(g,S){if(!E)try{g(T),E=c(S,1)}catch{}}),E};return Wt=function(T){if(!T||typeof T!="object")return!1;if(!s){var E=c(o(T),8,-1);return p(u,E)>-1?E:E!=="Object"?!1:h(T)}return i?f(T):null},Wt}var Kt,Sn;function Js(){if(Sn)return Kt;Sn=1;var t=di(),e=pi(),n=dr(),r=pr(),i=pt(),o=r("Object.prototype.toString"),s=lt()(),a=typeof globalThis>"u"?ur:globalThis,u=e(),c=r("String.prototype.slice"),l=Object.getPrototypeOf,p=r("Array.prototype.indexOf",!0)||function(T,E){for(var g=0;g<T.length;g+=1)if(T[g]===E)return g;return-1},d={__proto__:null};s&&i&&l?t(u,function(m){var T=new a[m];if(Symbol.toStringTag in T){var E=l(T),g=i(E,Symbol.toStringTag);if(!g){var S=l(E);g=i(S,Symbol.toStringTag)}d["$"+m]=n(g.get)}}):t(u,function(m){var T=new a[m],E=T.slice||T.set;E&&(d["$"+m]=n(E))});var f=function(T){var E=!1;return t(d,function(g,S){if(!E)try{"$"+g(T)===S&&(E=c(S,1))}catch{}}),E},h=function(T){var E=!1;return t(d,function(g,S){if(!E)try{g(T),E=c(S,1)}catch{}}),E};return Kt=function(T){if(!T||typeof T!="object")return!1;if(!s){var E=c(o(T),8,-1);return p(u,E)>-1?E:E!=="Object"?!1:h(T)}return i?f(T):null},Kt}var Ht,wn;function Zs(){if(wn)return Ht;wn=1;var t=Js();return Ht=function(n){return!!t(n)},Ht}var En;function ea(){return En||(En=1,(function(t){var e=Hs(),n=$s(),r=Xs(),i=Zs();function o(C){return C.call.bind(C)}var s=typeof BigInt<"u",a=typeof Symbol<"u",u=o(Object.prototype.toString),c=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),p=o(Boolean.prototype.valueOf);if(s)var d=o(BigInt.prototype.valueOf);if(a)var f=o(Symbol.prototype.valueOf);function h(C,gi){if(typeof C!="object")return!1;try{return gi(C),!0}catch{return!1}}t.isArgumentsObject=e,t.isGeneratorFunction=n,t.isTypedArray=i;function m(C){return typeof Promise<"u"&&C instanceof Promise||C!==null&&typeof C=="object"&&typeof C.then=="function"&&typeof C.catch=="function"}t.isPromise=m;function T(C){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(C):i(C)||k(C)}t.isArrayBufferView=T;function E(C){return r(C)==="Uint8Array"}t.isUint8Array=E;function g(C){return r(C)==="Uint8ClampedArray"}t.isUint8ClampedArray=g;function S(C){return r(C)==="Uint16Array"}t.isUint16Array=S;function v(C){return r(C)==="Uint32Array"}t.isUint32Array=v;function I(C){return r(C)==="Int8Array"}t.isInt8Array=I;function _(C){return r(C)==="Int16Array"}t.isInt16Array=_;function F(C){return r(C)==="Int32Array"}t.isInt32Array=F;function y(C){return r(C)==="Float32Array"}t.isFloat32Array=y;function R(C){return r(C)==="Float64Array"}t.isFloat64Array=R;function N(C){return r(C)==="BigInt64Array"}t.isBigInt64Array=N;function D(C){return r(C)==="BigUint64Array"}t.isBigUint64Array=D;function L(C){return u(C)==="[object Map]"}L.working=typeof Map<"u"&&L(new Map);function U(C){return typeof Map>"u"?!1:L.working?L(C):C instanceof Map}t.isMap=U;function $(C){return u(C)==="[object Set]"}$.working=typeof Set<"u"&&$(new Set);function X(C){return typeof Set>"u"?!1:$.working?$(C):C instanceof Set}t.isSet=X;function oe(C){return u(C)==="[object WeakMap]"}oe.working=typeof WeakMap<"u"&&oe(new WeakMap);function q(C){return typeof WeakMap>"u"?!1:oe.working?oe(C):C instanceof WeakMap}t.isWeakMap=q;function G(C){return u(C)==="[object WeakSet]"}G.working=typeof WeakSet<"u"&&G(new WeakSet);function H(C){return G(C)}t.isWeakSet=H;function z(C){return u(C)==="[object ArrayBuffer]"}z.working=typeof ArrayBuffer<"u"&&z(new ArrayBuffer);function te(C){return typeof ArrayBuffer>"u"?!1:z.working?z(C):C instanceof ArrayBuffer}t.isArrayBuffer=te;function b(C){return u(C)==="[object DataView]"}b.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&b(new DataView(new ArrayBuffer(1),0,1));function k(C){return typeof DataView>"u"?!1:b.working?b(C):C instanceof DataView}t.isDataView=k;var P=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function V(C){return u(C)==="[object SharedArrayBuffer]"}function j(C){return typeof P>"u"?!1:(typeof V.working>"u"&&(V.working=V(new P)),V.working?V(C):C instanceof P)}t.isSharedArrayBuffer=j;function Q(C){return u(C)==="[object AsyncFunction]"}t.isAsyncFunction=Q;function B(C){return u(C)==="[object Map Iterator]"}t.isMapIterator=B;function x(C){return u(C)==="[object Set Iterator]"}t.isSetIterator=x;function W(C){return u(C)==="[object Generator]"}t.isGeneratorObject=W;function re(C){return u(C)==="[object WebAssembly.Module]"}t.isWebAssemblyCompiledModule=re;function ce(C){return h(C,c)}t.isNumberObject=ce;function Ke(C){return h(C,l)}t.isStringObject=Ke;function Pe(C){return h(C,p)}t.isBooleanObject=Pe;function He(C){return s&&h(C,d)}t.isBigIntObject=He;function hr(C){return a&&h(C,f)}t.isSymbolObject=hr;function mi(C){return ce(C)||Ke(C)||Pe(C)||He(C)||hr(C)}t.isBoxedPrimitive=mi;function yi(C){return typeof Uint8Array<"u"&&(te(C)||j(C))}t.isAnyArrayBuffer=yi,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(C){Object.defineProperty(t,C,{enumerable:!1,value:function(){throw new Error(C+" is not supported in userland")}})})})(yt)),yt}var $t,In;function ta(){return In||(In=1,$t=function(e){return e&&typeof e=="object"&&typeof e.copy=="function"&&typeof e.fill=="function"&&typeof e.readUInt8=="function"}),$t}var tt={exports:{}},On;function ra(){return On||(On=1,typeof Object.create=="function"?tt.exports=function(e,n){n&&(e.super_=n,e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:tt.exports=function(e,n){if(n){e.super_=n;var r=function(){};r.prototype=n.prototype,e.prototype=new r,e.prototype.constructor=e}}),tt.exports}var kn;function fr(){return kn||(kn=1,(function(t){var e=Object.getOwnPropertyDescriptors||function(k){for(var P=Object.keys(k),V={},j=0;j<P.length;j++)V[P[j]]=Object.getOwnPropertyDescriptor(k,P[j]);return V},n=/%[sdj%]/g;t.format=function(b){if(!I(b)){for(var k=[],P=0;P<arguments.length;P++)k.push(s(arguments[P]));return k.join(" ")}for(var P=1,V=arguments,j=V.length,Q=String(b).replace(n,function(x){if(x==="%%")return"%";if(P>=j)return x;switch(x){case"%s":return String(V[P++]);case"%d":return Number(V[P++]);case"%j":try{return JSON.stringify(V[P++])}catch{return"[Circular]"}default:return x}}),B=V[P];P<j;B=V[++P])g(B)||!R(B)?Q+=" "+B:Q+=" "+s(B);return Q},t.deprecate=function(b,k){if(typeof M<"u"&&M.noDeprecation===!0)return b;if(typeof M>"u")return function(){return t.deprecate(b,k).apply(this,arguments)};var P=!1;function V(){if(!P){if(M.throwDeprecation)throw new Error(k);M.traceDeprecation?console.trace(k):console.error(k),P=!0}return b.apply(this,arguments)}return V};var r={},i=/^$/;if(M.env.NODE_DEBUG){var o=M.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}t.debuglog=function(b){if(b=b.toUpperCase(),!r[b])if(i.test(b)){var k=M.pid;r[b]=function(){var P=t.format.apply(t,arguments);console.error("%s %d: %s",b,k,P)}}else r[b]=function(){};return r[b]};function s(b,k){var P={seen:[],stylize:u};return arguments.length>=3&&(P.depth=arguments[2]),arguments.length>=4&&(P.colors=arguments[3]),E(k)?P.showHidden=k:k&&t._extend(P,k),F(P.showHidden)&&(P.showHidden=!1),F(P.depth)&&(P.depth=2),F(P.colors)&&(P.colors=!1),F(P.customInspect)&&(P.customInspect=!0),P.colors&&(P.stylize=a),l(P,b,P.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(b,k){var P=s.styles[k];return P?"\x1B["+s.colors[P][0]+"m"+b+"\x1B["+s.colors[P][1]+"m":b}function u(b,k){return b}function c(b){var k={};return b.forEach(function(P,V){k[P]=!0}),k}function l(b,k,P){if(b.customInspect&&k&&L(k.inspect)&&k.inspect!==t.inspect&&!(k.constructor&&k.constructor.prototype===k)){var V=k.inspect(P,b);return I(V)||(V=l(b,V,P)),V}var j=p(b,k);if(j)return j;var Q=Object.keys(k),B=c(Q);if(b.showHidden&&(Q=Object.getOwnPropertyNames(k)),D(k)&&(Q.indexOf("message")>=0||Q.indexOf("description")>=0))return d(k);if(Q.length===0){if(L(k)){var x=k.name?": "+k.name:"";return b.stylize("[Function"+x+"]","special")}if(y(k))return b.stylize(RegExp.prototype.toString.call(k),"regexp");if(N(k))return b.stylize(Date.prototype.toString.call(k),"date");if(D(k))return d(k)}var W="",re=!1,ce=["{","}"];if(T(k)&&(re=!0,ce=["[","]"]),L(k)){var Ke=k.name?": "+k.name:"";W=" [Function"+Ke+"]"}if(y(k)&&(W=" "+RegExp.prototype.toString.call(k)),N(k)&&(W=" "+Date.prototype.toUTCString.call(k)),D(k)&&(W=" "+d(k)),Q.length===0&&(!re||k.length==0))return ce[0]+W+ce[1];if(P<0)return y(k)?b.stylize(RegExp.prototype.toString.call(k),"regexp"):b.stylize("[Object]","special");b.seen.push(k);var Pe;return re?Pe=f(b,k,P,B,Q):Pe=Q.map(function(He){return h(b,k,P,B,He,re)}),b.seen.pop(),m(Pe,W,ce)}function p(b,k){if(F(k))return b.stylize("undefined","undefined");if(I(k)){var P="'"+JSON.stringify(k).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return b.stylize(P,"string")}if(v(k))return b.stylize(""+k,"number");if(E(k))return b.stylize(""+k,"boolean");if(g(k))return b.stylize("null","null")}function d(b){return"["+Error.prototype.toString.call(b)+"]"}function f(b,k,P,V,j){for(var Q=[],B=0,x=k.length;B<x;++B)G(k,String(B))?Q.push(h(b,k,P,V,String(B),!0)):Q.push("");return j.forEach(function(W){W.match(/^\d+$/)||Q.push(h(b,k,P,V,W,!0))}),Q}function h(b,k,P,V,j,Q){var B,x,W;if(W=Object.getOwnPropertyDescriptor(k,j)||{value:k[j]},W.get?W.set?x=b.stylize("[Getter/Setter]","special"):x=b.stylize("[Getter]","special"):W.set&&(x=b.stylize("[Setter]","special")),G(V,j)||(B="["+j+"]"),x||(b.seen.indexOf(W.value)<0?(g(P)?x=l(b,W.value,null):x=l(b,W.value,P-1),x.indexOf(`
|
|
3
|
-
`)>-1&&(Q?x=x.split(`
|
|
4
|
-
`).map(function(re){return" "+re}).join(`
|
|
5
|
-
`).slice(2):x=`
|
|
6
|
-
`+x.split(`
|
|
7
|
-
`).map(function(re){return" "+re}).join(`
|
|
8
|
-
`))):x=b.stylize("[Circular]","special")),F(B)){if(Q&&j.match(/^\d+$/))return x;B=JSON.stringify(""+j),B.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(B=B.slice(1,-1),B=b.stylize(B,"name")):(B=B.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),B=b.stylize(B,"string"))}return B+": "+x}function m(b,k,P){var V=b.reduce(function(j,Q){return Q.indexOf(`
|
|
9
|
-
`)>=0,j+Q.replace(/\u001b\[\d\d?m/g,"").length+1},0);return V>60?P[0]+(k===""?"":k+`
|
|
10
|
-
`)+" "+b.join(`,
|
|
11
|
-
`)+" "+P[1]:P[0]+k+" "+b.join(", ")+" "+P[1]}t.types=ea();function T(b){return Array.isArray(b)}t.isArray=T;function E(b){return typeof b=="boolean"}t.isBoolean=E;function g(b){return b===null}t.isNull=g;function S(b){return b==null}t.isNullOrUndefined=S;function v(b){return typeof b=="number"}t.isNumber=v;function I(b){return typeof b=="string"}t.isString=I;function _(b){return typeof b=="symbol"}t.isSymbol=_;function F(b){return b===void 0}t.isUndefined=F;function y(b){return R(b)&&$(b)==="[object RegExp]"}t.isRegExp=y,t.types.isRegExp=y;function R(b){return typeof b=="object"&&b!==null}t.isObject=R;function N(b){return R(b)&&$(b)==="[object Date]"}t.isDate=N,t.types.isDate=N;function D(b){return R(b)&&($(b)==="[object Error]"||b instanceof Error)}t.isError=D,t.types.isNativeError=D;function L(b){return typeof b=="function"}t.isFunction=L;function U(b){return b===null||typeof b=="boolean"||typeof b=="number"||typeof b=="string"||typeof b=="symbol"||typeof b>"u"}t.isPrimitive=U,t.isBuffer=ta();function $(b){return Object.prototype.toString.call(b)}function X(b){return b<10?"0"+b.toString(10):b.toString(10)}var oe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function q(){var b=new Date,k=[X(b.getHours()),X(b.getMinutes()),X(b.getSeconds())].join(":");return[b.getDate(),oe[b.getMonth()],k].join(" ")}t.log=function(){console.log("%s - %s",q(),t.format.apply(t,arguments))},t.inherits=ra(),t._extend=function(b,k){if(!k||!R(k))return b;for(var P=Object.keys(k),V=P.length;V--;)b[P[V]]=k[P[V]];return b};function G(b,k){return Object.prototype.hasOwnProperty.call(b,k)}var H=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;t.promisify=function(k){if(typeof k!="function")throw new TypeError('The "original" argument must be of type Function');if(H&&k[H]){var P=k[H];if(typeof P!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(P,H,{value:P,enumerable:!1,writable:!1,configurable:!0}),P}function P(){for(var V,j,Q=new Promise(function(W,re){V=W,j=re}),B=[],x=0;x<arguments.length;x++)B.push(arguments[x]);B.push(function(W,re){W?j(W):V(re)});try{k.apply(this,B)}catch(W){j(W)}return Q}return Object.setPrototypeOf(P,Object.getPrototypeOf(k)),H&&Object.defineProperty(P,H,{value:P,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(P,e(k))},t.promisify.custom=H;function z(b,k){if(!b){var P=new Error("Promise was rejected with a falsy value");P.reason=b,b=P}return k(b)}function te(b){if(typeof b!="function")throw new TypeError('The "original" argument must be of type Function');function k(){for(var P=[],V=0;V<arguments.length;V++)P.push(arguments[V]);var j=P.pop();if(typeof j!="function")throw new TypeError("The last argument must be of type Function");var Q=this,B=function(){return j.apply(Q,arguments)};b.apply(this,P).then(function(x){M.nextTick(B.bind(null,null,x))},function(x){M.nextTick(z.bind(null,x,B))})}return Object.setPrototypeOf(k,Object.getPrototypeOf(b)),Object.defineProperties(k,e(b)),k}t.callbackify=te})(mt)),mt}var zt,Nn;function fi(){if(Nn)return zt;Nn=1;const{inherits:t,format:e}=fr();function n(r,i,o=Error){if(!r)throw new Error("Avvio error code must not be empty");if(!i)throw new Error("Avvio base error message must not be empty");function s(a,u,c){if(!new.target)return new s(a,u,c);Error.captureStackTrace(this,s),this.code=r,this.message=i,this.name="AvvioError",a&&u&&c?this.message=e(i,a,u,c):a&&u?this.message=e(i,a,u):a?this.message=e(i,a):this.message=i}return s.prototype[Symbol.toStringTag]="Error",s.prototype.toString=function(){return`${this.name} [${this.code}]: ${this.message}`},t(s,o),s}return zt={createError:n,AVV_ERR_EXPOSE_ALREADY_DEFINED:n("AVV_ERR_EXPOSE_ALREADY_DEFINED","'%s' () is already defined, specify an expose option"),AVV_ERR_CALLBACK_NOT_FN:n("AVV_ERR_CALLBACK_NOT_FN","Callback for '%s' hook is not a function. Received: '%s'"),AVV_ERR_PLUGIN_NOT_VALID:n("AVV_ERR_PLUGIN_NOT_VALID","Plugin must be a function or a promise. Received: '%s'"),AVV_ERR_ROOT_PLG_BOOTED:n("AVV_ERR_PLUGIN_NOT_VALID","Root plugin has already booted"),AVV_ERR_PARENT_PLG_LOADED:n("AVV_ERR_PARENT_PLG_LOADED","Impossible to load '%s' plugin because the parent '%s' was already loaded"),AVV_ERR_READY_TIMEOUT:n("AVV_ERR_READY_TIMEOUT","Plugin did not start in time: '%s'. You may have forgotten to call 'done' function or to resolve a Promise")},zt}var Yt,Cn;function na(){return Cn||(Cn=1,Yt=function t(e,n,r){n===void 0&&(n=""),r||(r={});var i=function(u){var c={"│":"|","└":"`","├":"+","─":"-","┬":"-"};return r.unicode===!1?c[u]:u};typeof e=="string"&&(e={label:e});var o=e.nodes||[],s=(e.label||"").split(`
|
|
12
|
-
`),a=`
|
|
13
|
-
`+n+(o.length?i("│"):" ")+" ";return n+s.join(a)+`
|
|
14
|
-
`+o.map(function(u,c){var l=c===o.length-1,p=u.nodes&&u.nodes.length,d=n+(l?" ":i("│"))+" ";return n+i(l?"└":"├")+i("─")+i(p?"┬":"─")+" "+t(u,d,r).slice(n.length+2)}).join("")}),Yt}var Xt,Rn;function ia(){if(Rn)return Xt;Rn=1;const t=na(),e=Symbol("avvio.TimeTree.untrackNode"),n=Symbol("avvio.TimeTree.trackNode"),r=Symbol("avvio.TimeTree.getParent"),i=Symbol("avvio.TimeTree.getNode"),o=Symbol("avvio.TimeTree.addNode");class s{constructor(){this.root=null,this.tableId=new Map,this.tableLabel=new Map}[n](u){this.tableId.set(u.id,u),this.tableLabel.has(u.label)?this.tableLabel.get(u.label).push(u):this.tableLabel.set(u.label,[u])}[e](u){this.tableId.delete(u.id);const c=this.tableLabel.get(u.label);if(c.id){this.tableLabel.delete(u.label);return}c.pop(),c.length===0&&this.tableLabel.delete(u.label)}[r](u){if(u===null)return this.root;const c=this.tableLabel.get(u);return c.id?c:c[c.length-1]}[i](u){return this.tableId.get(u)}[o](u,c,l){if(u===null)return this.root={id:"root",label:c,start:l,nodes:[]},this[n](this.root),this.root.id;const d=this[r](u),f=`${c}-${Math.random()}`,h={id:f,parent:u,start:l,label:c,nodes:[]};return d.nodes.push(h),this[n](h),f}start(u,c,l=Date.now()){return this[o](u,c,l)}stop(u,c=Date.now()){const l=this[i](u);l&&(l.stop=c,l.diff=l.stop-l.start||0,this[e](l))}toJSON(){return Object.assign({},this.root)}prittyPrint(){const u=l=>(l.label=`${l.label} ${l.diff} ms`,l.nodes.length>0&&(l.nodes=l.nodes.map(p=>u(p))),l),c=u(this.toJSON());return t(c)}}return Xt=s,Xt}var rt={exports:{}},nt={exports:{}},Jt,Pn;function oa(){if(Pn)return Jt;Pn=1;var t=1e3,e=t*60,n=e*60,r=n*24,i=r*7,o=r*365.25;Jt=function(l,p){p=p||{};var d=typeof l;if(d==="string"&&l.length>0)return s(l);if(d==="number"&&isFinite(l))return p.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 p=/^(-?(?:\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(p){var d=parseFloat(p[1]),f=(p[2]||"ms").toLowerCase();switch(f){case"years":case"year":case"yrs":case"yr":case"y":return d*o;case"weeks":case"week":case"w":return d*i;case"days":case"day":case"d":return d*r;case"hours":case"hour":case"hrs":case"hr":case"h":return d*n;case"minutes":case"minute":case"mins":case"min":case"m":return d*e;case"seconds":case"second":case"secs":case"sec":case"s":return d*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return d;default:return}}}}function a(l){var p=Math.abs(l);return p>=r?Math.round(l/r)+"d":p>=n?Math.round(l/n)+"h":p>=e?Math.round(l/e)+"m":p>=t?Math.round(l/t)+"s":l+"ms"}function u(l){var p=Math.abs(l);return p>=r?c(l,p,r,"day"):p>=n?c(l,p,n,"hour"):p>=e?c(l,p,e,"minute"):p>=t?c(l,p,t,"second"):l+" ms"}function c(l,p,d,f){var h=p>=d*1.5;return Math.round(l/d)+" "+f+(h?"s":"")}return Jt}var Zt,Ln;function sa(){if(Ln)return Zt;Ln=1;function t(e){r.debug=r,r.default=r,r.coerce=c,r.disable=a,r.enable=o,r.enabled=u,r.humanize=oa(),r.destroy=l,Object.keys(e).forEach(p=>{r[p]=e[p]}),r.names=[],r.skips=[],r.formatters={};function n(p){let d=0;for(let f=0;f<p.length;f++)d=(d<<5)-d+p.charCodeAt(f),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=n;function r(p){let d,f=null,h,m;function T(...E){if(!T.enabled)return;const g=T,S=Number(new Date),v=S-(d||S);g.diff=v,g.prev=d,g.curr=S,d=S,E[0]=r.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let I=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(F,y)=>{if(F==="%%")return"%";I++;const R=r.formatters[y];if(typeof R=="function"){const N=E[I];F=R.call(g,N),E.splice(I,1),I--}return F}),r.formatArgs.call(g,E),(g.log||r.log).apply(g,E)}return T.namespace=p,T.useColors=r.useColors(),T.color=r.selectColor(p),T.extend=i,T.destroy=r.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==r.namespaces&&(h=r.namespaces,m=r.enabled(p)),m),set:E=>{f=E}}),typeof r.init=="function"&&r.init(T),T}function i(p,d){const f=r(this.namespace+(typeof d>"u"?":":d)+p);return f.log=this.log,f}function o(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];const d=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const f of d)f[0]==="-"?r.skips.push(f.slice(1)):r.names.push(f)}function s(p,d){let f=0,h=0,m=-1,T=0;for(;f<p.length;)if(h<d.length&&(d[h]===p[f]||d[h]==="*"))d[h]==="*"?(m=h,T=f,h++):(f++,h++);else if(m!==-1)h=m+1,T++,f=T;else return!1;for(;h<d.length&&d[h]==="*";)h++;return h===d.length}function a(){const p=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),p}function u(p){for(const d of r.skips)if(s(p,d))return!1;for(const d of r.names)if(s(p,d))return!0;return!1}function c(p){return p instanceof Error?p.stack||p.message:p}function l(){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}return Zt=t,Zt}var _n;function hi(){return _n||(_n=1,(function(t,e){e.formatArgs=r,e.save=i,e.load=o,e.useColors=n,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 n(){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 r(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,p=0;u[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(l++,d==="%c"&&(p=l))}),u.splice(p,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 M<"u"&&"env"in M&&(u=M.env.DEBUG),u}function s(){try{return localStorage}catch{}}t.exports=sa()(e);const{formatters:a}=t.exports;a.j=function(u){try{return JSON.stringify(u)}catch(c){return"[UnexpectedJSONParseError]: "+c.message}}})(nt,nt.exports)),nt.exports}var Dn;function aa(){if(Dn)return rt.exports;Dn=1;const t=ai(),e=ui().EventEmitter,n=fr().inherits,r=hi()("avvio"),{AVV_ERR_READY_TIMEOUT:i}=fi(),o=Symbol.for("plugin-meta");function s(d,f){return d[o]&&d[o].name?d[o].name:typeof f<"u"&&typeof f!="function"&&f.name?f.name:d.name?d.name:d.toString().split(`
|
|
15
|
-
`).slice(0,2).map(h=>h.trim()).join(" -- ")}function a(){const d={};return d.promise=new Promise((f,h)=>{d.resolve=f,d.reject=h}),d}function u(d,f,h,m,T){this.started=!1,this.func=f,this.opts=h,this.onFinish=null,this.parent=d,this.timeout=T===void 0?d._timeout:T,this.name=s(f,h),this.isAfter=m,this.q=t(d,c,1),this.q.pause(),this._error=null,this.loaded=!1,this._promise=null}n(u,e),u.prototype.exec=function(d,f){const h=this.func;let m=!1;const T=this.name;if(this.parent._error&&!this.isAfter){r("skipping loading of plugin as parent errored and it is not an after",T),M.nextTick(f);return}if(this.isAfter)this.server=d;else try{this.server=this.parent.override(d,h,this.opts)}catch(v){return r("override errored",T),f(v)}this.opts=typeof this.opts=="function"?this.opts(this.server):this.opts,r("exec",T);let E;const g=v=>{if(m){r("loading complete",T);return}this._error=v,r(v?"exec errored":"exec completed",T),m=!0,E&&clearTimeout(E),f(v)};this.timeout>0&&(r("setting up timeout",T,this.timeout),E=setTimeout(function(){r("timed out",T),E=null;const v=new i(T);v.fn=h,g(v)},this.timeout)),this.started=!0,this.emit("start",this.server?this.server.name:null,this.name,Date.now());const S=h(this.server,this.opts,g);S&&typeof S.then=="function"&&(r("exec: resolving promise",T),S.then(()=>M.nextTick(g),v=>M.nextTick(g,v)))},u.prototype.loadedSoFar=function(){if(this.loaded)return Promise.resolve();const d=()=>{this.server.after((h,m)=>{this._error=h,this.q.pause(),h?(r("rejecting promise",this.name,h),this._promise.reject(h)):(r("resolving promise",this.name),this._promise.resolve()),this._promise=null,M.nextTick(m,h)}),this.q.resume()};let f;return this._promise?f=Promise.resolve():(this._promise=a(),f=this._promise.promise,this.server?d():this.on("start",d)),f},u.prototype.enqueue=function(d,f){r("enqueue",this.name,d.name),this.emit("enqueue",this.server?this.server.name:null,this.name,Date.now()),this.q.push(d,f)},u.prototype.finish=function(d,f){r("finish",this.name,d);const h=()=>{this.loaded||(r("loaded",this.name),this.emit("loaded",this.server?this.server.name:null,this.name,Date.now()),this.loaded=!0,f(d))};if(d){this._promise&&(this._promise.reject(d),this._promise=null),h();return}const m=()=>{if(r("check",this.name,this.q.length(),this.q.running(),this._promise),this.q.length()===0&&this.q.running()===0)if(this._promise){const T=()=>{r("wrap"),queueMicrotask(m)};this._promise.resolve(),this._promise.promise.then(T,T),this._promise=null}else h();else r("delayed",this.name),this.q.drain=()=>{r("drain",this.name),this.q.drain=p,queueMicrotask(m)}};queueMicrotask(m),this.q.resume()};function c(d,f){const h=this;M.nextTick(l.bind(h),d,f)}function l(d,f){if(typeof d.func.then=="function"){d.func.then(m=>{typeof m.default=="function"&&(m=m.default),d.func=m,l.call(this,d,f)},f);return}const h=this._current[0];this._current.unshift(d),d.exec(h&&h.server||this._server,m=>{d.finish(m,T=>{this._current.shift(),f(T)})})}function p(){}return rt.exports=u,rt.exports.loadPlugin=l,rt.exports}var Fn;function ua(){if(Fn)return Je.exports;Fn=1;const t=ai(),e=ui().EventEmitter,n=fr().inherits,{AVV_ERR_EXPOSE_ALREADY_DEFINED:r,AVV_ERR_CALLBACK_NOT_FN:i,AVV_ERR_PLUGIN_NOT_VALID:o,AVV_ERR_ROOT_PLG_BOOTED:s,AVV_ERR_READY_TIMEOUT:a}=fi(),u=ia(),c=aa(),l=hi()("avvio"),p=Symbol("kAvvio"),d=Symbol("kThenifyDoNotWrap");function f(y,R,N){const D=R.expose||{},L=D.use||"use",U=D.after||"after",$=D.ready||"ready",X=D.onClose||"onClose",oe=D.close||"close";if(y[L])throw new r(L);if(y[U])throw new r(U);if(y[$])throw new r($);y[L]=function(q,G){return N.use(q,G),this},Object.defineProperty(y,"then",{get:g.bind(N)}),y[p]=!0,y[U]=function(q){return typeof q!="function"?N._loadRegistered():(N.after(F(q,this)),this)},y[$]=function(q){if(q&&typeof q!="function")throw new i($,typeof q);return N.ready(q?F(q,this):void 0)},y[X]=function(q){if(typeof q!="function")throw new i(X,typeof q);return N.onClose(_(q,this)),this},y[oe]=function(q){if(q&&typeof q!="function")throw new i(oe,typeof q);return q?(N.close(F(q,this)),this):N.close()}}function h(y,R,N){if(typeof y=="function"&&arguments.length===1&&(N=y,R={},y=null),typeof R=="function"&&(N=R,R={}),R=R||{},!(this instanceof h)){const D=new h(y,R,N);return y&&f(y,R,D),D}R.autostart!==!1&&(R.autostart=!0),y=y||this,this._timeout=Number(R.timeout)||0,this._server=y,this._current=[],this._error=null,this._isOnCloseHandlerKey=Symbol("isOnCloseHandler"),this._lastUsed=null,this.setMaxListeners(0),N&&this.once("start",N),this.started=!1,this.booted=!1,this.pluginTree=new u,this._readyQ=t(this,S,1),this._readyQ.pause(),this._readyQ.drain=()=>{this.emit("start"),this._readyQ.drain=E},this._closeQ=t(this,I,1),this._closeQ.pause(),this._closeQ.drain=()=>{this.emit("close"),this._closeQ.drain=E},this._doStart=null,this._root=new c(this,m.bind(this),R,!1,0),this._root.once("start",(D,L,U)=>{const $=this.pluginTree.start(null,L,U);this._root.once("loaded",(X,oe,q)=>{this.pluginTree.stop($,q)})}),c.loadPlugin.call(this,this._root,D=>{l("root plugin ready");try{this.emit("preReady"),this._root=null}catch(L){D=D||this._error||L}if(D){if(this._error=D,this._readyQ.length()===0)throw D}else this.booted=!0;this._readyQ.resume()})}function m(y,R,N){this._doStart=N,R.autostart&&this.start()}n(h,e),h.prototype.start=function(){return this.started=!0,M.nextTick(this._doStart),this},h.prototype.override=function(y,R,N){return y};function T(y){if(y&&typeof y=="object"&&typeof y.default=="function"&&(y=y.default),!(y&&(typeof y=="function"||typeof y.then=="function")))throw new o(typeof y);return y}h.prototype[p]=!0,h.prototype.use=function(y,R){return this._lastUsed=this._addPlugin(y,R,!1),this},h.prototype._loadRegistered=function(){const y=this._current[0];return!this.started&&!this.booted&&M.nextTick(()=>this._root.q.resume()),y?y.loadedSoFar():Promise.resolve()},Object.defineProperty(h.prototype,"then",{get:g}),h.prototype._addPlugin=function(y,R,N){if(y=T(y),R=R||{},this.booted)throw new s;const D=this._current[0],L=new c(this,y,R,N);if(L.once("start",(U,$,X)=>{const oe=this.pluginTree.start(D.name,$,X);L.once("loaded",(q,G,H)=>{this.pluginTree.stop(oe,H)})}),D.loaded)throw new Error(L.name,D.name);return D.enqueue(L,U=>{U&&(this._error=U)}),L},h.prototype.after=function(y){if(!y)return this._loadRegistered();this._addPlugin(R.bind(this),{},!0);function R(N,D,L){S.call(this,y,L)}return this},h.prototype.onClose=function(y){if(typeof y!="function")throw new Error("not a function");y[this._isOnCloseHandlerKey]=!0,this._closeQ.unshift(y,R.bind(this));function R(N){N&&(this._error=N)}return this},h.prototype.close=function(y){let R;if(y){if(typeof y!="function")throw new i("close",typeof y)}else R=new Promise(function(N,D){y=function(L){if(L)return D(L);N()}});return this.ready(()=>{this._error=null,this._closeQ.push(y),M.nextTick(this._closeQ.resume.bind(this._closeQ))}),R},h.prototype.ready=function(y){if(y){if(typeof y!="function")throw new i("ready",typeof y);this._readyQ.push(y),queueMicrotask(this.start.bind(this));return}return new Promise((R,N)=>{this._readyQ.push(L),this.start();const D=this._current[0].server;function L(U,$,X){U?N(U):R(D),M.nextTick(X)}})},h.prototype.prettyPrint=function(){return this.pluginTree.prittyPrint()},h.prototype.toJSON=function(){return this.pluginTree.toJSON()};function E(){}function g(){if(this.booted){l("thenify returning null because we are already booted");return}if(this[d]){this[d]=!1;return}return l("thenify"),(y,R)=>this._loadRegistered().then(()=>(this[d]=!0,y(this._server)),R)}function S(y,R){const N=this._server,D=this._error;let L;if(this._error=null,y.length===0)this._error=D,L=y(),L&&!L[p]&&typeof L.then=="function"?L.then(()=>M.nextTick(R),U=>M.nextTick(R,U)):M.nextTick(R);else if(y.length===1)L=y(D),L&&!L[p]&&typeof L.then=="function"?L.then(()=>M.nextTick(R),U=>M.nextTick(R,U)):M.nextTick(R);else if(this._timeout===0){const U=$=>{this._error=$,R(this._error)};y.length===2?y(D,U):y(D,N,U)}else v.call(this,y,D,N,R)}function v(y,R,N,D){const L=y.name;l("setting up ready timeout",L,this._timeout);let U=setTimeout(()=>{l("timed out",L),U=null;const X=new a(L);X.fn=y,this._error=X,D(X)},this._timeout);y.length===2?y(R,$.bind(this)):y(R,N,$.bind(this));function $(X){U&&(clearTimeout(U),this._error=X,D(this._error))}}function I(y,R){const N=this._server,D=y[this._isOnCloseHandlerKey];if(y.length===0||y.length===1){let L;D?L=y(N):L=y(this._error),L&&typeof L.then=="function"?(l("resolving close/onClose promise"),L.then(()=>M.nextTick(R),U=>M.nextTick(R,U))):M.nextTick(R)}else y.length===2?y(D?N:this._error,R):D?y(N,R):y(this._error,N,R)}function _(y,R){return N.bind(R);function N(D,L){let U;y.length===0?(U=y(),U&&U.then?U.then(function(){M.nextTick(L)},L):M.nextTick(L)):y.length===1?(U=y(this),U&&U.then?U.then(function(){M.nextTick(L)},L):M.nextTick(L)):y(this,L)}}function F(y,R){return N.bind(R);function N(D,L){let U;y?y.length===0?(U=y(),U&&U.then?U.then(function(){M.nextTick(L,D)},L):M.nextTick(L,D)):y.length===1?(U=y(D),U&&U.then?U.then(function(){M.nextTick(L)},L):M.nextTick(L)):y.length===2?y(D,L):y(D,this,L):M.nextTick(L)}}return Je.exports=h,Je.exports.express=function(y){return h(y,{expose:{use:"load"}})},Je.exports}var ca=ua();const la=si(ca);(function(){if(window.requestAnimationFrame&&window.cancelAnimationFrame)return;const t=["webkit","moz","ms","o"];for(const e of t)window.requestAnimationFrame=window.requestAnimationFrame||window[`${e}RequestAnimationFrame`],window.cancelAnimationFrame=window.cancelAnimationFrame||window[`${e}CancelAnimationFrame`]||window[`${e}CancelRequestAnimationFrame`];if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){let e=0;const n=!!(window.performance&&window.performance.now);window.requestAnimationFrame=function(r){const i=n?window.performance.now():new Date().getTime(),o=Math.max(0,16-(i-e)),s=window.setTimeout(function(){r(i+o)},o);return e=i+o,s},window.cancelAnimationFrame=clearTimeout}})();function da(t,e=!0,n=!0,r={friendsTab:"enabled"}){const i=e?"https://grpc-sdk.streamlayer.io:443":"https://grpc-sdk.next.streamlayer.io:443",o=e?"https://grpc.streamlayer.io:443":"https://grpc.next.streamlayer.io:443",s=la(Object.create({}),{autostart:!1});return s.use(Bo,{hideFriends:r.hideFriends,skipOnboarding:r.skipOnboarding,betPack:r.betPack,friendsTab:r.friendsTab,theme:r.theme,themeMode:r.themeMode}),s.use(Lo,{onDeepLinkHandled:r?.onDeepLinkHandled}),s.use(Uo,{videoPlayerController:r?.videoPlayerController}),s.use(xo,{onContentActivate:r?.onContentActivate,withAd:r?.withAd,withAdNotification:r?.withAdNotification}),s.use(zi,{sdkKey:t,host:i,analyticsHost:o,version:r?.version,webOS:r?.webOS}),s.use(eo),s.use(Fo),r?.gamification!==!1&&(s.use(Yo),s.use(wo),s.use(es)),s.use(_s),s.use(Ss),s.after((a,u,c)=>{if(a)throw a;u.ready(),c()}),n&&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=da;exports.getDefaultExportFromCjs=si;
|