gamestage 0.76.0 → 0.77.0

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.
Files changed (2) hide show
  1. package/cli.mjs +2 -2
  2. package/package.json +1 -1
package/cli.mjs CHANGED
@@ -307,7 +307,7 @@ You scored {points} points.`},Dte=Object.keys(dz),mz=l.object({notify_template_s
307
307
  `);for(let n of t??[])process.stderr.write(` ${uf(n)}
308
308
  `)}process.exit(1)}async function So(e,t,n={}){if(Qc)Z({ok:!1,error:{code:e,message:t,...n.extra},detail:n.detail??[]});else{process.stderr.write(`${M.red("Error")} ${uf(t)}
309
309
  `);for(let r of n.detail??[])process.stderr.write(` ${uf(r)}
310
- `)}return la(n.exitCode??1)}var Qc,mce,om,M,pce,hce,XO,dt=F(()=>{"use strict";Qc=!1;mce=()=>!Qc&&process.stdout.isTTY===!0&&!process.env.NO_COLOR,om=(e,t)=>mce()?`\x1B[${e}m${t}\x1B[0m`:t,M={bold:e=>om("1",e),dim:e=>om("2",e),red:e=>om("31",e),green:e=>om("32",e),yellow:e=>om("33",e),cyan:e=>om("36",e)};pce=["admin","adopt","ads","archive","cdn","client","create","deploy","dev","doctor","docs","domain","endpoint","fixtures","formats","graphic","help","inspect","issue","leaderboard","link","list","live","login","logout","logs","look","manifest","open","org","plan","promote","prune","reference","rename","results","review","round","sources","start","status","suggest","suspend","theme","usage","verify","wake","whoami","workspace"],hce=/`gamestage ([a-z][a-z-]*)((?: [^`]*)?)`/g});function fce(e=Gw){let[t,n]=e.replace(/^[^\d]*/,"").split(".").map(Number);return[t,n||0]}function t3(e,t=Gw){let[n,r]=fce(t),[o,a]=e.split(".").map(Number);return o>n||o===n&&a>=r}var Jn,Gs,Gw,Dl=F(()=>{"use strict";Jn="0.76.0",Gs="2026-11-15-4",Gw=">=22.13.0"});function $o(){return{[h4]:Jn}}function gce(e){let t=e;return t?.code===Iw||t?.status===426}function yce(e){let t=e?.trim()||`Update required: this is gamestage ${Jn}, and a newer version is needed. Run ${Zc}.`;G()?process.stderr.write(JSON.stringify({ok:!1,code:Iw,error:t,update:{current:Jn,command:Zc},detail:[]},null,2)+`
310
+ `)}return la(n.exitCode??1)}var Qc,mce,om,M,pce,hce,XO,dt=F(()=>{"use strict";Qc=!1;mce=()=>!Qc&&process.stdout.isTTY===!0&&!process.env.NO_COLOR,om=(e,t)=>mce()?`\x1B[${e}m${t}\x1B[0m`:t,M={bold:e=>om("1",e),dim:e=>om("2",e),red:e=>om("31",e),green:e=>om("32",e),yellow:e=>om("33",e),cyan:e=>om("36",e)};pce=["admin","adopt","ads","archive","cdn","client","create","deploy","dev","doctor","docs","domain","endpoint","fixtures","formats","graphic","help","inspect","issue","leaderboard","link","list","live","login","logout","logs","look","manifest","open","org","plan","promote","prune","reference","rename","results","review","round","sources","start","status","suggest","suspend","theme","usage","verify","wake","whoami","workspace"],hce=/`gamestage ([a-z][a-z-]*)((?: [^`]*)?)`/g});function fce(e=Gw){let[t,n]=e.replace(/^[^\d]*/,"").split(".").map(Number);return[t,n||0]}function t3(e,t=Gw){let[n,r]=fce(t),[o,a]=e.split(".").map(Number);return o>n||o===n&&a>=r}var Jn,Gs,Gw,Dl=F(()=>{"use strict";Jn="0.77.0",Gs="2026-11-15-4",Gw=">=22.13.0"});function $o(){return{[h4]:Jn}}function gce(e){let t=e;return t?.code===Iw||t?.status===426}function yce(e){let t=e?.trim()||`Update required: this is gamestage ${Jn}, and a newer version is needed. Run ${Zc}.`;G()?process.stderr.write(JSON.stringify({ok:!1,code:Iw,error:t,update:{current:Jn,command:Zc},detail:[]},null,2)+`
311
311
  `):process.stderr.write(`${t}
312
312
  `),process.exit(1)}function qr(e){if(!gce(e))return;let t=e.code===Iw,n=e.message;yce(t&&typeof n=="string"?n:void 0)}var ni=F(()=>{"use strict";Qe();dt();Dl()});function bce(e){try{let t=new URL(e).hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.startsWith("127.")}catch{return!1}}function n3(e){return e.GAMESTAGE_TEST_RUN==="1"||e.NODE_TEST_CONTEXT!==void 0}function ls(e=process.env){return n3(e)?1:void 0}function qw(e=Qt,t=process.env){if(n3(t)&&!bce(e)&&t.GAMESTAGE_ALLOW_REMOTE_TESTS!=="1")return`Refusing to register a test game against non-local control plane ${e}. Use the throwaway local control plane, or set GAMESTAGE_ALLOW_REMOTE_TESTS=1 for a deliberate real-plane run.`}function am(e=Qt){let t=qw(e);t&&B(t)}async function Ei(){let e=await jn();return e||B("You are not signed in.",["Run `gamestage login`. It creates the account too if you do not have one.","Inspecting, scaffolding and validating a manifest still need no account."]),e}async function Fe(e={}){let t=await Ei();return{client:is({baseUrl:Qt,headers:$o(),maxAttempts:ls(),workspace:e.ignoreChoice?void 0:Jc(),org:e.org,token:async()=>(await jn())?.accessToken??t.accessToken}),email:t.email??t.userId??"unknown"}}async function Fa(e={}){let t=await jn().catch(()=>null);if(t)return is({baseUrl:Qt,headers:$o(),maxAttempts:ls(),workspace:Jc(),org:e.org,token:async()=>(await jn())?.accessToken??t.accessToken})}async function Pl(){await Ei();let e=await Fa();if(!e)throw new Error("Signed in, but the session could not be read. Run `gamestage login` again.");return e}async function nn(){let e=await jn();return e||B("You are not signed in.",["Run `gamestage login`. An operator's command needs an operator's own session."]),{admin:c4({baseUrl:Qt,headers:$o(),maxAttempts:ls(),token:async()=>(await jn())?.accessToken??e.accessToken}),email:e.email??e.userId??"unknown"}}async function df(e){try{let t=await e.getWorkspace(),n=t?.access;return n==="approved"||n==="pending"||n==="refused"?{access:n,workspace:t}:{access:"unreported",workspace:t}}catch(t){qr(t);let n=t.status,r=t.code;return r===QO?{access:"pending"}:r===Rw?{access:"unknown",problem:"not_a_control_plane",reason:t.message??`${Qt} is not a Gamestage control plane.`,detail:["You are signed in, and your token was never checked: the address is wrong, not the token.","The main Space's API is https://api.gamestage.ai, which is the default when GAMESTAGE_CONTROL_URL is unset."]}:n===404||r==="not_found"?{access:"unknown",problem:"no_control_plane",reason:`Nothing is serving a control plane at ${Qt}.`,detail:["You are signed in, and deploying will fail until this is pointed somewhere real.","Set GAMESTAGE_CONTROL_URL to your control plane and run this again."]}:n===401||n===403?{access:"unknown",problem:"token_refused",reason:"The control plane refused this account's token.",detail:[`It is at ${Qt}.`,"A token from one environment is refused by another, so check which one you signed into."]}:{access:"unknown",problem:"unreachable",reason:`Could not reach the control plane at ${Qt}.`,detail:[String(t.message??t),"You are signed in. Deploying will fail until this answers."]}}}function mf(e){switch(e.access){case"approved":return{ok:!0,status:"approved",access:"approved",heading:"Approved",message:"Your account is approved, so every command works, including deploy.",next:["`gamestage status` shows the workspace, its games and what they are using."]};case"pending":return{ok:!0,status:"pending_approval",access:"pending",code:QO,heading:"On the waitlist",message:"You are registered and your account is on the waitlist. That is the normal path for an account created without an invitation, and a person decides it.",next:["Finish your application at https://gamestage.ai/stage: three questions and the terms. Nobody can approve the account until both are in.","We email you when the account is approved, usually within one to two weeks.","Inspecting a prototype, scaffolding a game and writing a round all work now and need no approval.","`gamestage status` re-checks approval. It never opens the browser again."]};case"refused":return{ok:!0,status:"access_refused",access:"refused",heading:"Access refused",message:"This account has been refused access. Signing in worked, so this is a decision about the account rather than a broken token.",next:["Nothing in the CLI changes this, and running `gamestage login` again will not.","Inspecting, scaffolding and writing a round still work and need no account.",`If you think this is wrong, say so where you registered: ${bn}.`]};case"unreported":return{ok:!0,status:"access_not_reported",access:null,heading:"Signed in",message:"This control plane answered and does not report an access state, so whether this account is approved is not known here.",next:["It predates the access state rather than being broken, so carry on.","A deploy that is refused for approval will say so in its own words."]};default:return{ok:!1,status:e.problem==="no_control_plane"||e.problem==="not_a_control_plane"?e.problem:e.problem==="token_refused"?"token_refused":"control_plane_unreachable",access:null,heading:"Signed in, and the control plane is not usable",message:e.reason,next:e.detail}}}function o3(e){return!e.changed&&e.refused?{ok:!0,status:"refused_by_store",access:e.access,code:e.code,heading:"Not approved",message:e.refused,next:[e.code==="profile_incomplete"?"Nothing was written. When they have finished their application in Stage, run this again.":e.code==="personal_email"?"Nothing was written. Ask them to sign in with their work email, or approve the exception in Stage > Approvals.":"Nothing was written. When they have accepted the terms, run this again."]}:e.changed?e.access==="approved"?{ok:!0,status:"approved",access:"approved",heading:"Approved",message:`${e.workspaceId} was ${e.previous} and is now approved.`,next:["Their next `gamestage status` says approved, and deploy works from then on."]}:{ok:!0,status:"refused",access:"refused",heading:"Refused",message:`${e.workspaceId} was ${e.previous} and is now refused.`,next:["Their next `gamestage status` says refused, and says how to argue with it."]}:{ok:!0,status:"unchanged",access:e.access,heading:"No change",message:`${e.workspaceId} was already ${e.previous}. Nothing was written.`,next:["No audit record either: the trail records transitions, and this was not one."]}}function im(e){if(q(e.heading),w(` ${e.message}`),e.next.length){w();for(let t of e.next)I(t)}w()}function r3(e,t,n){let r=i=>{let s=i.trim().toLowerCase();return hi.options.find(c=>c===s||Ea[c].toLowerCase()===s)},o=hi.options.map(i=>`${i} (${Ea[i]})`).join(", "),a=r(t);return a?n===void 0?{request:{workspaceId:e,tier:a}}:!/^\d+$/.test(n)||Number(n)>1e4?{problem:`"${n}" is not a live-game allowance.`,detail:["Give a whole number from 0 to 10000, where 0 means no ceiling.","Nothing has been changed."]}:{request:{workspaceId:e,tier:a,allowance:Number(n)}}:r(e)?{problem:"The workspace comes first and the plan second.",detail:[`Try: ${xe(`admin plan ${t} ${e}`)}`,"Nothing has been changed."]}:{problem:`"${t}" is not a plan.`,detail:[`Use one of: ${o}.`,"Nothing has been changed."]}}function rm(e){let t=Ea[e.tier];if(e.liveGameAllowance===void 0)return t;let n=e.liveGameAllowance===0?"no live-game ceiling":`${e.liveGameAllowance} live game${e.liveGameAllowance===1?"":"s"}`;return`${t}, ${n}`}function a3(e){let{request:t,previous:n,result:r,stored:o}=e,a=rm({tier:t.tier,liveGameAllowance:t.allowance}),i={previous:n,stored:o};return r.refused?{...i,status:"refused_by_store",exitCode:1,heading:"Not changed",message:r.refused,next:["Nothing was written."]}:o?o.tier===t.tier&&(t.allowance===void 0||o.liveGameAllowance===t.allowance)?n!==null&&n.tier===o.tier&&n.liveGameAllowance===o.liveGameAllowance?{...i,status:"unchanged",exitCode:0,heading:"No change",message:`${t.workspaceId} was already on ${rm(o)}, and still is.`,next:[JO]}:{...i,status:"set",exitCode:0,heading:"Plan set",message:`${t.workspaceId} is on ${rm(o)}, read back from the control plane after the write.`,next:[JO]}:{...i,status:"not_what_was_asked",exitCode:1,heading:"Not what was asked",message:`${t.workspaceId} was sent ${a} and holds ${rm(o)}. The write reported success, and the stored workspace disagrees with it.`,next:["Run it again to see whether the second read agrees. If it still disagrees, that is a control-plane defect to raise, not an operator mistake."]}:{...i,status:"unconfirmed",exitCode:2,heading:"Sent, and not confirmed",message:`The control plane accepted ${t.workspaceId} moving to ${a}, and could not then be asked what it kept: ${e.unreadable??"no reason given"}.`,next:["Treat the plan as unknown rather than set. Run this again once the control plane answers reads; repeating the same plan is safe.",JO]}}function i3(e){if(q(e.heading),w(` ${e.message}`),w(),z("Before",e.previous?rm(e.previous):"could not be read"),z("Stored now",e.stored?rm(e.stored):"could not be read"),e.next.length){w();for(let t of e.next)I(t)}w()}function vce(e){let t=e.status,n=e instanceof Error?e.message:"";if(!(t!==404||!/^No game with id\b/.test(n)))return"This workspace has no game by that id: it was never registered, or `create` could not register it. Run `gamestage manifest register gamestage.yaml` in the game's folder, then run this again."}async function Ae(e){let t=[],n=e.status,r=e.code;if(qr(e),r===QO){let{client:a}=await Fe(),i=mf(await df(a));i.access==="approved"&&i.next.push("The original command was not completed. Run it again."),G()?Z({ok:!1,status:i.status,access:i.access,code:i.code,message:i.message,next:i.next}):im(i),process.exit(1)}r===Rw&&B(e instanceof Error?e.message:`${Qt} is not a Gamestage control plane.`,["Your session was never checked: the address is wrong, not the token.","Unset GAMESTAGE_CONTROL_URL to use https://api.gamestage.ai, or set it to a Space's API address.",`Code: ${r}`]);let o=vce(e);o&&t.push(o),n===401?t.push("Your session has expired. Run `gamestage login` again."):n===403&&r===Uc?G()&&await So(Uc,e instanceof Error?e.message:"Not an organisation admin."):n===403?t.push("Either your session expired or that is not something this workspace is allowed to do. `gamestage login` rules out the first."):n===429?t.push("You are being rate limited. Wait a moment and try again."):e.retryable&&t.push("This one is worth retrying: the failure was at our end."),r&&t.push(`Code: ${r}`),t.push(`Control plane: ${Qt}`),B(e instanceof Error?e.message:"The control plane call failed.",t)}var Qt,QO,JO,Ht=F(()=>{"use strict";Uw();Qe();xi();dt();Si();ni();Qt=process.env.GAMESTAGE_CONTROL_URL??"https://api.gamestage.ai";QO="access_pending";JO="This does not re-provision. A live round keeps the caps it was provisioned with, including its day cap, until the game is deployed again, so a creator refused before this is refused the same way until they redeploy with `gamestage deploy`. That is not this change failing."});var lm,tu,Bo,Ws,cs,Tn,us,Ice,Dce,Pce,Nce,Lce,Fce,Mce,zce,jce,Uce,Bce,cm,rR,oi=F(()=>{"use strict";lm=`/**
313
313
  * @monterosa/gamestage-player, bundled for a browser.
@@ -896,7 +896,7 @@ export {
896
896
  shootOperation,
897
897
  shootProgressOf
898
898
  };
899
- `,tu="48fd8242624ce764",Bo="gamestage-player.js",Ws='/**\n * @monterosa/gamestage, bundled for a browser.\n * Gamestage client 0.111.0.\n *\n * Generated by the Gamestage CLI. Do not edit: it is replaced whenever the CLI\n * writes it again, and it carries no game logic of yours. Minified; its source\n * map is beside it on gamestage.ai.\n */\nvar es=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var ja=Object.prototype.hasOwnProperty;var ee=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(s){throw n=[s],s}};var Vo=(e,t)=>{for(var n in t)es(e,n,{get:t[n],enumerable:!0})},qa=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fa(t))!ja.call(e,o)&&o!==n&&es(e,o,{get:()=>t[o],enumerable:!(s=Ua(t,o))||s.enumerable});return e};var Ba=e=>qa(es({},"__esModule",{value:!0}),e);function er(e,t){let n=a=>{let d=e[a],g=d&&typeof d=="object"?d:void 0,c=g?[t,"all","en",...Object.keys(g)].filter(u=>!!u).map(u=>g[u]).find(u=>typeof u=="boolean"||typeof u=="string"&&u.trim()):d;return typeof c=="boolean"?String(c):typeof c=="string"?c.trim():""},s=Object.fromEntries(Object.entries(tc).map(([a,d])=>[a,n(`label_notify_${a}`)||d])),o=n("consent_brand_name"),r=n("privacy_policy_url"),i=(n("notify_channels")||"email").split(",").map(a=>a.trim()).filter(a=>["email","sms","rcs"].includes(a));return{enabled:["true","yes","1"].includes(n("notify_enabled")),channels:i,ownerName:o,privacyUrl:r,labels:s,termsVersion:n("notify_terms_version")||"2",wording:`${s.consent.replaceAll("{brand}",o)} ${s.privacy}`}}function wn(e,t){return t==="email"?e.length<=254&&/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(e):/^\\+[1-9]\\d{6,14}$/.test(e)}var tc,ds=ee(()=>{"use strict";tc={title:"Tell me my result",via:"Send my result by",email:"Email",sms:"Text message",email_address:"Email address",mobile_number:"Mobile number",country:"Country",consent:"{brand} will use these details to tell you your result. You can unsubscribe at any time.",privacy:"Privacy policy",button:"Notify Me",pending:"Saving\\u2026",success:"Done. We\'ll tell you after full time.",error:"That did not work. Please try again.",invalid_email:"Enter an email address, such as name@example.com.",invalid_mobile:"Enter a complete mobile number for the country you picked.",code:"6-digit code",code_incomplete:"Enter all 6 digits.",confirm:"Confirm",resend_code:"Send a new code",resend_email:"Send the email again",resend_wait:"Send again in {seconds}s",resent:"Sent. Check again.",change_address:"Use a different number or email"}});function En(e,t){if(!e||typeof e!="object"||Array.isArray(e))return e;let n=e;for(let s of[t,"all","en",...Object.keys(n)])if(s&&n[s]!==void 0&&n[s]!==null&&n[s]!=="")return n[s]}function nr(e,t){if(!e)return{};let n={},s=En(e.gate_age_required,t),o=typeof s=="boolean"?s:typeof s=="string"?s.trim().toLowerCase():void 0;o===!0||o==="true"||o==="yes"||o==="1"?n.ageRequired=!0:(o===!1||o==="false"||o==="no"||o==="0")&&(n.ageRequired=!1);let r=En(e.gate_minimum_age,t),i=typeof r=="number"?r:typeof r=="string"&&r.trim()?Number(r.trim()):NaN;Number.isInteger(i)&&i>0&&i<=120&&(n.minimumAge=i);let a=En(e.gate_territories,t);if(typeof a=="string"&&a.trim()){let g=a.split(/[\\s,;]+/).map(c=>c.trim().toUpperCase()).filter(c=>/^[A-Z]{2}$/.test(c));n.territories=[...new Set(g)]}let d=En(e.gate_note,t);return typeof d=="string"&&d.trim()&&(n.note=d.trim().slice(0,200)),n}function sr(e,t){let n=e??{},s=n.ageRequired!==void 0;if(!(s||n.minimumAge!==void 0||n.territories!==void 0||n.note!==void 0))return t?{...t}:void 0;let i=n.ageRequired??!!t?.minimumAge?n.minimumAge??t?.minimumAge??nc:void 0,a=n.territories?.length?n.territories:n.territories!==void 0||!s?t?.territories:void 0,d=n.note??(s?void 0:t?.note);if(!(!i&&!a?.length))return{...i?{minimumAge:i}:{},...a?.length?{territories:[...a]}:{},...d?{note:d}:{}}}function or(e,t){if(!e||t!==!0||!e.minimumAge)return e;if(e.territories?.length)return{territories:[...e.territories],...e.note?{note:e.note}:{}}}var tr,nc,ls=ee(()=>{"use strict";tr=["gate_age_required","gate_minimum_age","gate_territories","gate_note"];nc=18});function Cn(e){let t=Array.isArray(e)?e.filter(s=>typeof s=="string"):typeof e=="string"?e.split(/[\\s,]+/):[],n=new Set;for(let s of t){let o=s.trim();if(!/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#@*\\s]+\\/?$/i.test(o))continue;let r;try{r=new URL(o)}catch{continue}let i=r.hostname==="localhost"||r.hostname==="127.0.0.1";r.protocol!=="https:"&&!(r.protocol==="http:"&&i)||n.add(r.origin)}return[...n]}function oc(){return{necessary:!0,analytics:!1,marketing:!1,functional:!1}}function qt(e,t,n={}){let s=oc();for(let o of rr)o!=="necessary"&&(s[o]=e[o]===!0);return{version:1,categories:s,source:t,decidedAt:(n.at??new Date).toISOString(),policyVersion:n.policyVersion??us,jurisdiction:n.jurisdiction??sc}}function cr(e){if(!e||typeof e!="object")return null;let t=e;if(t.version!==1||t.source!=="host"&&t.source!=="fan"&&t.source!=="default"||typeof t.decidedAt!="string"||typeof t.policyVersion!="string"||typeof t.jurisdiction!="string"||!t.categories||typeof t.categories!="object")return null;let n=t.categories;for(let s of rr)if(typeof n[s]!="boolean")return null;return qt(n,t.source,{policyVersion:t.policyVersion,jurisdiction:t.jurisdiction,at:new Date(t.decidedAt)})}function ur(e,t){let n=t.trim();if(e.includes("{brand}")){let s=!n||n.toLowerCase()==="monterosa";return e.includes("{brand} and Monterosa, who run")?s?e.replace("{brand} and Monterosa, who run","Monterosa, who runs").replaceAll("{brand}","Monterosa"):e.replaceAll("{brand}",n):e.replaceAll("{brand}",n||"Monterosa")}return e}var rr,ir,ar,sc,us,dr,lr,Tn=ee(()=>{"use strict";rr=["necessary","analytics","marketing","functional"],ir="gamestage:consent:v1",ar="gamestage:consent";sc="GB",us="1";dr="https://gamestage.ai/copyright",lr={brand:"",title:"Your privacy",detail:"{brand} would like to record analytics on how you play, so we can improve the game. We only do this if you agree. Data needed to run the game, such as your scores, is processed on the basis of legitimate interests.",accept:"Accept",reject:"Reject",dismiss:"Close",choose:"Manage preferences",save:"Save my choices",necessary:"Needed for the game to work. Always on.",analytics:"Measure how the game is played",marketing:"Offers and news from the game\'s owner",functional:"Remember my preferences",settings:"Privacy settings",policy:"Privacy policy",copyright:"Report copyright infringement"}});function Ce(e,t){if(typeof e=="string")return e.trim()||void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"]){if(!s)continue;let o=n[s];if(typeof o=="string"&&o.trim())return o.trim()}}function ac(e,t){if(typeof e=="boolean")return e;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"])if(s&&typeof n[s]=="boolean")return n[s]}function cc(e,t=ms){return`${t}/fonts/${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}.css`}function hs(e){return e.replace(/[^\\p{L}\\p{N} \\-]/gu,"").trim()}function xr(e,t){if(!e)return;let n=Object.keys(fs).find(i=>i.toLowerCase()===e.trim().toLowerCase());if(!n)return;let s=fs[n],o=Number(t);if(!Number.isFinite(o))return{family:n,weight:s[s.length-1]};let r=[...s].sort((i,a)=>Math.abs(i-o)-Math.abs(a-o)||a-i)[0];return{family:n,weight:r}}function kr(e){if(e===void 0)return;let t=/^\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+))(?:em)?\\s*$/i.exec(e);if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return`${Math.min(.4,Math.max(-.1,n))}em`}function Or(e){let t=e?.trim().toLowerCase();if(t)return["upper","uppercase","capitals","caps"].includes(t)?"uppercase":["none","uppercase","lowercase","capitalize"].includes(t)?t:"none"}function dc(e,t){let n=Ce(e.sponsor_name,t);if(!n)return;let s=Ce(e.sponsor_logo,t),o=Ce(e.sponsor_link,t);return{name:n,label:Ce(e.sponsor_intro,t)||"In association with",...s&&ps.test(s)?{logoUrl:s}:{},...o&&ps.test(o)?{link:o}:{}}}function Bt(e,t){let n=e?.trim();if(!n)return null;let s=t.find(r=>r.name.trim().toLowerCase()===n.toLowerCase());if(s){let r=hs(s.name);if(r)return{family:r}}let o=Object.keys(fs).find(r=>r.toLowerCase()===n.toLowerCase());return o?{family:o,stylesheetHref:cc(o)}:null}function at(e,t){let n={};if(!e)return n;if("notify_enabled"in e&&(n.notify=er(e,t)),tr.some(b=>b in e)){let b=nr(e,t);Object.keys(b).length>0&&(n.gate=b)}for(let[b,T]of Object.entries(rc)){let f=Ce(e[b],t);f&&(n[T]=f)}for(let[b,T]of Object.entries(ic)){if(n[T])continue;let f=Ce(e[b],t);f&&(n[T]=f)}let s=Ce(e.analytics_oneTrustId,t);s&&(n.oneTrustId=s);let o=Cn(Ce(e.embed_origins,t));o.length&&(n.embedOrigins=o);let r=Ce(e.logo_url,t)?.replace(/^\\/\\//,"https://");r&&ps.test(r)&&(n.logoUrl=r);let i=dc(e,t);i&&(n.sponsor=i);let a=Ce(e.default_font_family,t);a&&(n.defaultFontFamily=a);let d=e.uploaded_fonts;if(Array.isArray(d)){let b=f=>typeof f=="string"?f.trim():f==null?"":String(f),T=d.map(f=>f&&typeof f=="object"?f:{}).map(f=>({name:b(f.name),url:b(f.file),weight:b(f.weight)})).filter(f=>f.name&&f.url);T.length&&(n.uploadedFonts=T)}let g="css_variables_",c={};for(let b of Object.keys(e)){if(!b.startsWith(g))continue;let T=Ce(e[b],t);T&&(c[b.slice(g.length)]=T)}Object.keys(c).length>0&&(n.cssVariables=c);let u={};for(let b of Object.keys(e)){if(!b.startsWith(gr))continue;let T=Ce(e[b],t);T&&(u[b.slice(gr.length)]=T)}Object.keys(u).length>0&&(n.labels=u);let y={};for(let b of Object.keys(e)){if(!b.startsWith(gs)||b===gs)continue;let T=ac(e[b],t);T!==void 0&&(y[b.slice(gs.length)]=T)}return Object.keys(y).length>0&&(n.options=y),n}var fr,pr,mr,hr,yr,br,_r,vr,Sr,wr,Er,Cr,Tr,rc,ic,gr,gs,fs,ms,ps,St=ee(()=>{"use strict";ds();ls();Tn();fr="Provisional result. Final at {finalAt}.",pr=["a","b","c","d","e","f"],mr=e=>`quiz_option_${e}`,hr="quiz_question",yr="quiz_image",br="quiz_image_alt",_r="quiz_media",vr=e=>`quiz_option_${e}_image`,Sr="quiz_outcome_name",wr="quiz_outcome_verdict",Er="quiz_outcome_why",Cr="quiz_outcome_image",Tr="quiz_outcome_image_alt",rc={display_name:"displayName",title_font:"titleFont",title_font_weight:"titleFontWeight",title_letter_spacing:"titleLetterSpacing",title_colour:"titleColour",title_case:"titleCase",logo_text:"logoText",logo_accent_colour:"logoAccentColour",splash_gradient_start:"splashGradientStart",splash_gradient_end:"splashGradientEnd",splash_play_label:"splashPlayLabel",splash_continue_label:"splashContinueLabel",splash_error_text:"splashErrorText",splash_retry_label:"splashRetryLabel",consent_brand_name:"consentBrandName",consent_title:"consentTitle",consent_detail:"consentDetail",consent_accept_label:"consentAcceptLabel",consent_reject_label:"consentRejectLabel",consent_choose_label:"consentChooseLabel",consent_save_label:"consentSaveLabel",consent_analytics_label:"consentAnalyticsLabel",consent_marketing_label:"consentMarketingLabel",consent_functional_label:"consentFunctionalLabel",consent_settings_label:"consentSettingsLabel",consent_policy_version:"consentPolicyVersion",privacy_policy_url:"privacyPolicyUrl",signin_play_as_label:"signInPlayAsLabel",signin_detail:"signInDetail",signin_dismiss_label:"signInDismissLabel",recovery_open_label:"recoveryOpenLabel",recovery_show_title:"recoveryShowTitle",recovery_show_detail:"recoveryShowDetail",recovery_private_note:"recoveryPrivateNote",recovery_replace_note:"recoveryReplaceNote",recovery_enter_title:"recoveryEnterTitle",recovery_enter_detail:"recoveryEnterDetail",recovery_submit_label:"recoverySubmitLabel",recovery_not_recognised:"recoveryNotRecognised",recovery_restored:"recoveryRestored",recovery_get_label:"recoveryGetLabel",recovery_issue_failed:"recoveryIssueFailed",recovery_copy_label:"recoveryCopyLabel",recovery_copied_label:"recoveryCopiedLabel",recovery_share_label:"recoveryShareLabel",recovery_close_label:"recoveryCloseLabel",analytics_url:"analyticsUrl",strapline:"strapline",how_to_play:"howToPlay",primary_colour:"primaryColour",play_button_label:"playButtonLabel",play_again_label:"playAgainLabel",result_button_label:"resultButtonLabel",share_button_label:"shareButtonLabel",edition_name:"editionName",edition_strapline:"editionStrapline",edition_live_contest:"liveContest",margin_over:"marginOver",margin_exact:"marginExact",margin_under:"marginUnder",result_over:"resultOver",result_exact:"resultExact",result_under:"resultUnder",share_over:"shareOver",share_exact:"shareExact",share_under:"shareUnder",result_bust_note:"resultBustNote",share_bust_note:"shareBustNote",capped_today_note:"cappedTodayNote",share_dare:"shareDare",result_dare:"resultDare"},ic={primary_color:"primaryColour"},gr="label_",gs="option_";fs={"Abril Fatface":[400],Anton:[400],"Archivo Black":[400],"Bebas Neue":[400],Bungee:[400],"Chakra Petch":[300,400,500,600,700],"DM Serif Display":[400],Fraunces:[400,600,700,900],Oswald:[400,500,600,700],"Playfair Display":[400,700,900],"Russo One":[400],"Space Grotesk":[400,500,700],Teko:[400,500,600,700],Unbounded:[400,700,900]},ms="https://gamestage.ai";ps=/^https:\\/\\//i});function Te(e,t){if(typeof e=="string")return e.trim()||void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"]){if(!s)continue;let o=n[s];if(typeof o=="string"&&o.trim())return o.trim()}}function fc(e){return typeof e=="boolean"?e:Te(e)?.toLowerCase()==="true"}function zt(e,t){if(!e)return{enabled:!1};let n={web:Te(e.userAccessSignInUrlWeb,t),iOS:Te(e.userAccessSignInUrlNativeIOS,t),android:Te(e.userAccessSignInUrlNativeAndroid,t)},s={web:Te(e.userAccessSignUpUrlWeb,t),iOS:Te(e.userAccessSignUpUrlNativeIOS,t),android:Te(e.userAccessSignUpUrlNativeAndroid,t)},o=r=>Object.values(r).some(Boolean);return{enabled:fc(e.mIdEnabled),frontendUrl:Te(e.mIdFrontendUrl,t),apiUrl:Te(e.mIdApiUrl,t),clientId:Te(e.xClientId,t),title:Te(e.userAccessTitle,t),subtitle:Te(e.userAccessSubtitle,t),...o(n)?{signInUrl:n}:{},...o(s)?{signUpUrl:s}:{}}}var vs=ee(()=>{"use strict"});function Et(e,t){return e.declared?e.categories[t]===!0:!1}function ct(e,t){return e.analyticsRequiresConsent?Et(t,Mr):!0}function dt(e,t){return ct(e,t)}var Mr,Ht=ee(()=>{"use strict";Mr="analytics"});function Lr(e){let t=0,n=0;return{track(s){if(!ct(e.policy,e.consent()))return t+=1,!1;for(let o of e.destinations)try{o.send(s)}catch{}return e.destinations.length>0&&(n+=1),e.destinations.length>0},get withheld(){return t},get sent(){return n}}}function On(e){let t={};for(let[n,s]of Object.entries(e))if(s===null)t[n]=null;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")t[n]=s;else{if(s===void 0)continue;try{t[n]=JSON.stringify(s)??null}catch{t[n]=null}}return t}var Vt=ee(()=>{"use strict";Ht()});function Kt(){let e=0,t=!1;return{now:()=>Date.now()+e,sample(n){Number.isFinite(n)&&(e=n-Date.now(),t=!0)},get synchronised(){return t}}}function Ct(e,t){if(!t)return;let n=Date.parse(t);Number.isNaN(n)||e.sample(n)}var Wt=ee(()=>{"use strict"});function Xr(e){return`gamestage:settings:v${Ms}:${e}`}function ei(e){return Et(e,Zr)}function ti(e){let t=e.now??(()=>Date.now()),n=e.readTimeoutMs??300;return{async read(s){let o;try{o=await Promise.race([e.store.read(Xr(s)),new Promise(r=>setTimeout(()=>r(null),n))])}catch{return null}if(!o)return null;try{let r=JSON.parse(o);if(r.format!==Ms||typeof r.savedAt!="number"||t()-r.savedAt>Ac)return null;let i=r.presentation;return!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length===0?null:i}catch{return null}},async write(s,o){if(ei(e.consent())&&Object.keys(o).length!==0)try{await e.store.write(Xr(s),JSON.stringify({format:Ms,savedAt:t(),presentation:o}))}catch{}}}}var Ms,Zr,Ac,Ls=ee(()=>{"use strict";Ht();Ms=1,Zr="functional",Ac=720*60*60*1e3});function Ds(e){return e.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i,"").replace(/\\/+$/,"")}var $s=ee(()=>{"use strict"});var xi={};Vo(xi,{TextDecoder:()=>Ti,TextEncoder:()=>Ci,default:()=>cd});var Ci,Ti,cd,ki=ee(()=>{"use strict";Ci=globalThis.TextEncoder,Ti=globalThis.TextDecoder,cd={TextEncoder:Ci,TextDecoder:Ti}});function Ve(){if(typeof self<"u")return self;if(typeof globalThis<"u")return globalThis;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}function ut(e){return Rn.localStorage.getItem(Vs(e))}function tn(e,t){return Rn.localStorage.setItem(Vs(e),t)}function Ks(e){return Rn.localStorage.removeItem(Vs(e))}function Ws(){return Rn.localStorage.clear()}function nn(){try{return tn(Pn,Pn),ut(Pn),Ks(Pn),!0}catch{return!1}}function Ge(e,t,...n){let s=t[e](...n);return new Ze(e,s)}function Ne(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return"Unknown error"}}function Ys(){return Date.now()/1e3}function Ii(e){return Math.floor(e)+.5}function fd(){return(Ii(Tt)+1-Tt)*1e3}function Ni(){clearTimeout(en);let e=Ys(),t=e-Bs;Tt+=t,Bs=e,en=setTimeout(Ni,fd()),typeof en=="object"&&"unref"in en&&en.unref(),Ai.emit("tick",Tt)}function Qs(e){Bs=Ys(),Tt=Ii(e)}function Ke(){return Math.floor(Tt)}function Mn(e){return He(Ai,"tick",e)}function Ri(e){let s=2166136261,o=new zs().encode(e);for(let r=0;r<o.length;r++)s^=o[r],s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Ln(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ue(e){return e.trim()}function et(e){let t=Oi.get(e);if(t!==void 0)return t;let n=new Hs(e);return n.logLevel=hd,n.logHandler=yd,Oi.set(e,n),n}var z,He,ye,dd,Pn,Rn,Vs,Ze,ld,ud,Zu,gd,eg,Ai,Tt,Bs,en,Pi,qs,pd,zs,B,md,Mi,Hs,Oi,hd,yd,We=ee(()=>{z=class{constructor(){this.listeners=new Map}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>this.off(t,n)}off(t,n){var s;if(n===void 0){this.listeners.delete(t);return}(s=this.listeners.get(t))===null||s===void 0||s.delete(n)}emit(t,...n){var s;(s=this.listeners.get(t))===null||s===void 0||s.forEach(o=>o(...n))}once(t,n){let s=(...o)=>{n(...o),this.off(t,s)};return this.on(t,s)}},He=(e,t,n)=>(e.on(t,n),()=>e.off(t,n));ye=(e,t,n={})=>{var s,o;let r=(s=n.clearOnResolve)!==null&&s!==void 0?s:!1,i=(o=n.clearOnReject)!==null&&o!==void 0?o:!0,a=new Map,d=(...g)=>{let c=t(...g);if(a.has(c))return a.get(c);let u=e(...g);return a.set(c,u),u.then(()=>r&&a.delete(c)).catch(()=>i&&a.delete(c)),u};return d.cache=a,d};dd="monterosa_sdk_",Pn="bait",Rn=Ve(),Vs=e=>`${dd}${e}`;Ze=class e extends Error{constructor(t,n){super(n),this.name="MonterosaError",this.code=t,Object.setPrototypeOf(this,e.prototype)}};ld=typeof global=="object"&&global&&global.Object===Object&&global,ud=typeof self=="object"&&self&&self.Object===Object&&self,Zu=ld||ud||Function("return this")(),gd=Object.prototype,eg=gd.toString;Ai=new z,Tt=0,Bs=0;Qs(Ys());Ni();Pi=e=>{let t=e.reduce((r,i)=>r+i,0),n=e.map((r,i)=>{let a=100*r/t||0;return{idx:i,votes:r,percentage:Math.floor(a),remainder:a%1}}),s=n.reduce((r,{percentage:i})=>r+i,0);s=s||100;let o=100-s;n.sort((r,i)=>r.remainder!==i.remainder?i.remainder-r.remainder:r.idx-i.idx);for(let r=0;r<o;r++)n[r].percentage+=1;return n.sort((r,i)=>r.idx-i.idx),n.map(r=>r.percentage)};pd=typeof process<"u"&&((qs=process.versions)===null||qs===void 0?void 0:qs.node)!=null;pd?zs=(ki(),Ba(xi)).TextEncoder:zs=TextEncoder;(function(e){e[e.Verbose=0]="Verbose",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Silent=5]="Silent"})(B||(B={}));md={[B.Verbose]:"log",[B.Debug]:"log",[B.Info]:"info",[B.Warn]:"warn",[B.Error]:"error"},Mi=(e,t,...n)=>{let s=md[t],o=e.name.replace("@monterosa/sdk-","monterosa/");console[s](`[${o}]`,...n)},Hs=class{constructor(t){this.name=t,this._logLevel=B.Warn,this._logHandler=Mi}get logLevel(){return this._logLevel}set logLevel(t){this._logLevel=t}get logHandler(){return this._logHandler}set logHandler(t){this._logHandler=t}emit(t,...n){this._logLevel>t||this._logHandler(this,t,...n)}log(...t){this.emit(B.Verbose,...t)}debug(...t){this.emit(B.Debug,...t)}info(...t){this.emit(B.Info,...t)}warn(...t){this.emit(B.Warn,...t)}error(...t){this.emit(B.Error,...t)}},Oi=new Map,hd=B.Warn,yd=Mi});function sn(e=Li){let t=Zs.get(e);if(!t)throw new Error(`No Monterosa Sdk "${e}" has been configured.\n You need to call configure() first`);return t}function Di(e,t=Li){let n=Zs.get(t);if(n)return n;let s=new Xs(e,t);return Zs.set(t,s),s}var bd,Li,_d,Js,Xs,Zs,Dn=ee(()=>{We();bd="2.0.0-rc.9";Li="[DEFAULT]",_d=bd;if(typeof document<"u"){let e=document.title||((Js=document.location)===null||Js===void 0?void 0:Js.hostname)||"",t=e?` \\u2014 "${e}"`:"";console.debug(`Monterosa SDK v${_d}${t}`)}Xs=class{constructor(t,n){this._isDestroyed=!1,this._options=Object.assign(Object.assign({},t),{host:Ue(t.host),projectId:Ue(t.projectId)}),this._name=n,this._kits=new Map}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get isDestroyed(){return this._isDestroyed}get kits(){return this._kits}set isDestroyed(t){this._isDestroyed=t}deleteKits(){this.kits.forEach((t,n)=>{this.kits.delete(n),t.delete()})}checkDestroyed(){if(this.isDestroyed)throw new Error(`SDK named ${this.name} destroyed`)}};Zs=new Map});function ji(e){if(e<=0)throw Ge(tt.InvalidRequestTimeoutError,Fi);lo.requestTimeout=e}function xd(e){return e instanceof Object&&Object.prototype.hasOwnProperty.call(e,"bridgeId")}function kd({data:e}){try{if(typeof e!="string")return;let t=JSON.parse(e);uo(t)}catch(t){Gn.error(Ne(t))}}function Ad(e){if(rn.has(e))return rn.get(e);let t=new Fn(e);return rn.set(e,t),t}function Id(){if(typeof window>"u")return null;if(on!==void 0)return on;let t=new URL(window.location.href).searchParams.get(Sd);return t===null?null:(on=new Fn(t),on.send(ft.OnBridgeInitialised,{},xe.Sdk),on)}function qi(e,t={}){rn.forEach(n=>{n.isConnected&&n.send(e,t,xe.Sdk)})}function xt(e){return He(Od.monterosaSdk.emitter,"message",t=>{t.sourceName===xe.Sdk&&t.action!==ft.OnBridgeInitialised&&rn.has(t.bridgeId)&&e(t)})}function go(e,t,n={}){return e.bridge.send(t,n,xe.Sdk)}function jn(e,t,n={},s=lo.requestTimeout){return e.bridge.request(t,n,s,xe.Sdk)}function an(e,t={}){Nd(xe.Sdk,e,t)}function Nd(e,t,n){Ad(t.bridgeId).send(t.action,n,e,t.id)}function Pd(e,t,n){return He(e.bridge,"message",s=>{s.sourceName===t&&n(s)})}function Bi(e,t){return Pd(e,xe.Sdk,t)}function Se(){if($n!==void 0)return $n;let e=Id();return e===null?null:($n=new co(e),$n)}var ft,xe,eo,to,no,so,Un,vd,Sd,wd,Ed,Cd,Td,tt,Fi,lo,Gn,oo,ro,io,ao,$i,Gi,Ui,Fe,uo,gt,Fn,Od,on,rn,co,$n,kt=ee(()=>{We();(function(e){e.OnBridgeInitialised="onBridgeInitialised",e.OnExperienceInitialised="onExperienceInitialised",e.OnReady="onReady",e.OnResize="onIntrinsicSizeChanged",e.OnMoreDataRequested="onMoreDataRequested",e.OnShare="onShare"})(ft||(ft={}));(function(e){e.Sdk="sdk",e.User="user"})(xe||(xe={}));Un=Ve(),vd="micBridge",Sd="micBridgeId",wd=!!(!((no=(to=(eo=Un.webkit)===null||eo===void 0?void 0:eo.messageHandlers)===null||to===void 0?void 0:to.monterosaSdk)===null||no===void 0)&&no.postMessage),Ed=!!(!((so=Un.monterosaSdk)===null||so===void 0)&&so.postMessage),Cd=Un.self!==Un.parent,Td="1.0.0";(function(e){e.InvalidRequestTimeoutError="invalid_request_timeout_error",e.RequestTimeoutError="request_timeout_error"})(tt||(tt={}));Fi={[tt.InvalidRequestTimeoutError]:()=>"Request timeout must be greater than 0",[tt.RequestTimeoutError]:(e,t)=>`Request timeout: action "${e}" did not receive a response within ${t}ms`};lo={requestTimeout:2e4};Gn=et("@monterosa/sdk-bridge-kit");Fe=Ve(),uo=e=>{xd(e)&&Fe.monterosaSdk.emitter.emit("message",e)};(oo=Fe.monterosaSdk)!==null&&oo!==void 0||(Fe.monterosaSdk={initialised:!1,emitter:new z,receiveMessage:uo});(ro=($i=Fe.monterosaSdk).initialised)!==null&&ro!==void 0||($i.initialised=!1);(io=(Gi=Fe.monterosaSdk).emitter)!==null&&io!==void 0||(Gi.emitter=new z);(ao=(Ui=Fe.monterosaSdk).receiveMessage)!==null&&ao!==void 0||(Ui.receiveMessage=uo);Fe.monterosaSdk.initialised||(typeof Fe.addEventListener<"u"&&Fe.addEventListener("message",kd),Fe.monterosaSdk.initialised=!0);gt=Ve(),Fn=class extends z{constructor(t=Ln()){super(),this.id=t,this.recipientInitialised=!1,this.messagesQueue=[],gt.monterosaSdk.emitter.on("message",this.handleMessage.bind(this))}static isMessage(t){return t instanceof Object&&Object.prototype.hasOwnProperty.call(t,"bridgeId")&&Object.prototype.hasOwnProperty.call(t,"action")}get iFrameId(){return`${vd}-${this.id}`}get iFrameSelector(){return`iframe#${this.iFrameId}`}get childIFrame(){return document.querySelector(this.iFrameSelector)}handleMessage(t){let{id:n,bridgeId:s,action:o,respondingTo:r}=t;if(s===this.id){if(Gn.log(`Received a ${r===null?"message":"response"}`,t),o===ft.OnBridgeInitialised){r===null&&this.send(ft.OnBridgeInitialised,{},xe.Sdk,n),this.connect();return}this.emit("message",t)}}createMessage(t,n,s,o=null){return{id:Ln(),respondingTo:o,action:t,sourceName:s,bridgeId:this.id,payload:n,version:Td,timestamp:Date.now()}}get isConnected(){return this.recipientInitialised}connect(){for(this.recipientInitialised=!0;this.messagesQueue.length>0;)this.postMessage(this.messagesQueue.shift())}disconnect(){this.recipientInitialised=!1}postMessage(t){var n,s,o,r;if(!this.recipientInitialised&&t.action!==ft.OnBridgeInitialised){this.messagesQueue.push(t);return}let i=JSON.stringify(t);wd&&((s=(n=gt.webkit)===null||n===void 0?void 0:n.messageHandlers)===null||s===void 0||s.monterosaSdk.postMessage(i)),Ed&&!((o=gt.monterosaSdk)===null||o===void 0)&&o.postMessage&&gt.monterosaSdk.postMessage(i),Cd&&gt.parent.postMessage(i,"*"),this.childIFrame&&((r=this.childIFrame.contentWindow)===null||r===void 0||r.postMessage(i,"*"))}send(t,n={},s=xe.Sdk,o){let r=this.createMessage(t,n,s,o);return Gn.log(`Sending a ${r.respondingTo===null?"message":"response"}`,r),this.postMessage(r),r}async request(t,n={},s=lo.requestTimeout,o=xe.Sdk){let r,i,a=this.createMessage(t,n,o);Gn.log("Sending a request",a);let d=new Promise((c,u)=>{r=setTimeout(()=>{u(Ge(tt.RequestTimeoutError,Fi,t,s))},s)}),g=new Promise(c=>{i=u=>{u.respondingTo===a.id&&c(u)},gt.monterosaSdk.emitter.on("message",i),this.postMessage(a)});return Promise.race([d,g]).finally(()=>{clearTimeout(r),gt.monterosaSdk.emitter.off("message",i)})}};Od=Ve(),rn=new Map;co=class{constructor(t){this.bridge=t}};});function Rd(e){var t;if(Object.values(je).includes(e.action))try{let n={};switch(e.action){case je.Read:n={key:e.payload.key,value:Pe.getItem(e.payload.key)};break;case je.Write:n={key:e.payload.key},Pe.setItem(e.payload.key,e.payload.value);break;case je.Remove:n={key:e.payload.key},Pe.removeItem(e.payload.key);break;case je.Clear:Pe.clear();break}an(e,n)}catch(n){let s=Ne(n),o=(t=e.payload)===null||t===void 0?void 0:t.key,r=o?` for key "${o}"`:"";qn.error(`Unable to handle storage action ${e.action}${r} with error: ${s}`),an(e,{error:s})}}async function po(e,t,n){try{let s=await jn(e,t,n),{value:o,error:r}=s.payload;if(r!==void 0)throw Ge(we.ParentAppError,cn,r);return o}catch(s){if(s instanceof Ze&&s.code===tt.RequestTimeoutError){let o=Ne(s);throw Ge(we.ParentTimeoutError,cn,o)}throw s}}async function Ot(e){let t=Se(),n=null;try{t!==null?n=await po(t,je.Read,{key:e}):n=Pe.getItem(e)}catch(s){let o=Ne(s);throw qn.error(`Unable to read storage item "${e}" with error: ${o}`),Ge(we.ReadError,cn,o)}return n}async function At(e,t){let n=Se();try{n!==null?await po(n,je.Write,{key:e,value:t}):Pe.setItem(e,t)}catch(s){let o=Ne(s);throw qn.error(`Unable to write storage item "${e}" with error: ${o}`),Ge(we.WriteError,cn,o)}}async function Bn(e){let t=Se();try{t!==null?await po(t,je.Remove,{key:e}):Pe.removeItem(e)}catch(n){let s=Ne(n);throw qn.error(`Unable to remove storage item "${e}" with error: ${s}`),Ge(we.RemoveError,cn,s)}}var je,we,cn,fo,qn,Pe,zn=ee(()=>{We();kt();(function(e){e.Read="storageRead",e.Write="storageWrite",e.Remove="storageRemove",e.Clear="storageClear"})(je||(je={}));(function(e){e.ParentAppError="parent_app_error",e.ParentTimeoutError="parent_timeout_error",e.ReadError="read_error",e.WriteError="write_error",e.RemoveError="remove_error",e.ClearError="clear_error"})(we||(we={}));cn={[we.ParentAppError]:e=>`Parent application error: ${e}`,[we.ParentTimeoutError]:e=>`Parent application timeout: ${e}. Please check if the storage-kit is imported on the parent page.`,[we.ReadError]:e=>`Storage read error: ${e}`,[we.WriteError]:e=>`Storage write error: ${e}`,[we.RemoveError]:e=>`Storage remove error: ${e}`,[we.ClearError]:e=>`Storage clear error: ${e}`};fo=class{constructor(){this.memoryStore={},this.accessible=nn(),this._persistent=!0}set persistent(t){if(this._persistent===t)return;let s=t===!0&&this.accessible,o=t===!1&&this.accessible;if(s)for(let[r,i]of Object.entries(this.memoryStore))tn(r,i);o&&Ws(),this._persistent=t}get persistent(){return this._persistent}getItem(t){return this.persistent&&this.accessible?ut(t):Object.prototype.hasOwnProperty.call(this.memoryStore,t)?this.memoryStore[t]:null}setItem(t,n){this.persistent&&this.accessible&&tn(t,n),this.memoryStore[t]=n}removeItem(t){this.persistent&&this.accessible&&Ks(t),delete this.memoryStore[t]}clear(){this.persistent&&this.accessible&&Ws(),this.memoryStore={}}};qn=et("@monterosa/sdk-storage-kit");Pe=new fo;xt(Rd)});function E(e,...t){var n;switch((n=jd[e])!==null&&n!==void 0?n:B.Verbose){case B.Info:ln.info(...t);break;case B.Debug:ln.debug(...t);break;default:ln.log(...t);break}}function dn(e,t){ln.error(`EnMasse: ${e}: ${Ne(t)}`)}function qd(e){ln.warn(`EnMasse: ${e}`)}var Md,Ld,Vi,So,Ki,Wi,Vn,wo,Yi,Eo,Dd,$d,Co,Gd,Qi,Ud,zi,Hi,Fd,Re,Q,ce,de,pt,Ji,Me,It,Xi,ln,jd,mo,Kn,Zi,ea,Bd,ho,J,Hn,le,me,zd,yo,Hd,bo,Vd,Kd,Wd,_o,vo,Yd,Qd,Pt,Rt,Nt,L,ta=ee(()=>{We();zn();kt();Md="enmasse_override_methods",Ld="enmasse_config",Vi="auth",So="authr",Ki="authok",Wi="ping",Vn="sub",wo="unsub",Yi="eoc",Eo="login",Dd="login_ok",$d="login_fail",Co="logout",Gd="counter",Qi=e=>{if(nn()){let n=ut(e);if(n!==null)return n}if(typeof window>"u")return null;let{searchParams:t}=new URL(window.location.href);return t.has(e)?t.get(e):!1},Ud=()=>{let e=Qi(Md);if(typeof e=="string")return e.split(",")},zi=Ud(),Hi=Qi(Ld),Fd="2.0.0-rc.9";Re=1,Q=2,ce=4,de=8,pt=16,Ji=32,Me=64,It=128,Xi=256,ln=et("@monterosa/sdk-enmasse-kit"),jd={[Re]:B.Info,[Q]:B.Debug,[ce]:B.Debug,[de]:B.Debug,[Me]:B.Verbose,[It]:B.Verbose,[pt]:B.Verbose,[Ji]:B.Verbose,[Xi]:B.Verbose};mo=class{constructor(t={}){this.queue=[],this.stashed=[],this.running=!1,this.runner=typeof t.runner=="function"?t.runner:null,this._subscriptions=[]}push(t,n=!1){E(pt,"Queue::push",t,n);let{klass:s,channel:o}=t;if(!n)switch(s){case Eo:case Co:case So:break;case Vn:if(this._subscriptions.indexOf(o)===-1)this._subscriptions.push(o);else return;break;case wo:{let r=this._subscriptions.indexOf(o);if(r!==-1)this._subscriptions.splice(r,1);else return;break}default:if(this._subscriptions.indexOf(o)===-1)return;break}this.queue.push(t)}get subscriptions(){return this._subscriptions}run(){E(pt,"Queue::run",`running=${this.running}, head=${this.queue[0]}`),!(this.runner===null||this.running||!this.queue[0])&&(this.running=!0,this.runner(this.queue.shift()))}success(){E(pt,"Queue::success"),this.running=!1,this.run()}failure(){E(pt,"Queue::failure"),this.running=!1}stash(){E(pt,"Queue::stash");let t;for(;(t=this.queue.shift())!==void 0;)this.stashed.push(t)}unstash(){E(pt,"Queue::unstash");let t;for(;(t=this.stashed.shift())!==void 0;)this.queue.push(t)}},Kn=()=>Date.now()/1e3,Zi=Kn(),ea=Kn(),Bd=e=>{E(Ji,"Time::setTime",e),Zi=e,ea=Kn()},ho=()=>{let e=Kn()-ea;return Math.round(Zi+e)},J=class e extends z{constructor(){super(...arguments),this.state=e.STATE_DISCONNECTED,this.trigger=this.emit,this.bind=this.on,this.unbind=this.off}connect(){}disconnect(){}init(){}send(t,n,s){}};J.ON_READY="ready";J.ON_MESSAGE="message";J.ON_CONNECTED="connected";J.ON_CONNECT_FAILED="connect_failed";J.ON_CONNECT_LOST="connect_lost";J.ON_DISCONNECTED="disconnected";J.STATE_CONNECTED="connected";J.STATE_CONNECTING="connecting";J.STATE_DISCONNECTED="disconnected";J.STATE_DISCONNECTING="disconnecting";Hn=[0,3,5,10,20,30,45,60],le=class e extends z{constructor(t){super(),this._handleTransportMessage=s=>{E(Q,"ConnectionManager::handleTransportMessage",s);let o=s.split("\\0");for(let r=0;r<o.length;r+=1)o[r].length>0&&(this._inactivityTimeout.reset(),E(Q,"ConnectionManager::handleTransportMessage","send upstream m:",o[r]),this.emit(e.ON_MESSAGE,o[r]))},this._handleTransportConnected=()=>{E(Q,"ConnectionManager::handleTransportConnected"),this._setStateToConnected()},this._handleTransportConnectFailed=()=>{E(Q,"ConnectionManager::handleTransportConnectFailed"),this._disconnectingOnConnectFailed()},this._handleTransportConnectLost=()=>{E(Q,"ConnectionManager::handleTransportConnectLost"),this._disconnectingOnConnectLost()},this._handleTransportDisconnected=()=>{switch(E(Q,"ConnectionManager::handleTransportDisconnected"),this._state){case e.STATE_CONNECTED:this._disconnectedOnConnectLost();break;case e.STATE_CONNECTING:this._disconnectedOnConnectFailed();break;case e.STATE_DISCONNECTING:this._setStateToDisconnected();break}},this._handleVisibilityChange=()=>{switch(E(Q,"ConnectionManager::handleVisibilityChange()",document.visibilityState),document.visibilityState){case"visible":if(this._backgroundedAt===null||this._state!==e.STATE_CONNECTED)return;Date.now()-this._backgroundedAt>this._config.background_timeout*1e3&&(E(Q,"ConnectionManager::handleVisibilityChange()","disconnecting due to background timeout"),this._disconnect()),this._backgroundedAt=null;break;case"hidden":this._backgroundedAt=Date.now();break}},this._handleNetworkStatus=()=>{!navigator.onLine&&this._state===e.STATE_CONNECTED&&(E(Q,"ConnectionManager::handleNetworkStatus()","disconnecting due to network loss"),this._disconnect())},this._transportManager=t,this._state=e.STATE_DISCONNECTED,this._transport=null,this._attempt=1,this._backgroundedAt=null;let n=this;this._inactivityTimeout={start(){E(Me,"ConnectionManager::inactivityTimeout::start");let s=ho();this.interval=setInterval(()=>{ho()-s>=n._config.inactivity_timeout&&this.resolve()},1e3)},stop(){E(Me,"ConnectionManager::inactivityTimeout::stop"),clearInterval(this.interval)},reset(){E(Me,"ConnectionManager::inactivityTimeout::reset"),this.stop(),this.start()},resolve(){E(Me,"ConnectionManager::inactivityTimeout::resolve"),n._disconnectingOnConnectLost()}},this._connectTimeout={start(){E(Me,"ConnectionManager::connectTimeout::start"),this.timeout=setTimeout(()=>{this.resolve()},n._config.connect_timeout*1e3)},stop(){E(Me,"ConnectionManager::connectTimeout::stop"),clearTimeout(this.timeout)},resolve(){E(Me,"ConnectionManager::connectTimeout::resolve"),n._disconnectingOnConnectFailed()}},this._connectDelay={active:!1,start(s){E(Me,"ConnectionManager::connectDelay::start"),this.active=!0,this.timeout=setTimeout(()=>{this.resolve()},s*1e3)},stop(){E(Me,"ConnectionManager::connectDelay::stop"),this.active=!1,clearTimeout(this.timeout)},resolve(){E(Me,"ConnectionManager::connectDelay::resolve"),this.stop(),n._connect()}}}_initTransport(t){E(Q,"ConnectionManager::initTransport"),this._transport=t,t.bind(J.ON_MESSAGE,this._handleTransportMessage),t.bind(J.ON_CONNECTED,this._handleTransportConnected),t.bind(J.ON_CONNECT_FAILED,this._handleTransportConnectFailed),t.bind(J.ON_CONNECT_LOST,this._handleTransportConnectLost),t.bind(J.ON_DISCONNECTED,this._handleTransportDisconnected)}_teardownTransport(){E(Q,"ConnectionManager::teardownTransport"),this._transport!==null&&(this._transport.unbind(J.ON_MESSAGE,this._handleTransportMessage),this._transport.unbind(J.ON_CONNECTED,this._handleTransportConnected),this._transport.unbind(J.ON_CONNECT_FAILED,this._handleTransportConnectFailed),this._transport.unbind(J.ON_CONNECT_LOST,this._handleTransportConnectLost),this._transport.unbind(J.ON_DISCONNECTED,this._handleTransportDisconnected),this._transport=null)}_disconnectingOnConnectFailed(){E(Q,"ConnectionManager::disconnectingOnConnectFailed()"),this._disconnect()}_disconnectingOnConnectLost(){E(Q,"ConnectionManager::disconnectingOnConnectLost()"),this._disconnect()}_disconnectedOnConnectLost(){E(Q,"ConnectionManager::disconnectedOnConnectLost()"),this._teardownTransport(),this._setStateToConnecting()}_disconnectedOnConnectFailed(){E(Q,"ConnectionManager::disconnectedOnConnectFailed()"),this._transportManager.addUnsuccessful(this._transport),this._teardownTransport(),this._transportManager.next()===!1?this._setStateToConnecting():this._connect()}_setStateToConnecting(){E(Q,"ConnectionManager::setStateToConnecting()");let t;this._attempt>=Hn.length?t=Hn[Hn.length-1]:t=Hn[this._attempt-1],this._state=e.STATE_CONNECTING,this.emit(e.ON_STATE,this._state,this._attempt,t),this._transportManager.reset(),this._attempt+=1,this._connectDelay.start(t)}_setStateToConnected(){E(Q,"ConnectionManager::setStateToConnected()"),this._attempt=1,this._transportManager.reset(),this._inactivityTimeout.reset(),this._connectTimeout.stop(),this._connectDelay.stop(),this._state=e.STATE_CONNECTED,this.emit(e.ON_STATE,this._state)}_setStateToDisconnecting(){E(Q,"ConnectionManager::setStateToDisconnecting()"),this._state=e.STATE_DISCONNECTING,this.emit(e.ON_STATE,this._state),this._disconnect()}_setStateToDisconnected(){E(Q,"ConnectionManager::setStateToDisconnected()"),this._attempt=1,this._teardownTransport(),this._transportManager.reset(),this._state=e.STATE_DISCONNECTED,this.emit(e.ON_STATE,this._state)}_connect(){var t;this._state===e.STATE_CONNECTING&&(this._connectTimeout.start(),this._initTransport(this._transportManager.current),(t=this._transport)===null||t===void 0||t.connect())}_disconnect(){this._inactivityTimeout.stop(),this._connectTimeout.stop(),this._connectDelay.stop(),this._transport?this._transport.disconnect():this._setStateToDisconnected()}connect(){E(Q,"ConnectionManager::connect()"),this._connectDelay.active?this._connectDelay.resolve():this._state===e.STATE_DISCONNECTED&&this._setStateToConnecting(),window.addEventListener("online",this._handleNetworkStatus),window.addEventListener("offline",this._handleNetworkStatus),window.addEventListener("visibilitychange",this._handleVisibilityChange)}disconnect(){E(Q,"ConnectionManager::disconnect()"),this._setStateToDisconnecting(),window.removeEventListener("online",this._handleNetworkStatus),window.removeEventListener("offline",this._handleNetworkStatus),window.removeEventListener("visibilitychange",this._handleVisibilityChange)}send(t,n=()=>{},s=()=>{}){var o;E(Q,"ConnectionManager::send",t),(o=this._transport)===null||o===void 0||o.send(t,n,s)}get connectAttempt(){return this._attempt}init(t){E(Q,"ConnectionManager::init()",t),this._config=t}};le.STATE_DISCONNECTED="state_disconnected";le.STATE_DISCONNECTING="state_disconnecting";le.STATE_CONNECTING="state_connecting";le.STATE_CONNECTED="state_connected";le.ON_MESSAGE="message";le.ON_STATE="state";me=class e extends z{constructor(){super(...arguments),this.connected=!1,this.trigger=this.emit,this.bind=this.on,this.unbind=this.off}connect(t,n,s){}disconnect(){}send(...t){}init(){this.trigger(e.ON_READY)}};me.ON_READY="ready";me.ON_MESSAGE="message";me.ON_CONNECTED="connected";me.ON_DISCONNECTED="disconnected";zd=Ve(),yo=class e extends me{constructor(t={}){super(),this.config=t,this.requests={},this.requestIdx=0}_request(t,n=()=>{},s=()=>{},o=()=>{}){this.requestIdx+=1,E(It,`XHRDriver::request url=${t}, idx=${this.requestIdx}`);let r=new XMLHttpRequest,i="POST";if(typeof XDomainRequest<"u")r=new XDomainRequest,r.open(i,t);else if("withCredentials"in r)r.open(i,t,!0),r.setRequestHeader("Content-type","application/x-www-form-urlencoded");else return null;return r._idx=this.requestIdx,r.onload=()=>{E(It,`XHRDriver::request::onload idx=${r._idx}, response=${r.responseText}`),r.responseText.length>0?n(this._parseResponse(r.responseText)):s(r.responseText)},r.onerror=()=>{E(It,`XHRDriver::request::onerror idx=${r._idx}, response=${r.responseText}`),s(r.responseText)},r._onabort=()=>{E(It,`XHRDriver::request::onabort idx=${r._idx}`),o()},r}_parseResponse(t){let n={},s=t.split("&");for(let o=0,r=s.length;o<r;o++){let[i,a]=s[o].split("="),d=decodeURIComponent((a??"").replace("\\0",""));i in n?(n[i].constructor!==Array&&(n[i]=[n[i]]),n[i].push(d)):n[i]=d}return n}_removeRequest(t){E(It,"XHRDriver::removeRequest",t),Object.prototype.hasOwnProperty.call(this.requests,t)&&delete this.requests[t]}connect(){if(E(de,"XHRDriver::connect"),this.connected){E(de,"XHRDriver::connect already been connected!");return}this.connected=!0,this.trigger(e.ON_CONNECTED)}disconnect(){if(E(de,"XHRDriver::disconnect"),this.connected){for(let t in this.requests)Object.prototype.hasOwnProperty.call(this.requests,t)&&typeof this.requests[t].abort=="function"&&(this.requests[t].abort(),typeof this.requests[t]._onabort=="function"&&this.requests[t]._onabort(),this._removeRequest(t));this.connected=!1}this.trigger(e.ON_DISCONNECTED)}send(t,n,s=()=>{},o=()=>{}){E(de,"XHRDriver::send",n);let r,i=1,a=()=>{r=this._request(t,d,g,c),this.requests[r._idx]=r,setTimeout(()=>{r.send(n)},0)},d=u=>{E(de,"XHRDriver::success",n),this._removeRequest(r._idx),s(u)},g=u=>{var y,b;E(de,"XHRDriver::failure, retry: ",i),this._removeRequest(r._idx),i<=((y=this.config.request_retries)!==null&&y!==void 0?y:0)?setTimeout(()=>{a(),i++},((b=this.config.request_retry_delay)!==null&&b!==void 0?b:0)*1e3):o(u)},c=()=>{E(de,"XHRDriver::abort",n),this._removeRequest(r._idx),o()};a()}static hasSupport(){return"XDomainRequest"in zd||"withCredentials"in new XMLHttpRequest}},Hd=Ve(),bo=class e extends me{constructor(){super(...arguments),this.websocket=null,this.closeTimeout=void 0}_onMessage(t){E(de,"WebSocketDriver::onMessage",t.data),this.trigger(e.ON_MESSAGE,t.data)}_onOpen(){E(de,"WebSocketDriver::onOpen"),this.connected=!0,this.trigger(e.ON_CONNECTED)}_onClose(){E(de,"WebSocketDriver::onClose"),this._disconnect()}_onError(){E(de,"WebSocketDriver::onError")}_disconnect(){E(de,"WebSocketDriver::disconnect"),this.connected=!1,this.websocket!==null&&(this.websocket.onmessage=()=>{},this.websocket.onopen=()=>{},this.websocket.onclose=()=>{},this.websocket.onerror=()=>{},this.websocket=null),clearTimeout(this.closeTimeout),this.trigger(e.ON_DISCONNECTED)}connect(t,n,s){if(this.connected)return;E(de,"WebSocketDriver::connect",t,n);let o=`${s?"wss":"ws"}://${t}:${n}/ws`;this.websocket=new WebSocket(o),this.websocket.onmessage=this._onMessage.bind(this),this.websocket.onopen=this._onOpen.bind(this),this.websocket.onclose=this._onClose.bind(this),this.websocket.onerror=this._onError.bind(this)}disconnect(){var t;E(de,"WebSocketDriver::disconnect"),this.connected?((t=this.websocket)===null||t===void 0||t.close(),this.closeTimeout=setTimeout(this._disconnect.bind(this),750)):this._disconnect()}send(t,n=()=>{}){var s;E(de,"WebSocketDriver::send",t),(s=this.websocket)===null||s===void 0||s.send(t),n()}static hasSupport(){return"WebSocket"in Hd}},Vd="connect",Kd="pass",Wd="poll",_o=class e extends J{constructor(t={}){E(ce,"ProxyTransport::constructor",t),super(),this.driver=t.driver,this.host=t.host,this.port=t.port,this.secure=t.secure||!1,this.proxyIp=null,this.childId=null,this.clientId=null,this.sessionId=null,this.driver.bind(me.ON_READY,this._handleDriverReady.bind(this)),this.driver.bind(me.ON_CONNECTED,this._handleDriverConnected.bind(this)),this.driver.bind(me.ON_DISCONNECTED,this._handleDriverDisconnected.bind(this))}_url(){let t=this.childId===null?"":`${this.childId}/`;return`${this.secure?"https":"http"}://${this.proxyIp?this.proxyIp:this.host}:${this.port}/${t}?_r=${new Date().getTime()}`}_request(t="",n=()=>{},s=()=>{}){let o=i=>{i.sscp.constructor===String&&(i.sscp=[i.sscp]);for(let a=0,d=i.sscp.length;a<d;a++)i.sscp[a]!==""&&this.trigger(e.ON_MESSAGE,i.sscp[a]);n(i)},r=()=>{switch(this.state){case e.STATE_CONNECTED:case e.STATE_CONNECTING:this.state=e.STATE_DISCONNECTING,this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.state=e.STATE_DISCONNECTED,this.trigger(e.ON_DISCONNECTED);break}s()};this.driver.send(this._url(),t,o,r)}_poll(){let t=`command=${Wd}&clientid=${this.clientId}&sid=${this.sessionId}`;this._request(t,this._poll.bind(this))}_connect(){let t=o=>{o&&(this.proxyIp=o.proxy,this.clientId=Number.parseInt(o.clientid,10),this.childId=Number.parseInt(o.childid,10),this.sessionId=o.sid,this.state=e.STATE_CONNECTED,this.trigger(e.ON_CONNECTED),this._poll())},n=()=>{this.state=e.STATE_DISCONNECTED,this.trigger(e.ON_CONNECT_FAILED)},s=`command=${Vd}`;this._request(s,t,n)}_handleDriverReady(){this.trigger(e.ON_READY)}_handleDriverConnected(){this._connect()}_handleDriverDisconnected(){E(ce,"ProxyTransport::handleDriverDisconnected");let{state:t}=this;switch(this.state=e.STATE_DISCONNECTED,t){case e.STATE_CONNECTED:this.trigger(e.ON_CONNECT_LOST);break;case e.STATE_CONNECTING:this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.trigger(e.ON_DISCONNECTED);break}}send(t,n=()=>{},s=()=>{}){E(ce,"ProxyTransport::send",t);let o=`command=${Kd}&clientid=${this.clientId}&sscp=${t}&sid=${this.sessionId}`;this._request(o,n,s)}connect(){E(ce,"ProxyTransport::connect",this.host,this.port),this.state=e.STATE_CONNECTING,this.driver.connect()}disconnect(){E(ce,"ProxyTransport::disconnect"),this.proxyIp=null,this.childId=null,this.sessionId=null,this.state=e.STATE_DISCONNECTING,this.driver.disconnect()}init(){E(ce,"ProxyTransport::init"),this.driver.init()}},vo=class e extends J{constructor(t={}){E(ce,"SocketTransport::constructor",t),super(),this.driver=t.driver,this.host=t.host,this.port=t.port,this.secure=t.secure||!1,this.driver.bind(me.ON_READY,this._handleDriverReady.bind(this)),this.driver.bind(me.ON_MESSAGE,this._handleDriverMessage.bind(this)),this.driver.bind(me.ON_CONNECTED,this._handleDriverConnected.bind(this)),this.driver.bind(me.ON_DISCONNECTED,this._handleDriverDisconnected.bind(this))}_handleDriverReady(){E(ce,"SocketTransport::_handleDriverReady"),this.trigger(e.ON_READY)}_handleDriverMessage(t){E(ce,"SocketTransport::handleDriverMessage"),this.trigger(e.ON_MESSAGE,t)}_handleDriverConnected(){E(ce,"SocketTransport::handleDriverConnected"),this.state=e.STATE_CONNECTED,this.trigger(e.ON_CONNECTED)}_handleDriverDisconnected(){E(ce,"SocketTransport::handleDriverDisconnected");let{state:t}=this;switch(this.state=e.STATE_DISCONNECTED,t){case e.STATE_CONNECTED:this.trigger(e.ON_CONNECT_LOST);break;case e.STATE_CONNECTING:this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.trigger(e.ON_DISCONNECTED);break}}send(t,n=()=>{},s=()=>{}){E(ce,"SocketTransport::send",t),this.driver.send(t,n,s)}connect(){E(ce,"SocketTransport::connect",this.host,this.port),this.state=e.STATE_CONNECTING,this.driver.connect(this.host,this.port,this.secure)}disconnect(){E(ce,"SocketTransport::disconnect"),this.state=e.STATE_DISCONNECTING,this.driver.disconnect()}init(){E(ce,"SocketTransport::init"),this.driver.init()}},Yd="proxy",Qd="websocket",Pt=class e extends z{constructor(){super(),this.idx=0,this.methods={},this.transports={},this.loaded=0,this.sequence=[],this.allowed=[],this.secure=!0,this.unsuccessful=[],typeof window<"u"&&(this.secure=window.location.protocol.startsWith("https"))}_instantiate(){E(Q,"TransportManager::instantiate"),this.allowed.forEach(t=>{let n=this._getMethodConfig(t),s=n.hosts[Math.floor(Math.random()*n.hosts.length)],o=this.methods[t].transport,r=this.methods[t].driver,i=new o({driver:new r(n.driver||{}),host:s,port:this.secure?n.secure_port:n.port,secure:this.secure});this.transports[t]=i,i.bind(J.ON_READY,this._handleTransportReady.bind(this))});for(let t in this.transports)Object.prototype.hasOwnProperty.call(this.transports,t)&&this.transports[t].init()}_getMethodConfig(t){return this.config.methods.find(n=>n.type===t)}_handleTransportReady(){this.loaded+=1,this.loaded===this.allowed.length&&this.emit(e.ON_READY)}get current(){return this.transports[this.allowed[this.idx]]}next(){return this.idx+=1,this.idx>=this.allowed.length?!1:this.current}reset(){this.allowed=[],this.unsuccessful=[];for(let t=0,n=this.sequence.length;t<n;t+=1){let s=this.sequence[(t+this.idx)%n];this.methods[s].driver.hasSupport()&&this.allowed.push(s)}this.idx=0}addUnsuccessful(t){for(let n in this.transports)Object.prototype.hasOwnProperty.call(this.transports,n)&&this.transports[n]===t&&this.unsuccessful.push(n)}init(t={}){this.config=t,this.idx=0,this.loaded=0,this.sequence=[],this.secure=t.forceSecure===!0?!0:this.secure,this.methods[Yd]={driver:yo,transport:_o},this.methods[Qd]={driver:bo,transport:vo},zi?this.sequence=zi:this.config.methods.forEach(s=>this.sequence.push(s.type));let n=s=>Object.prototype.hasOwnProperty.call(this.methods,s);this.sequence=this.sequence.filter(n),this.reset(),this._instantiate()}};Pt.ON_READY="ready";Rt=class e extends z{addCounter(t,n,s,o,r=null,i=null,a=null){if(E(Xi,"Demographics::addCounter",t,n,s,o,r,i,a),!t||!n||!Array.isArray(s)||!s.length||s.length%2!==0||o!==Number.parseInt(String(o),10))return;let d=s.filter((c,u)=>(u+1)%2).join(":"),g=s.filter((c,u)=>u%2).join(":");this.emit(e.ON_ADD_COUNTER,t,[n,i,a,r,d,g,o])}};Rt.ON_ADD_COUNTER="add-counter";Nt="enmasse_session_id",L=class e extends z{constructor({transportManager:t=new Pt,demographics:n=new Rt,connectionManager:s}={}){super(),this._runner=o=>{let r=()=>{this._queue.success()},i=()=>{this._queue.failure()};this._connectionManager.send(this._stringifySSCP(o),r,i)},this._handleTransportManagerReady=()=>{E(Re,"Enmasse::handleTransportManagerReady"),this.emit(e.ON_READY)},this._handleConnectionManagerState=(o,r,i)=>{switch(E(Re,"Enmasse::handleConnectionManagerState",o,r,i),o){case le.STATE_DISCONNECTED:this._setStateToDisconnected();break;case le.STATE_CONNECTING:this._setStateToConnecting(r,i);break;case le.STATE_CONNECTED:break}},this._handleConnectionManagerMessage=async o=>{E(Re,"Enmasse::handleConnectionManagerMessage",o);let r=this._parseSSCP(o);switch(r.klass){case Vi:{let i=r.sent_at,a=[`enmassejs-${e.VERSION}`,navigator.userAgent].concat(this._info);this._sysChannel=r.channel,a.forEach((d,g)=>{a[g]=encodeURIComponent(d)}),this._sessionId===null&&([this._sessionId]=r.body,await this._storeSession(this._sessionId)),Bd(i),this._queue.stash(),this._queue.push({channel:this._sysChannel,klass:So,body:[this._sessionId,e.PROTOCOL_VERSION,a.join(",")]},!0),this._queue.run();break}case Ki:{let{subscriptions:i}=this._queue;i.forEach(a=>{this._queue.push({channel:a,klass:Vn,body:[]},!0)}),this._queue.unstash(),this._queue.run(),this._setStateToConnected();break}case Dd:this._resolveLogin();break;case $d:this._rejectLogin();break;case Wi:break;case Yi:this.emit(e.ON_EOC,r.channel);break;default:this.emit(e.ON_MESSAGE,r);break}},this._handleDemographicsCounter=(o,r)=>{this.send(o,"avgcounter",r)},this._transportManager=t,this._demographics=n,this._connectionManager=s||new le(t),this.Demographics=this._demographics,this._configFile=null,this._info=[],this._sessionId=null,this._state=e.STATE_DISCONNECTED,this._sysChannel=null,this._forceSecure=!1,this._loginContext={inProgress:!1,success:()=>{},failure:()=>{}},this._initPromise=null}async _storeSession(t){try{await At(Nt,t)}catch(n){dn("Failed to persist session to shared storage",n)}}async _restoreSession(){let t=null;try{t=await Ot(Nt)}catch(n){dn("Failed to read session from shared storage",n)}if(t!==null)return t;if(Se()===null)return null;try{t=ut(Nt)}catch(n){dn("Failed to read local session during migration",n)}if(t===null)return null;try{await At(Nt,t)}catch(n){dn("Failed to persist session to shared storage during migration",n)}return t}async resetSession(){this._sessionId=null;try{await Bn(Nt)}catch(t){dn("Failed to remove session from shared storage",t)}}_validateSession(t){return/^[a-f\\d]{8}\\-[a-f\\d]{4}\\-[a-f\\d]{4}-[a-f\\d]{4}\\-[a-f\\d]{12}$/i.test(t)}_finaliseLogin(t){this._loginContext.inProgress!==!1&&(this._loginContext={inProgress:!1,success:()=>{},failure:()=>{}},typeof t=="function"&&t())}_resolveLogin(){this._finaliseLogin(this._loginContext.success)}_rejectLogin(){this._finaliseLogin(this._loginContext.failure)}_setStateToDisconnected(){E(Re,"Enmasse::setStateToDisconnected()"),this._state=e.STATE_DISCONNECTED,this._sysChannel=null,this._rejectLogin(),this.emit(e.ON_STATE,this._state)}_setStateToConnected(){E(Re,"Enmasse::setStateToConnected()");let t=ho();this._state=e.STATE_CONNECTED,this.emit(e.ON_STATE,this._state,t)}_setStateToConnecting(t,n){E(Re,"Enmasse::setStateToConnecting()"),this._state=e.STATE_CONNECTING,this._rejectLogin(),this.emit(e.ON_STATE,this._state,t,n)}_parseSSCP(t){let n={channel:"",klass:"",sent_at:0,body:[]},s=t.indexOf("/");if(s!==-1){let o=t.indexOf("/",s+1);if(o!==-1){n.channel=t.substr(0,s),n.klass=t.substr(s+1,o-s-1);let r=t.indexOf("/",o+1);if(r!==-1){n.sent_at=Number.parseInt(t.substr(o+1,r-o-1),10);let i=t.substr(r+1);if(i!==""){let a=i.split("|");for(let d=0,g=a.length;d<g;d+=1)n.body[d]=decodeURIComponent(a[d])}}}}return n}_stringifySSCP(t){var n;return[t.channel,t.klass,Math.floor(Date.now()/1e3),((n=t.body)!==null&&n!==void 0?n:[]).join("|")].join("/")}connect(){E(Re,"Enmasse::connect"),this._connectionManager.connect()}disconnect(){E(Re,"Enmasse:disconnect"),this._connectionManager.disconnect()}teardown(){E(Re,"Enmasse::teardown"),this.disconnect(),this._transportManager.off(Pt.ON_READY,this._handleTransportManagerReady),this._connectionManager.off(le.ON_STATE,this._handleConnectionManagerState),this._connectionManager.off(le.ON_MESSAGE,this._handleConnectionManagerMessage),this._demographics.off(Rt.ON_ADD_COUNTER,this._handleDemographicsCounter)}send(t,n,s=[]){E(Re,"Enmasse::send",t,n,s),this._queue.push({channel:t,klass:n,body:s}),this._state===e.STATE_CONNECTED&&this._queue.run()}get sessionId(){return this._sessionId}get state(){return this._state}subscribe(t){this.send(t,Vn)}unsubscribe(t){this.send(t,wo)}login(t,n,s,o,r){let i=this._sysChannel;if(i!==null){if(this._loginContext.inProgress){qd("Login is already in progress");return}this._loginContext={inProgress:!0,success:o,failure:r},this.send(i,Eo,[t,n,s])}}logout(){let t=this._sysChannel;t!==null&&(this._loginContext.inProgress&&this._rejectLogin(),this.send(t,Co))}init(t={}){return this._initPromise||(this._initPromise=this._init(t)),this._initPromise}async _init(t={}){if(this._configFile=Hi||t.config||null,this._info=t.info||[],this._sessionId=await this._restoreSession(),typeof t.forceSecure=="boolean"&&(this._forceSecure=t.forceSecure),this._configFile===null)throw new Error("EnMasse config file is not set");let n=this._configFile;this._sessionId!==null&&!this._validateSession(this._sessionId)&&await this.resetSession(),this._queue=new mo({runner:this._runner}),this._transportManager.on(Pt.ON_READY,this._handleTransportManagerReady),this._connectionManager.on(le.ON_STATE,this._handleConnectionManagerState),this._connectionManager.on(le.ON_MESSAGE,this._handleConnectionManagerMessage),this._demographics.on(Rt.ON_ADD_COUNTER,this._handleDemographicsCounter);try{let s=await fetch(n),{status:o,statusText:r}=s,i;try{i=await s.json()}catch{this.emit(e.ON_ERROR,`Invalid JSON from config ${n}`);return}let a=o>=200&&o<=300||o===0&&!!r||o==="";i.forceSecure=this._forceSecure,i.background_timeout===void 0&&(i.background_timeout=0),a?(this._connectionManager.init(i),this._transportManager.init(i)):this.emit(e.ON_ERROR,`Failed to load config ${n}`)}catch(s){this.emit(e.ON_ERROR,`Error loading config: ${s.message}`)}}};L.VERSION=Fd;L.PROTOCOL_VERSION="8";L.SSCP_KLASS_AUTH=Vi;L.SSCP_KLASS_AUTHR=So;L.SSCP_KLASS_AUTHOK=Ki;L.SSCP_KLASS_PING=Wi;L.SSCP_KLASS_SUB=Vn;L.SSCP_KLASS_UNSUB=wo;L.SSCP_KLASS_EOC=Yi;L.SSCP_KLASS_LOGIN=Eo;L.SSCP_KLASS_LOGOUT=Co;L.SSCP_KLASS_COUNTER=Gd;L.ON_STATE="on_state";L.ON_MESSAGE="on_message";L.ON_EOC="on_eoc";L.ON_READY="on_ready";L.ON_ERROR="on_error";L.STATE_DISCONNECTED="disconnected";L.STATE_CONNECTED="connected";L.STATE_CONNECTING="connecting";L.PARAM_SESSION_ID=Nt});function xo(e,t,n){let s=(o,...r)=>{o===t&&n(...r)};return e.on("state",s),()=>e.off("state",s)}function Wn(e){return e===void 0&&(e=sn().options.host),Jd(Ue(e))}function un(e,t){return xo(e,ie.Connected,t)}function sa(e,t){return xo(e,ie.Connecting,t)}function oa(e,t){return xo(e,ie.Disconnected,t)}function ra(e,t){let n=s=>{t(s)};return e.on("message",n),()=>e.off("message",n)}function Yn(e){return e.connect()}function Qn(e){e.disconnect()}function Mt(e,t){return Xd(e,Ue(t))}function Lt(e,t){e.unsubscribe(Ue(t))}function ia(e,t,n,s){e.send(Ue(t),n,s)}var Ye,ie,na,To,Jd,Xd,ko=ee(()=>{Dn();We();ta();(function(e){e.NotInitialised="not_initialised",e.Initialised="initialised",e.Initialising="initialising"})(Ye||(Ye={}));(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected"})(ie||(ie={}));(function(e){e.Authenticate="auth",e.AuthenticateResponse="authr",e.AuthenticateSuccess="authok",e.Ping="ping",e.Subscribe="sub",e.Unsububscribe="unsub",e.EndOfCache="eoc",e.Login="login",e.LoginSuccess="login_ok",e.LoginFail="login_fail",e.Counter="counter",e.Vote="v"})(na||(na={}));To=class extends z{constructor(t=new L){super(),this.enmasse=t,this.initState=Ye.NotInitialised,this.initPromise=Promise.resolve(),this.connectPromise=null,this.enmasse.on(L.ON_STATE,(n,...s)=>{if(n===L.STATE_CONNECTED){let[o]=s;Qs(o)}this.emit("state",this.toConnState(n),...s)}),this.enmasse.on(L.ON_MESSAGE,n=>{this.emit("message",n)})}get state(){return this.toConnState(this.enmasse.state)}get sessionId(){return this.enmasse.sessionId}toConnState(t){switch(t){case L.STATE_CONNECTING:return ie.Connecting;case L.STATE_CONNECTED:return ie.Connected;case L.STATE_DISCONNECTED:default:return ie.Disconnected}}async init(t){return this.initState===Ye.Initialising||this.initState===Ye.Initialised?this.initPromise:(this.initPromise=new Promise((n,s)=>{this.initState=Ye.Initialising,this.enmasse.on(L.ON_READY,()=>{this.initState=Ye.Initialised,this.enmasse.off(L.ON_READY),this.enmasse.off(L.ON_ERROR),n()}),this.enmasse.on(L.ON_ERROR,o=>{this.initState=Ye.NotInitialised,this.enmasse.off(L.ON_READY),this.enmasse.off(L.ON_ERROR),s(new Error(`Unable to initialise connect kit: ${o}`))}),this.enmasse.init({config:`https://${t}/config/enmasse.json`})}),this.initPromise)}connect(){return this.initState!==Ye.Initialised?Promise.reject(new Error("must be initialised before connecting")):this.state===ie.Connected?Promise.resolve():this.state===ie.Connecting?this.connectPromise?this.connectPromise:Promise.reject(new Error("BUG: Connection state is Connecting but connectPromise is null - this indicates an internal inconsistency")):(this.connectPromise=new Promise((t,n)=>{let s=o=>{switch(o){case ie.Connected:this.enmasse.off(L.ON_STATE,s),this.connectPromise=null,t();break;case ie.Disconnected:this.enmasse.off(L.ON_STATE,s),this.connectPromise=null,n(new Error("disconnected"));break;case ie.Connecting:break}};this.enmasse.on(L.ON_STATE,s),this.enmasse.connect()}),this.connectPromise)}disconnect(){this.enmasse.disconnect()}subscribe(t){return new Promise(n=>{let s=o=>{o===t&&(this.enmasse.off(L.ON_EOC,s),n())};this.enmasse.on(L.ON_EOC,s),this.enmasse.subscribe(t)})}unsubscribe(t){this.enmasse.unsubscribe(t)}send(t,n,s){this.enmasse.send(t,n,s)}async login(t,n,s){return new Promise((o,r)=>{this.enmasse.login(t,n,s,o,()=>{r(new Error("Login failure"))})})}async logout(){this.enmasse.logout()}delete(){this.enmasse.teardown()}};Jd=ye(async e=>{let t=new To;return await t.init(e),t},e=>e);Xd=ye(async(e,t)=>e.subscribe(t),(e,t)=>t)});function gn(){let e=Oo.getInstance();if(!ca){for(let t of da)t(e);ca=!0}return e}function Zd(e){da.push(e)}function la(e){if(Se()!==null)throw new Ze(nt.CannotSetFromChild,aa[nt.CannotSetFromChild]());if("necessary"in e&&e.necessary===!1)throw new Ze(nt.NecessaryCategoryRequired,aa[nt.NecessaryCategoryRequired]());let n=gn();n.state=e}function ua(){var e;return(e=gn().state)!==null&&e!==void 0?e:{}}function Ao(e){return gn().on(Jn.ConsentChanged,e)}function ga(e){let t=gn();t.state=e}function el(){Ao(e=>{qi(Dt.OnConsentUpdated,{state:e})}),xt(e=>{if(e.action!==Dt.RequestConsent)return;let t=gn();an(e,{state:t.isActive?t.state:null})})}async function tl(){let e=Se();if(e!==null)try{let t=await jn(e,Dt.RequestConsent),{state:n}=t.payload;n!=null&&ga(n)}catch{}}function nl(e){let t=Se();if(t===null)return()=>{};let n=Bi(t,s=>{if(s.action===Dt.OnConsentUpdated){let{state:o}=s.payload;ga(o)}});return tl(),n}var Dt,Jn,nt,aa,Oo,da,ca,fa=ee(()=>{kt();We();(function(e){e.OnConsentUpdated="consentOnConsentUpdated",e.SetConsent="consentSetConsent",e.RequestConsent="consentRequestConsent"})(Dt||(Dt={}));(function(e){e.ConsentChanged="consent_changed"})(Jn||(Jn={}));(function(e){e.NecessaryCategoryRequired="necessary_category_required",e.CannotSetFromChild="cannot_set_from_child"})(nt||(nt={}));aa={[nt.NecessaryCategoryRequired]:()=>"Cannot set \'necessary\' category to false. Strictly necessary functionality cannot be disabled.",[nt.CannotSetFromChild]:()=>"Cannot set consent state from embedded experience. Consent is managed by the parent application."};Oo=class e extends z{get state(){return this._state}set state(t){let n=this._state;this._state=t,t!==null&&!e.isConsentStateEqual(n,t)&&this.emit(Jn.ConsentChanged,t)}get isActive(){return this._state!==null}constructor(){super(),this._state=null}static isConsentStateEqual(t,n){if(t===null&&n===null)return!0;if(t===null||n===null)return!1;let s=Object.keys(t),o=Object.keys(n);if(s.length!==o.length)return!1;let r=t,i=n;return s.every(a=>r[a]===i[a])}static getInstance(){return e.instance||(e.instance=new e),e.instance}};da=[],ca=!1;Zd(nl);el()});function pa(e){if(Io.has(e))return Io.get(e);let t=new No(e);return Io.set(e,t),t}function sl(e){return pa(e===void 0?"__SELF__":e.bridge.id)}function ma(e,t){sl().emit(st.OnEvent,e,t);let s=Se();s!==null&&go(s,st.OnEvent,{eventName:e,properties:t})}var st,No,Io,ha=ee(()=>{kt();We();(function(e){e.OnEvent="onAnalyticsEvent"})(st||(st={}));No=class extends z{constructor(t){super(),this.id=t}};Io=new Map;xt(e=>{if(!Object.values(st).includes(e.action))return;let t=pa(e.bridgeId);if(e.action===st.OnEvent){let{eventName:n,properties:s}=e.payload;t.emit(st.OnEvent,n,s);let o=Se();o!==null&&go(o,st.OnEvent,{eventName:n,properties:s})}})});async function Po(e,t){return await(await fetch(`https://${e}/projects/${t.substring(0,2)}/${t}/settings.json`)).json()}var ya=ee(()=>{});function ht(e){return ol(e)}function ba(e){return e.split(/[-_]/)[0]}function il(e){let t=[navigator.language,...navigator.languages];for(let n of t)if(e.includes(n))return n;for(let n of t){let s=ba(n);for(let o of e)if(ba(o)===s)return o}return e[0]}function pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:e.all}async function al(e,t){let{id:n,host:s}=e;if($t.has(n))return $t.get(n);let o=new Do(e,t);$t.set(n,o);try{if(await(await cl(s)).subscribeProject(n),!o.listings)throw new Error(`Unable to fetch project ${n} listings. Possibly wrong project id.`);return o.fields=await Po(o.host,o.id),o}catch(r){throw Xn.has(n)&&Xn.get(n).unsubscribeProject(n),$t.delete(n),r}}async function cl(e){if(Xn.has(e))return Xn.get(e);let t=await ht(e);return t.on("message",dl),t}async function dl(e){let{id:t,klass:n,data:s}=e,o=$t.get(t);o&&n===Xe.Listings&&await ll(o,s[0])}async function ll(e,t){var n;let s=JSON.parse(t),o=s.project.app_settings_digest,r=(n=e.listings)===null||n===void 0?void 0:n.project.app_settings_digest;e.listings=s;try{r!==void 0&&o!==r&&(e.fields=await Po(e.host,e.id))}catch{Sa.warn(`Unable to fetch project ${e.id} settings`)}}function Ut(e=sn()){return ul(e)}function wa(e,t){return He(e,"updated",t)}async function Zn(e,t){let n=await fetch(`https://${e}/events/${t.substring(0,2)}/${t}/history.json`);if(!n.ok)throw new Error(`Failed to fetch event ${t} history`);return await n.json()}function Go(e,t){if(Gt.has(e.id))return Gt.get(e.id);let n=new $o(e,t);return n.on("internal_state",hl.bind(n)),Gt.set(e.id,n),n}async function gl(e){if(e.initState===it.Initialising)throw new Error("can\'t initialise event, event is already being initialised");if(e.initState===it.Initialised)throw new Error("can\'t initialise event, event is already initialised");if(e.initState=it.Initialising,e.canLoadHistory&&e.history===null){let t=await Zn(e.context.project.host,e.id);e.history=t}e.canSubscribe&&await fl(e),await ml(e),e.initState=it.Initialised}async function fl(e){if(!e.canSubscribe)throw new Error("Event can\'t be subscribed");await(await ht(e.context.project.host)).subscribeEvent(e.id)}async function pl(e){(await ht(e.context.project.host)).unsubscribeEvent(e.id)}async function ml(e){let{project:t}=e.context;if(_a.has(t.id))return;let n=await ht(t.host);if(n.enmasse!==null){let s=un(n.enmasse,yl);_a.set(t.id,s)}}async function hl(e){e===he.Finished&&await pl(this)}async function yl(){for(let e of Array.from(Gt.values()))if(e.initState===it.Initialised){let t=await Zn(e.context.project.host,e.id);e.history=t}}function Ea(e){return bl(e)}function mn(e,t){return _l(Ue(e),t)}function Ca(e,t){return He(e,"updated",t)}async function Ta(e,t){if(ke.has(e.id))return ke.get(e.id);let n=new jo(e,t);return await Ol(n),ke.set(n.id,n),n}function xa(e){return Array.from(ke.values()).find(t=>t.pollId===e)}async function Bo(e){return vl(e)}async function wl(e){return Sl(e)}async function El(e){let{klass:t}=e;switch(t){case Xe.Create:await Cl(e);break;case Xe.Revoke:Tl(e);break;case Xe.Feedback:await xl(e);break;case Xe.Reveal:kl(e);break}}async function Cl(e){let{id:t,data:n}=e,s=JSON.parse(n[0]),o=await mn(t);if(o!==null)if(ke.has(s.id)){let r=ke.get(s.id);(s.updated_at>r.updatedAt||s.duration!==r.duration)&&(r.update(s),o.emit("update",r))}else{let r=Object.assign(Object.assign({},o.context),{event:o}),i=await Ta(s,r);o.emit("publish",i)}}function Tl(e){let{data:t}=e,{id:n}=JSON.parse(t[0]);if(!ke.has(n))return;let s=ke.get(n);ke.delete(n),s.destroy(),s.context.event.emit("revoke",s)}async function xl(e){let{data:t}=e,n=+t[0],s=t[3],o=xa(n);if(!o)return;let r=s.split(":").map(d=>+d),i=Pi(r),a=r.map((d,g)=>({percentage:i[g],votes:d}));o.results=a}function kl(e){let{data:t}=e,n=+t[0],s=+t[1]-1,o=xa(n);o&&o.correctOption!==s&&(o.correctOption=s,o.context.event.emit("update",o))}async function va(e){if(e.timeline.length===0)return;let t=await mn(e.config.id);if(t===null)return;let n=Object.assign(Object.assign({},t.context),{event:t});for(let s of e.timeline)ke.has(s.id)||await Ta(s,n)}async function Ol(e){let t=await Ot(`element_${e.id}_vote`);t!==null&&(e.userAnswer=Uo.fromJSON(t))}function ka(e){return Al(e)}function Oa(e,t){return Bo(e),He(e,"update",t)}var rt,Xe,Qe,Mo,ol,fn,Lo,Ag,rl,Do,Sa,$t,Xn,ul,he,it,$o,Gt,_a,bl,_l,qe,Ig,mt,Uo,Fo,ot,jo,ke,vl,Sl,Ng,Al,Je,qo,Ro,Pg,Aa=ee(()=>{We();ko();Dn();ya();zn();(function(e){e.Ok="ok",e.Error="error"})(rt||(rt={}));(function(e){e.Listings="listings",e.History="history",e.Create="create",e.Revoke="revoke",e.Stop="stop",e.Reveal="reveal",e.Poll="p",e.Feedback="fb",e.Eoc="eoc",e.Vote="v",e.SubsCounter="subscounter"})(Xe||(Xe={}));(function(e){e.Poll="p",e.Live="l"})(Qe||(Qe={}));Mo=class extends z{constructor(t){super(),this.host=t,this._state=rt.Ok,this._enmasse=null}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this.emit("state",this._state))}get enmasse(){if(this._enmasse===null)throw new Error("Connect is not initialised, init() method should be called first.");return this._enmasse}set enmasse(t){this._enmasse=t}async init(){this.enmasse=await Wn(this.host),this.enmasse.on("message",this.handleMessage.bind(this)),this.enmasse.on("state",this.handleState.bind(this))}async connect(){await Yn(this.enmasse)}disconnect(){Qn(this.enmasse)}async subscribeProject(t){await Mt(this.enmasse,`${Qe.Live}-${t}`)}unsubscribeProject(t){Lt(this.enmasse,`${Qe.Live}-${t}`)}async subscribeEvent(t){await Promise.all([Mt(this.enmasse,`${Qe.Live}-${t}`),Mt(this.enmasse,`${Qe.Poll}-${t}`)])}unsubscribeEvent(t){Lt(this.enmasse,`${Qe.Live}-${t}`),Lt(this.enmasse,`${Qe.Poll}-${t}`)}sendVote(t,n,s){ia(this.enmasse,`${Qe.Poll}-${t}`,Xe.Vote,[n,s,""])}handleMessage(t){let{klass:n,body:s,channel:o}=t,r=o.substring(o.indexOf("-")+1);this.emit("message",{id:r,klass:n,data:s})}handleState(t,...n){switch(t){case ie.Disconnected:this.state=rt.Error;break;case ie.Connecting:{let[s]=n;s>1&&(this.state=rt.Error);break}case ie.Connected:this.state=rt.Ok;break}}};ol=ye(async e=>{let t=new Mo(e);return await t.init(),await t.connect(),t},e=>e);(function(e){e.Ok="ok",e.Error="error"})(fn||(fn={}));Lo=class extends z{constructor(t){super(),this.connect=t,this._state=fn.Ok,this.connect.on("state",this.handleState.bind(this))}get state(){return this._state}set state(t){this._state=t,this.emit("state",t)}handleState(){switch(this.connect.state){case rt.Error:this.state=fn.Error;break;case rt.Ok:default:this.state=fn.Ok;break}}};Ag=ye(async e=>{let t=await ht(e.options.host);return new Lo(t)},e=>e.options.host);rl=30;Do=class extends z{constructor(t,n){super(),this.eventsChecksum=null,this.id=t.id,this.host=t.host,this._context=n}get context(){return this._context}get embedUrl(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.embed}get uuid(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.uuid}get events(){var t;return((t=this._listings)===null||t===void 0?void 0:t.events)||[]}get listings(){return this._listings}set listings(t){let n=this._calculateCreatedEvents(t),s=this._calculateUpdatedEvents(t),o=this._calculateDeletedEvents(t);this._listings=Object.assign({},t),this._updateLocales(t),this._updateEventsChecksum(t),this._emitListingsEvents(n,s,o)}_calculateCreatedEvents(t){return this._listings?t.events.filter(({id:n})=>!this._listings.events.some(s=>n===s.id)):[]}_calculateUpdatedEvents(t){return this._listings?t.events.filter(n=>{let s=this._listings.events.find(({id:o})=>n.id===o);return s&&n.digest!==s.digest}):[]}_calculateDeletedEvents(t){return this._listings?this._listings.events.filter(({id:n})=>!t.events.some(s=>n===s.id)):[]}_updateLocales(t){this._locales=t.project.locales.map(n=>Object.assign({},n)).sort(n=>n.default?-1:0).map(n=>n.key),this._locale=il(this._locales)}_updateEventsChecksum(t){this.eventsChecksum=Ri(t.events.map(n=>n.digest).join(""))}_emitListingsEvents(t,n,s){let o=t.length>0,r=s.length>0,i=n.length>0,a=o||r||i;o&&this.emit("listings_events_created",t),r&&this.emit("listings_events_deleted",s),i&&this.emit("listings_events_updated",n),a&&this.emit("listings")}get isLocalisationSupported(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.is_localisation_supported}get locale(){return this._locale}set locale(t){if(!this.locales.includes(t))throw new Error(`Unknown locale name "${t}"`);this._locale=t}get locales(){return this._locales}get fields(){return this._fields!==void 0?pn(this._fields,this.locale):{}}set fields(t){let n=typeof this._fields<"u";this._fields=Object.assign({},t),n&&this.emit("updated")}get extensions(){var t;return(t=this._listings)===null||t===void 0?void 0:t.assets}get historyIgnore(){var t;let n=(t=this._listings)===null||t===void 0?void 0:t.project.history_ignore;return n&&n>0?n:rl}delete(){}};Sa=et("@monterosa/sdk-interact-kit");$t=new Map,Xn=new Map;ul=ye(async e=>await al({id:e.options.projectId,host:e.options.host},{sdk:e}),e=>e.options.projectId);(function(e){e.Upcoming="upcoming",e.Active="active",e.Prolonged="prolonged",e.Finished="finished"})(he||(he={}));(function(e){e.Uninitialised="uninitialised",e.Initialising="initialising",e.Initialised="initialised"})(it||(it={}));$o=class extends z{constructor(t,n){super(),this._initState=it.Uninitialised,this._history=null,this._data=t,this._context=n,this._state=this.calculateState(),this._internalState=this.calculateInternalState(),this.boundHandleState=this.handleState.bind(this),this.boundHandleInternalState=this.handleInternalState.bind(this),this.boundHandleEventsUpdated=this.handleEventsUpdated.bind(this),this.unsubscribeStateHandler=Mn(this.boundHandleState),this.unsubscribeInternalStateHandler=Mn(this.boundHandleInternalState),this.unsubscribeListingsHandler=He(this.context.project,"listings_events_updated",this.boundHandleEventsUpdated)}calculateState(){return!this._data.started||Ke()<this.startAt?he.Upcoming:Ke()<this.endAt?he.Active:he.Finished}calculateInternalState(){return!this._data.started||Ke()<this.startAt?he.Upcoming:Ke()<this.endAt?he.Active:Ke()<this.endAt+this._data.extra_time?he.Prolonged:he.Finished}handleState(){let t=this.calculateState();t===he.Finished&&this.unsubscribeStateHandler(),t!==this._state&&(this._state=t,this.emit("state",t))}handleInternalState(){let t=this.calculateInternalState();t===he.Finished&&this.unsubscribeInternalStateHandler(),t!==this._internalState&&(this._internalState=t,this.emit("internal_state",t))}handleEventsUpdated(t){let n=t.find(({id:s})=>s===this.id);n&&this._data.digest!==n.digest&&(this._data=n,this.handleState(),this.handleInternalState(),this.emit("updated"))}destroy(){this.unsubscribeStateHandler(),this.unsubscribeInternalStateHandler(),this.unsubscribeListingsHandler()}get context(){return this._context}get id(){return this._data.id}get name(){return this._data.name}get startAt(){return this._data.start_at}get startAtIso(){return this._data.start_at_iso}get endAt(){return this._data.end_at}get endAtIso(){return this._data.end_at_iso}get duration(){return this._data.duration}get fields(){let{locale:t}=this.context.project;return pn(this._data.custom_fields,t)}get state(){return this._state}get internalState(){return this._internalState}get initState(){return this._initState}set initState(t){this._initState=t}get history(){return this._history}set history(t){this._history=t,this.emit("history",t)}get canSubscribe(){return this._internalState===he.Active||this._internalState===he.Prolonged}get canLoadHistory(){return Ke()>=this.startAt+this.context.project.historyIgnore}};Gt=new Map,_a=new Map;bl=ye(async e=>{e===void 0&&(e=await Ut());let t=Object.assign(Object.assign({},e.context),{project:e});return e.events.map(n=>Go(n,t)).sort((n,s)=>n.startAt-s.startAt)},e=>{var t,n;if(e!==void 0)return(t=e.eventsChecksum)!==null&&t!==void 0?t:e.id;let s=sn(),o=$t.get(s.options.projectId);return o?(n=o.eventsChecksum)!==null&&n!==void 0?n:o.id:s.options.projectId});_l=ye(async(e,t)=>{if(Gt.has(e))return Gt.get(e);t===void 0&&(t=await Ut());let n=Object.assign(Object.assign({},t.context),{project:t}),s=t.events.find(o=>o.id===e);if(s!==void 0){let o=Go(s,n);if(o.canLoadHistory){let r=await Zn(t.host,e);o.history=r}return o}try{let o=await Zn(t.host,e),r=Go(o.config,n);return r.history=o,r}catch{return null}},e=>e);(function(e){e.OptionIndexOutOfRange="out_of_range",e.BelowMinVoteOptions="below_min_vote_options",e.AboveMaxVoteOptions="above_max_vote_options",e.AboveMaxVotesPerUser="above_max_per_user",e.AboveMaxVotesPerOption="above_max_per_option",e.VotedOnNonInteractiveElement="non_interactive_element",e.VotedOnClosedElement="closed_element",e.EmptyVote="empty_vote"})(qe||(qe={}));Ig={[qe.OptionIndexOutOfRange]:(e,t)=>`Options index ${t} is out of range [0..${e}]`,[qe.BelowMinVoteOptions]:(e,t)=>`Below min (${e}) vote options: ${t}`,[qe.AboveMaxVoteOptions]:(e,t)=>`Above max (${e}) vote options: ${t}`,[qe.AboveMaxVotesPerUser]:(e,t)=>`Above max (${e}) votes per user: ${t}`,[qe.AboveMaxVotesPerOption]:(e,t)=>`Above max (${e}) votes per option: ${t}`,[qe.VotedOnNonInteractiveElement]:e=>`Non interact element ${e}`,[qe.VotedOnClosedElement]:e=>`Element ${e} is closed`,[qe.EmptyVote]:e=>`Empty value for options indices: ${e}`};(function(e){e.Opened="opened",e.Closed="closed"})(mt||(mt={}));Uo=class e{constructor(t=[]){this._answers=new Map;for(let{option:n,value:s}of t)this._answers.set(n,s)}get answers(){return Array.from(this._answers.entries()).map(([t,n])=>({option:t,value:n}))}static fromIndices(t){return new e(t.map(n=>({option:n,value:1})))}set(t,n){return this._answers.set(t,n),this}remove(t){return this._answers.delete(t),this}toJSON(){return this.answers}static fromJSON(t){return new e(JSON.parse(t))}};(function(e){e.Data="data",e.Poll="poll",e.RegularPoll="rpoll",e.DiametricPoll="dpoll",e.EmotingPoll="emo",e.Powerbar="powerbar",e.Prediction="prediction",e.Trivia="trivia"})(Fo||(Fo={}));(function(e){e.OnVote="vote",e.OnClose="close",e.OnEventEnd="event_end",e.Manual="manual",e.Never="never",e.Always="always"})(ot||(ot={}));jo=class extends z{constructor(t,n){var s,o;super(),this._results=null,this._userAnswer=null,this._correctOption=null,this._data=t,this._context=n,this._results=((s=t.data)===null||s===void 0?void 0:s.results)||null,this._correctOption=!((o=t.data)===null||o===void 0)&&o.correct_option?t.data.correct_option-1:null,this._state=this.calculateState(),this.unsubscribeStateHandler=Mn(()=>this.handleState())}calculateState(){return Ke()<this.publishedAt+this.duration?mt.Opened:mt.Closed}handleState(){let t=this.calculateState();t===mt.Closed&&this.unsubscribeStateHandler(),t!==this._state&&(this._state=t,this.emit("state",t))}update(t){this._data=t,this.handleState()}destroy(){this.unsubscribeStateHandler()}get context(){return this._context}get id(){return this._data.id}get eventId(){return this.context.event.id}get state(){return this._state}get type(){return this._data.type}get contentType(){return this._data.content_type}get publishedAt(){return this._data.published_at}get publishedAtIso(){return this._data.published_at_iso}get updatedAt(){return this._data.updated_at}get updatedAtIso(){return this._data.updated_at_iso}get duration(){return this._data.duration}get fields(){let{locale:t}=this.context.project;return pn(this._data.custom_fields,t)}get interactive(){return this.type!==Fo.Data}get pollId(){return this._data.data.id||null}get question(){let{locale:t}=this.context.project;return this._data.data.question===void 0?null:pn(this._data.data.question,t)}get answerOptions(){let{locale:t}=this.context.project;return this._data.data.options===void 0?null:pn(this._data.data.options,t)}get minOptionsPerVote(){return this._data.data.min_options_per_vote||1}get maxOptionsPerVote(){return this._data.data.max_options_per_vote||1}get maxVotesPerOption(){return this._data.data.max_votes_per_option||1}get maxVotesPerUser(){return this._data.data.max_votes_per_user||null}get userAnswer(){return this._userAnswer}set userAnswer(t){this._userAnswer=t}get hasBeenAnswered(){return this._userAnswer!==null}get showResultsMode(){return this._data.data.reveal_results_mode||null}get canShowResults(){switch(this.showResultsMode){case ot.OnVote:return this.hasBeenAnswered||this.state===mt.Closed;case ot.OnClose:return this.state===mt.Closed;case ot.Manual:return this._results!==null;case ot.OnEventEnd:return this.context.event.state===he.Finished;case ot.Never:return!1;case ot.Always:default:return!0}}get results(){return this.canShowResults?this._results:null}set results(t){JSON.stringify(t)!==JSON.stringify(this.results)&&(this._results=t,this.canShowResults&&this.emit("results"))}get correctOption(){return this._correctOption}set correctOption(t){this._correctOption=t}get isCorrectOptionRevealed(){return this._correctOption!==null}};ke=new Map;vl=ye(async e=>{e.on("history",va),e.history!==null&&va(e.history),await wl(e.context.sdk.options.host),await gl(e)},e=>e.id);Sl=ye(async e=>{(await ht(e)).on("message",El)},e=>e);Ng=ye(async(e,t)=>(await Bo(e),Array.from(ke.values()).find(s=>s.id===t)||null),(e,t)=>t),Al=ye(async e=>(await Bo(e),Array.from(ke.values()).filter(t=>t.eventId===e.id).sort((t,n)=>t.publishedAt-n.publishedAt)),e=>e.id,{clearOnResolve:!0});(function(e){e.Opened="opened",e.Closed="closed"})(Je||(Je={}));qo=class extends z{constructor(t,n){super(),this.host=t,this.id=n,this.state=Je.Closed,this.lastCount=0,this.connect=null,this.boundHandleMessage=this.handleMessage.bind(this),this.boundHandleTimeout=this.handleTimeout.bind(this)}async init(){this.connect=await ht(this.host),this.connect.on("message",this.boundHandleMessage)}get isOpened(){return this.state===Je.Opened}handleMessage(t){let{id:n,klass:s,data:o}=t;if(!(n!==this.id||s!==Xe.SubsCounter))try{let r=JSON.parse(o[0]);this.handleCounterUpdate(r.counter),this.resetTimeout(r.next_update_at)}catch{Sa.warn("Couldn\'t parse subscounter message.")}}handleCounterUpdate(t){if(t<0)return;let n=!1,s=!1;this.lastCount!==t&&(n=!0,this.lastCount=t),this.state===Je.Closed&&(s=!0,this.state=Je.Opened),n&&this.emit("updated",this.lastCount),s&&this.emit("state",Je.Opened)}handleTimeout(){this.state=Je.Closed,this.emit("state",Je.Closed)}resetTimeout(t){clearTimeout(this.closeTimeout),this.closeTimeout=setTimeout(this.boundHandleTimeout,(t-Ke()+3)*1e3)}destroy(){this.connect!==null&&this.connect.off("message",this.boundHandleMessage)}};Ro=new Map,Pg=ye(async(e,t)=>{if(Ro.has(t))return Ro.get(t);let n=new qo(e,t);return await n.init(),Ro.set(t,n),n},(e,t)=>t)});function Ia(e=15e3){let t=new Map,n,s=!1;return{announce:()=>{for(let r of[...t.keys()])r()},subscribe(r,i){return t.set(r,i),()=>{t.delete(r)}},start(r){s||n!==void 0||(n=setInterval(()=>{for(let[i,a]of[...t])(!r||a?.())&&i()},e))},stop(){s=!0,clearInterval(n),t.clear()}}}var Na=ee(()=>{"use strict"});function Il(e){let t;try{t=new URL(e??"").searchParams}catch{return"none"}return t.get("micBridgeId")===null?"none":parseInt(t.get("micBridgeVersion")??"",10)>=2?"v2":"legacy"}function Pl(e){let{kit:t,local:n,timeout:s=()=>{}}=e;if(e.bridge==="none")return t;let o=e.answerMs??1500,r,i=()=>{r=!1,s(1)};e.bridge==="legacy"?i():s(o+500);let a=d=>{if(r===!1)return d(n);if(r)return d(t);let g=d(t).finally(()=>{r===void 0&&(r=!0,s(Nl))});return new Promise((c,u)=>{let y=setTimeout(()=>{i(),g.catch(()=>{}),d(n).then(c,u)},o);g.then(c,u).finally(()=>clearTimeout(y))})};return{read:d=>a(g=>g.read(d)),write:(d,g)=>a(c=>c.write(d,g)),remove:d=>a(g=>g.remove(d))}}var Nl,Rl,Pa,Ra=ee(()=>{"use strict";kt();zn();Nl=2e4;Pa=()=>Rl??=Pl({bridge:Il(globalThis.location?.href),kit:{read:Ot,write:At,remove:Bn},local:{read:async e=>Pe.getItem(e),write:async(e,t)=>Pe.setItem(e,t),remove:async e=>Pe.removeItem(e)},timeout:ji})});var La={};Vo(La,{createMonterosaPlatform:()=>Ll});function zo(){let t={...ua()};return{declared:Object.keys(t).length>0,categories:t}}async function Ma(e,t){return t?await mn(t,e):(await Ea(e)).find(s=>s.state==="active")}function Ml(e,t){return Di({host:e,projectId:t},`gamestage:${e}:${t}`)}async function Ll(e){let t=Kt(),n={},s=[],o=Ia(e.pollMilliseconds),r=o.announce;s.push(o.stop);let i=new Set,a,d={enabled:!1},g=Ds(e.host),c=Ml(g,e.projectId),u=Pa(),y=async()=>{try{let w=await Ut(c);b(w);let h=at(w?.fields);d=zt(w?.fields);let N=await Ma(w,e.eventId);if(a=N?.id??a,N){let R=at(N.fields),k={...h.labels,...R.labels},H={...h.options,...R.options};Object.assign(h,R),Object.keys(k).length>0&&(h.labels=k),Object.keys(H).length>0&&(h.options=H)}for(let R of Object.keys(n))delete n[R];Object.assign(n,h);for(let R of[...i])R(n);f="studio",l=h,v?.write(e.projectId,h)}catch{}},b=w=>{if(!(!e.locale||!w||typeof w!="object"))try{w.locale=e.locale}catch{}},T=w=>{for(let h of Object.keys(n))delete n[h];Object.assign(n,w);for(let h of[...i])h(n)},f="none",l,v=e.rememberSettings===!1?void 0:ti({store:u,consent:e.settingsConsent??zo}),p=v?await v.read(e.projectId):null;p&&(Object.assign(n,p),f="device");let C,S=new Promise(w=>C=w),_=(async()=>{let w=!1;try{let h=await Wn(g);C(h),s.push(un(h,N=>t.sample(N*1e3))),s.push(()=>Qn(h)),await Promise.race([Yn(h),new Promise((N,R)=>setTimeout(()=>R(new Error("mesh connect timed out")),e.connectTimeoutMs??8e3))]),w=!0}catch{C(null)}try{let h=await Promise.race([Ut(c),new Promise((k,H)=>setTimeout(()=>H(new Error("studio settings read timed out")),e.connectTimeoutMs??8e3))]);b(h);let N=at(h?.fields);d=zt(h?.fields);let R=await Ma(h,e.eventId);if(a=R?.id,R){let k=at(R.fields),H={...N.labels,...k.labels},ue={...N.options,...k.options};Object.assign(N,k),Object.keys(H).length>0&&(N.labels=H),Object.keys(ue).length>0&&(N.options=ue)}return T(N),f="studio",l=N,v?.write(e.projectId,N),R&&w&&(s.push(Oa(R,r)),s.push(Ca(R,()=>{y()}))),h&&w&&s.push(wa(h,()=>{y()})),w&&!!R}catch{return!1}})();p?_.then(o.start):o.start(await _);let x=new Set;return s.push(Ao(()=>{let w=zo();for(let h of[...x])h(w)})),{kind:"monterosa",projectId:c.options.projectId,get eventId(){return a},async elementFields(w){let h=await Ut(c),N=await mn(w,h);return N?(await ka(N)).map(k=>({id:k.id,contentType:String(k.contentType),fields:k.fields??{}})):[]},clock:t,presentation:n,get signInSettings(){return d},settingsSource:()=>f,rememberSettings(){l&&v?.write(e.projectId,l)},consent:zo,onConsentChanged(w){return x.add(w),()=>x.delete(w)},onPresentationChanged(w){return i.add(w),()=>i.delete(w)},declareConsent(w){try{return la(w),!0}catch{return!1}},onRoundAnnounced:o.subscribe,subscribeLive(w,h){let N=!1,R=!1,k=null,H=!1,ue=[];h.status({state:"connecting"});let be=async $=>{R=!1;try{await Mt($,w)}catch{return}N||(R=!0,h.synced(),h.status({state:"live"}))};return S.then($=>{if(!N){if(!$)return h.status({state:"unavailable"});k=$,ue.push(ra($,ge=>{if(ge.channel!==w)return;let _e;try{_e=JSON.parse(ge.body[0]??"")}catch{return}h.message(String(ge.klass),_e,!R)}),sa($,(ge,_e)=>h.status({state:typeof navigator<"u"&&navigator.onLine===!1?"offline":ge>1?"reconnecting":"connecting",attempt:ge,retryAt:Date.now()+_e*1e3})),oa($,()=>{R=!1,H=!0,h.status({state:"reconnecting"})}),un($,()=>{H&&(H=!1,be($))})),be($)}}),()=>{if(N=!0,ue.forEach($=>$()),k)try{Lt(k,w)}catch{}}},emit(w){ma(w.name,{...On(w.properties),at:w.at})},storage:u,stop(){for(let w of s.splice(0))w();x.clear()}}}var Da=ee(()=>{"use strict";Dn();ko();fa();ha();Aa();Vt();$s();St();vs();Wt();Ls();Na();Ra()});var Ko="gs-gate-style",za=`\n.gs-gate{position:fixed;inset:0;z-index:2147483100;display:grid;place-items:center;padding:16px;background:rgba(10,10,14,.72);box-sizing:border-box}\n.gs-gate__card{width:100%;max-width:24rem;box-sizing:border-box;display:grid;gap:14px;padding:22px 20px;border-radius:20px;background:var(--gs-gate-surface,#fff);color:var(--gs-gate-ink,#1b1c1f);font-family:inherit;font-size:17px;line-height:1.45;box-shadow:0 10px 30px rgba(0,0,0,.25)}\n.gs-gate__title{margin:0;font-size:22px;line-height:1.25}\n.gs-gate__note{margin:0;font-weight:600}\n.gs-gate__choice{display:flex;gap:12px;align-items:flex-start;cursor:pointer}\n.gs-gate__choice input{width:22px;height:22px;margin:2px 0 0;flex:none;accent-color:var(--gs-gate-accent,#1b1c1f)}\n.gs-gate__continue{min-height:48px;padding:12px 20px;border:0;border-radius:12px;background:var(--gs-gate-accent,#1b1c1f);color:var(--gs-gate-on-accent,#fff);font:inherit;font-weight:650;cursor:pointer}\n.gs-gate__continue:disabled{opacity:.45;cursor:default}\n.gs-gate [hidden]{display:none!important}\n.gs-gate__not-me{justify-self:center;min-height:44px;padding:8px 12px;border:0;background:none;color:inherit;font:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer}\n.gs-gate__sorry{margin:0;font-size:19px;font-weight:600}\n.gs-gate :is(input,button):focus-visible{outline:3px solid var(--gs-gate-accent,#1b1c1f);outline-offset:3px}\n`;function ts(e){let t=e.GAMESTAGE_GATE;if(!t||typeof t!="object")return;let n=t,s=typeof n.minimumAge=="number"&&n.minimumAge>0?n.minimumAge:void 0,o=Array.isArray(n.territories)?n.territories.filter(r=>typeof r=="string"&&/^[A-Z]{2}$/.test(r)):[];if(!(!s&&!o.length))return{...s?{minimumAge:s}:{},...o.length?{territories:o}:{},...typeof n.note=="string"&&n.note.trim()?{note:n.note.trim()}:{}}}function ns(e,t="en-GB"){let n;try{n=new Intl.DisplayNames([t],{type:"region"})}catch{}let s=new Set(["GB","US","AE","NL","PH","CZ","DO","BS","GM","MV"]),o=e.map(r=>`${s.has(r)?"the ":""}${n?.of(r)??r}`);return o.length<=1?o.join(""):`${o.slice(0,-1).join(", ")} or ${o[o.length-1]}`}var ss=e=>`gamestage:gate:${e}`,jt=e=>JSON.stringify([e.minimumAge??null,e.territories??[]]);function Wo(e,t,n){try{let s=n?.getItem(ss(e));if(!s)return;let o=JSON.parse(s);return o.gate!==jt(t)?void 0:o.qualified===!1?"not_qualified":"qualified"}catch{return}}function Yo(e,t,n){return Wo(e,t,n)==="qualified"}function os(e,t=Ha()){try{t?.removeItem(ss(e))}catch{}}function Ha(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Va(e,t){let n=e.minimumAge?` aged ${e.minimumAge} and over`:"",s=e.territories?.length?` in ${ns(e.territories,t)}`:"";return`Sorry, this game is for people${n}${s}.`}function bn(e,t,n={}){let s=n.document??(typeof document>"u"?void 0:document),o=n.storage??(typeof localStorage>"u"?void 0:localStorage);if(!e||!s||Yo(t,e,o))return Promise.resolve();let r=x=>{try{o?.setItem(ss(t),JSON.stringify({gate:jt(e),qualified:x,at:i().toISOString()}))}catch{}},i=n.now??(()=>new Date);if(!s.getElementById?.(Ko)){let x=s.createElement("style");x.id=Ko,x.textContent=za,s.head?.append(x)}let a=(x,w)=>{let h=s.createElement(x);return w&&(h.textContent=w),h},d=a("div");d.className="gs-gate",d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-labelledby","gs-gate-title");let g=a("form");g.className="gs-gate__card";let c=a("h2","Before you play");if(c.id="gs-gate-title",c.className="gs-gate__title",g.append(c),e.note){let x=a("p",e.note);x.className="gs-gate__note",g.append(x)}let u=[],y=(x,w)=>{let h=a("label");h.className="gs-gate__choice";let N=a("input");N.type="checkbox",N.setAttribute("data-gs-declare",x),h.append(N,a("span",w)),u.push(N),g.append(h)};e.territories?.length&&y("territory",`I\'m in ${ns(e.territories,n.locale)}.`),e.minimumAge&&y("age",`I\'m ${e.minimumAge} or over.`);let b=a("button","Continue");b.type="submit",b.className="gs-gate__continue",b.setAttribute("data-gs-gate-continue",""),b.disabled=!0,g.append(b);let T=a("button","I don\'t meet these");T.type="button",T.className="gs-gate__not-me",T.setAttribute("data-gs-gate-not-me",""),g.append(T);let f=a("div");f.className="gs-gate__card gs-gate__exit";let l=a("p",Va(e,n.locale));l.className="gs-gate__sorry";let v=a("button","Go back");v.type="button",v.className="gs-gate__not-me",v.setAttribute("data-gs-gate-back",""),f.append(l,v);let p=x=>{g.hidden=x,f.hidden=!x};T.onclick=()=>{r(!1),p(!0)},v.onclick=()=>{p(!1),u[0]?.focus?.()},p(Wo(t,e,o)==="not_qualified"),d.append(g,f);let C=()=>Array.from(d.querySelectorAll?.("input, button")??[]).filter(x=>!x.disabled&&!x.closest?.("[hidden]"));d.onkeydown=x=>{if(x.key!=="Tab")return;let w=C();if(!w.length)return;let h=w[0],N=w[w.length-1],R=s.activeElement;x.shiftKey&&(R===h||!d.contains?.(R))?(x.preventDefault(),N.focus()):!x.shiftKey&&(R===N||!d.contains?.(R))&&(x.preventDefault(),h.focus())};let S=x=>{d.isConnected&&!d.contains?.(x.target)&&C()[0]?.focus()};s.addEventListener?.("focusin",S);let _=()=>s.removeEventListener?.("focusin",S);for(let x of u)x.onchange=()=>{b.disabled=!u.every(w=>w.checked)};return new Promise(x=>{g.onsubmit=w=>{w.preventDefault?.(),u.every(h=>h.checked)&&(r(!0),_(),d.remove?.(),x())},(s.body??s.documentElement)?.append(d),u[0]?.focus?.()})}var W={notify:"/play/v1/games/{game}/notify",notifyConfirm:"/play/v1/games/{game}/notify/confirm",notifyResend:"/play/v1/games/{game}/notify/resend",runtime:"/play/v1/games/{game}/runtime",currentRound:"/play/v1/games/{game}/rounds/current",rounds:"/play/v1/games/{game}/rounds",roundsMine:"/play/v1/games/{game}/rounds/mine",nextRound:"/play/v1/games/{game}/rounds/next",round:"/play/v1/games/{game}/rounds/{round}",plays:"/play/v1/games/{game}/rounds/{round}/plays",session:"/play/v1/games/{game}/session",restoreSession:"/play/v1/games/{game}/session/restore",guestToken:"/play/v1/games/{game}/guest-token",gameToken:"/play/v1/games/{game}/game-token",commentsToken:"/play/v1/games/{game}/comments-token",commentsKeys:"/play/v1/comments-keys",roundState:"/play/v1/games/{game}/rounds/{round}/players/me",profile:"/play/v1/games/{game}/players/me/profile",identityOptions:"/play/v1/games/{game}/identity",identity:"/play/v1/games/{game}/players/me/identity",nameTicket:"/play/v1/games/{game}/name-ticket",recoveryCode:"/play/v1/games/{game}/players/me/recovery-code",declaration:"/play/v1/games/{game}/players/me/declaration",roundStats:"/play/v1/games/{game}/rounds/{round}/stats",leaderboard:"/play/v1/games/{game}/leaderboard",editionLeaderboard:"/play/v1/games/{game}/leaderboard/edition"};var Be={rooms:"/play/v1/games/{game}/rooms",roomJoin:"/play/v1/games/{game}/rooms/join",room:"/play/v1/games/{game}/rooms/{room}",roomStart:"/play/v1/games/{game}/rooms/{room}/start",roomLeave:"/play/v1/games/{game}/rooms/{room}/leave",roomPresence:"/play/v1/games/{game}/rooms/{room}/presence",roomPlay:"/play/v1/games/{game}/rooms/{room}/play",roomBoard:"/play/v1/games/{game}/rooms/{room}/board"};var Qo="penalty_v1";var Ka="balanced_v1",Jo={aimX:{min:-1200,max:1200},aimY:{min:-200,max:1200},power:{min:0,max:1e3}},Xo={postX:1e3,barY:1e3,postWidth:60,barHeight:60,ballRadius:40,keeperStart:{x:0,y:420}},Wa="shoot";function bt(e){return{op:Wa,model:Qo,shotIndex:e.shotIndex,aimX:e.aimX,aimY:e.aimY,power:e.power}}function _n(e){let t=e?.progress;if(!t||t.kind!=="shoot")return;let n=Array.isArray(t.shots)?t.shots:[];return{kind:"shoot",model:t.model??Qo,profile:t.profile??Ka,goals:typeof t.goals=="number"?t.goals:0,shots:n}}function vn(e){return e?.shots.at(-1)}function Ya(e){return{...e.picks?{picks:e.picks}:{},...e.answers?{answers:e.answers}:{},...e.op?{op:e.op}:{},...e.centre!==void 0?{centre:e.centre}:{},...e.board!==void 0?{board:e.board}:{},...e.operation??{}}}var Sn=e=>`gamestage-session:${e}`;function rs(e,t=typeof localStorage>"u"?void 0:localStorage){return t?.getItem(Sn(e))??void 0}var F=(e,t,n,s)=>e.replace("{game}",encodeURIComponent(t)).replace("{round}",encodeURIComponent(n??"")).replace("{room}",encodeURIComponent(s??""));function is(){let e=new Uint8Array(12);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var _t=class extends Error{status;code;retryable;detail;constructor(t,n,s,o,r={}){super(s),this.status=t,this.code=n,this.retryable=o,this.detail=r,this.name="PlayerApiError"}},Qa=6e4;function Ja(e){let t=e.split(".")[1];if(t)try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),s=n+"=".repeat((4-n.length%4)%4),o=JSON.parse(atob(s));return typeof o.exp=="number"&&Number.isFinite(o.exp)?o.exp*1e3:void 0}catch{return}}function Zo(e){let t=e.fetch??globalThis.fetch.bind(globalThis),n=e.baseUrl.replace(/\\/+$/,""),s=e.storage??(typeof localStorage>"u"?void 0:localStorage),o=e.session??s?.getItem(Sn(e.game))??void 0,r;async function i(){return o||(r??=(async()=>{let p=await t(`${n}${F(W.session,e.game)}`,{method:"POST"});if(!p.ok)return;let C=await p.json();if(C.token)return o=C.token,s?.setItem(Sn(e.game),o),o})().finally(()=>{r=void 0}),r)}let a=e.now??Date.now,d,g;async function c(p=!1){return p&&(d=void 0),d&&a()<d.renewAt?d.token:(d=void 0,g??=(async()=>{let C=await l(F(W.guestToken,e.game),{method:"POST"});if(!C.token)throw new _t(200,"unknown","The Engine did not issue a guest token.",!1);let S=Ja(C.token);return d=S===void 0?void 0:{token:C.token,renewAt:S-Qa},C.token})().finally(()=>{g=void 0}),g)}async function u(){let p=await l(F(W.commentsToken,e.game),{method:"POST"});if(!p.token)throw new _t(200,"unknown","The Engine did not issue a comments token.",!1);return p.token}let y,b;async function T(){return y&&a()<y.renewAt?y.token:(b??=(async()=>{let p=await c(),C=await t(e.spaceAuthUrl??`${n}/api/auth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"jwt_bearer",assertion:p}).toString()}),S=await C.json().catch(()=>({}));if(!C.ok||!S.access_token)throw C.status<500&&(d=void 0),new _t(C.status,"space_sign_in_refused",S.message??"The Space did not accept the guest token.",C.status>=500);let _=(S.expires_in??3600)*1e3;return y={token:S.access_token,renewAt:a()+Math.max(_-6e4,0)},S.access_token})().finally(()=>{b=void 0}),b)}let f=()=>typeof e.identity=="function"?e.identity():e.identity;async function l(p,C,S=!0){let _=await i(),x=await f(),w=await t(`${n}${p}`,{...C,headers:{"content-type":"application/json",..._?{"x-gamestage-player":_}:{},...x?{authorization:`Bearer ${x}`}:{},...C?.headers??{}}}),h=await w.json().catch(()=>({}));if(!w.ok){let N=h.error;if(S&&w.status===401&&N?.code==="session_required")return o===_&&(o=void 0),l(p,C,!1);throw new _t(w.status,N?.code??"unknown",N?.message??w.statusText,N?.retryable??!1,N??{})}return h}return{guestToken:c,commentsToken:u,spaceToken:T,subscribeNotify:p=>l(F(W.notify,e.game),{method:"POST",body:JSON.stringify(p)}),confirmNotify:p=>l(F(W.notifyConfirm,e.game),{method:"POST",body:JSON.stringify(p)}),resendNotify:p=>l(F(W.notifyResend,e.game),{method:"POST",body:JSON.stringify(p)}),getRuntime:()=>l(F(W.runtime,e.game)),getCurrentRound:()=>l(F(W.currentRound,e.game)),getRound:p=>l(F(W.round,e.game,p)),getNextRound:()=>l(F(W.nextRound,e.game)),getRounds:()=>l(F(W.rounds,e.game)),getPlayedRounds:()=>l(F(W.roundsMine,e.game)),getRoundState:p=>l(F(W.roundState,e.game,p)),getRoundStats:p=>l(F(W.roundStats,e.game,p)),getProfile:()=>l(F(W.profile,e.game)),getIdentityOptions:()=>l(F(W.identityOptions,e.game)),createRoom:p=>l(F(Be.rooms,e.game),{method:"POST",body:JSON.stringify({name:p})}),joinRoom:(p,C)=>l(F(Be.roomJoin,e.game),{method:"POST",body:JSON.stringify({code:p,name:C})}),getRoom:p=>l(F(Be.room,e.game,void 0,p)),startRoom:p=>l(F(Be.roomStart,e.game,void 0,p),{method:"POST"}),leaveRoom:p=>l(F(Be.roomLeave,e.game,void 0,p),{method:"POST"}),roomPresence:p=>l(F(Be.roomPresence,e.game,void 0,p),{method:"POST"}),getRoomPlay:p=>l(F(Be.roomPlay,e.game,void 0,p)),getRoomBoard:p=>l(F(Be.roomBoard,e.game,void 0,p)),setIdentity:p=>l(F(W.identity,e.game),{method:"POST",body:JSON.stringify(p)}),getNameTicket:()=>l(F(W.nameTicket,e.game),{method:"POST"}),declare:p=>l(F(W.declaration,e.game),{method:"POST",body:JSON.stringify({gate:p,qualified:!0})}),getLeaderboard:()=>l(F(W.leaderboard,e.game)),getEditionLeaderboard:()=>l(F(W.editionLeaderboard,e.game)),getRecoveryStatus:()=>l(F(W.recoveryCode,e.game)),issueRecoveryCode:()=>l(F(W.recoveryCode,e.game),{method:"POST"}),restoreFromRecoveryCode:async p=>{let C=await l(F(W.restoreSession,e.game),{method:"POST",body:JSON.stringify({code:p})});return o=C.token,r=void 0,s?.setItem(Sn(e.game),o),C},play:v,shoot:(p,C,S)=>v(p,{operation:bt(C),roundVersion:C.roundVersion,challengeInstanceId:C.challengeInstanceId},S)};function v(p,C,S){return l(F(W.plays,e.game,p),{method:"POST",body:JSON.stringify({idempotency_key:S,round_version:C.roundVersion,challenge_instance_id:C.challengeInstanceId??null,payload:Ya(C),...C.room?{room:C.room}:{}})})}}var vt=class extends Error{constructor(n,s,o){super(s);this.status=n;this.code=s;this.retryAfterSeconds=o;this.name="ArcadeError"}status;code;retryAfterSeconds;get retryable(){return this.code==="rate_limited"||this.code==="engine_busy"||this.status===0}get needsSignIn(){return this.code==="sign_in_required"}get runDidNotCount(){return/^(score_|duration_|run_)/.test(this.code)}},Xa="/game-token";function as(e){let t=e.api.replace(/\\/$/,"")+(e.basePath??"/api/arcade"),n=e.fetch??fetch,s=e.newKey??(()=>crypto.randomUUID()),o=encodeURIComponent(e.game);async function r(){let a=await e.gameToken?.().catch(()=>{});return a?{token:a,prefix:Xa}:{token:await e.token(),prefix:""}}async function i(a,d,g,c={}){let u=async()=>{let y;try{let{token:T,prefix:f}=await r();y=await n(t+f+d,{method:a,headers:{authorization:`Bearer ${T}`,...g===void 0?{}:{"content-type":"application/json"},...c},...g===void 0?{}:{body:JSON.stringify(g)}})}catch{throw new vt(0,"network_error")}let b=await y.json().catch(()=>({}));if(!y.ok)throw new vt(y.status,b.message??"unknown",b.retryAfterSeconds);return b.data};try{return await u()}catch(y){if(y instanceof vt&&y.status===0)return u();throw y}}return{start:a=>i("POST",`/games/${o}/runs`,{build:a.build},{"idempotency-key":s()}),finish:(a,d)=>i("POST",`/runs/${encodeURIComponent(a)}/result`,{score:d.score,playedMs:d.playedMs,metrics:d.metrics??{}}),board:(a="all-time",d={})=>{let g=new URLSearchParams;d.limit!==void 0&&g.set("limit",String(d.limit)),d.offset!==void 0&&g.set("offset",String(d.offset));let c=g.toString();return i("GET",`/boards/${o}/${encodeURIComponent(a)}${c?`?${c}`:""}`)},me:()=>i("GET",`/games/${o}/me`),setName:a=>i("PUT",`/games/${o}/me/name`,{ticket:a})}}var Za=e=>`edition-${e}`;function ec(e){let n=(e??"").trim().toLowerCase().replace(/[^a-z0-9_.]/g,"").replace(/\\.{2,}/g,"."),s=/[a-z]/.test(n),r=(s?n:`fan${n?`_${n}`:""}`).slice(0,30);return(r.length>=3?r:s?r.padEnd(3,"0"):r.padEnd(3,"a"))||"fan"}function cs(e){let t=e.fetch??((...a)=>fetch(...a)),n,s,o=async(a=!1)=>{try{let d=await e.fanToken(a),g=await t(`${e.api}/api/auth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"jwt_bearer",assertion:d}).toString()}),c=await g.json().catch(()=>({}));return!g.ok||!c.access_token?!a&&g.status<500?o(!0):null:(n=c.access_token,c.access_token)}catch{return null}},r=async()=>n||(s??=o().finally(()=>{s=void 0}),s);async function i(a,d,g=!1,c=!0){let u=c?await r():void 0;if(c&&!u)return null;try{let y=await t(`${e.api}${a}`,{...d,headers:{...d?.body!==void 0?{"content-type":"application/json"}:{},...u?{authorization:`Bearer ${u}`}:{},...d?.headers??{}}});return c&&y.status===401&&!g?(n=void 0,s=void 0,i(a,d,!0)):y.ok?await y.json().catch(()=>null):null}catch{return null}}return{suggestName:ec,async list(){return((await i(`/api/v1/comments/topics/${encodeURIComponent(e.topicId)}/messages?sort=oldest&top_level=true`,void 0,!1,!1))?.data??[]).sort((g,c)=>g.received_at-c.received_at)},async canPost(){return await r()!==null},async post(a){let g=(await i(`/api/v1/comments/topics/${encodeURIComponent(e.topicId)}`,{method:"POST",body:JSON.stringify({text:a})}))?.data?.message_id;return g?{message_id:g}:null},async me(){let a=await i(`/api/v1/comments/me?topic_id=${encodeURIComponent(e.topicId)}`,void 0);return a&&typeof a.user_id=="string"?a:null},async setName(a){let d=await i("/api/v1/comments/me/display-name",{method:"PUT",body:JSON.stringify({display_name:a})});return d?.display_name?{display_name:d.display_name}:null}}}St();var wt=class extends Error{constructor(n,s,o){super(s);this.status=n;this.code=s;this.retryAfterSeconds=o;this.name="QuizError"}status;code;retryAfterSeconds;get retryable(){return lc.has(this.code)||this.status===0}get needsSignIn(){return this.code==="sign_in_required"}get questionClosed(){return this.code==="question_closed"}get needsNickname(){return this.code==="nickname_required"||this.code==="nickname_refused"||this.code==="nickname_taken"}},lc=new Set(["rate_limited","engine_busy","nickname_check_unavailable","question_not_open"]),Ar=5,uc="/game-token",gc=30;function ys(e){let t=e.api.replace(/\\/$/,"")+(e.basePath??"/api/quiz"),n=e.fetch??fetch,s=e.sleep??(c=>new Promise(u=>setTimeout(u,c))),o=e.retries??3,r=encodeURIComponent(e.game),i=c=>encodeURIComponent(c);async function a(){let c=await e.gameToken?.().catch(()=>{});return c?{token:c,prefix:uc}:{token:await e.token(),prefix:""}}async function d(c,u,y){let b=async()=>{let f;try{let{token:v,prefix:p}=await a();f=await n(t+p+u,{method:c,headers:{authorization:`Bearer ${v}`,...y===void 0?{}:{"content-type":"application/json"}},...y===void 0?{}:{body:JSON.stringify(y)}})}catch{throw new wt(0,"network_error")}let l=await f.json().catch(()=>({}));if(!f.ok){let v=l.message&&/^[a-z_]+$/.test(l.message)?l.message:f.status===429?"rate_limited":"unknown";throw new wt(f.status,v,l.retryAfterSeconds)}return l.data},T=0;for(let f=0;;f++)try{return await b()}catch(l){if(!(l instanceof wt)||!l.retryable||f>=o)throw l;let v=l.status===0?0:Math.min(l.retryAfterSeconds??1,gc);if(l.code==="question_not_open"){if(T>=Ar)throw l;v=Math.min(v,Ar-T),T+=v}await s(v*1e3)}}let g=(c={})=>{let u=new URLSearchParams;c.limit!==void 0&&u.set("limit",String(c.limit)),c.cursor!==void 0&&u.set("cursor",c.cursor);let y=u.toString();return y?`?${y}`:""};return{nickname:c=>d("POST",`/games/${r}/nickname`,{nickname:c}),me:()=>d("GET",`/games/${r}/me`),get:c=>d("GET",`/quizzes/${i(c)}`),questions:async c=>e.words?e.words(c):[],outcomes:async c=>e.outcomeWords?e.outcomeWords(c):[],outcomeShares:async c=>{try{let u=await d("GET",`/quizzes/${i(c)}/outcomes`),y=Array.isArray(u?.outcomes)?u.outcomes:[],b=typeof u?.total=="number"?u.total:0;return b<=0?[]:y.flatMap(T=>typeof T?.outcomeId=="string"&&typeof T?.count=="number"?[{outcomeId:T.outcomeId,share:Math.min(1,Math.max(0,T.count/b))}]:[])}catch{return[]}},start:c=>d("POST",`/quizzes/${i(c)}/plays`,{}),answer:(c,u)=>d("POST",`/quizzes/${i(c)}/answers`,{answers:u.map(y=>({question:y.question,option:y.option}))}),result:c=>d("GET",`/quizzes/${i(c)}/result`),board:(c,u)=>d("GET",`/quizzes/${i(c)}/board${g(u)}`),gameBoard:c=>d("GET",`/games/${r}/board${g(c)}`)}}function bs(e,t){let n=a=>typeof a=="string"&&a.trim()?a.trim():void 0,s=n(t[hr]);if(!s)return;let o=pr.flatMap(a=>{let d=n(t[mr(a)]),g=xn(t[vr(a)]);return d?[{id:a,text:d,...g?{image:g}:{}}]:[]}),r=xn(t[yr]),i=xn(t[_r]);return{id:e,question:s,options:o,...r?{image:{url:r,alt:n(t[br])??""}}:{},...i?{media:{url:i}}:{}}}function _s(e,t){let n=a=>typeof a=="string"&&a.trim()?a.trim():void 0,s=n(t[Sr]);if(!s)return;let o=n(t[wr]),r=n(t[Er]),i=xn(t[Cr]);return{id:e,name:s,...o?{verdict:o}:{},...r?{why:r}:{},...i?{image:{url:i,alt:n(t[Tr])??""}}:{}}}function xn(e){let t=typeof e=="string"?e:e&&typeof e=="object"&&typeof e.url=="string"?e.url:void 0;if(!(!t||!t.trim()))try{let n=new URL(t.trim());return n.protocol==="https:"?n.href:void 0}catch{return}}var Ir=["moment"];function Nr(e,t){let n=t?.id;return e==="side"&&(typeof n=="string"||typeof n=="number")?`side:${n}`:e}async function Pr(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new Error("liveChannel needs WebCrypto (a browser, or Node 18+)");let s=new Uint8Array(await n.digest("SHA-1",new TextEncoder().encode(`gamestage/live/${e}/${t}`)));s[6]=s[6]&15|80,s[8]=s[8]&63|128;let o=[...s.subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`l-${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Rr(e){return e.rows.map(t=>{let n={elapsed:0,sides:[]};return e.columns.forEach((s,o)=>{if(s==="elapsed")return void(n.elapsed=t[o]);let r=s.indexOf("."),i=Number(s.slice(0,r));(n.sides[i]??={})[s.slice(r+1)]=t[o]}),n})}function kn(e,t={}){let n=t.provider??"sportmonks",s=t.contest!==void 0?String(t.contest):null,o=new Map,r=new Map,i=new Set,a={state:"idle",contest:null,last:null},d=null,g=null,c=0,u=p=>{a={...a,...p};for(let C of[...i])C(a)},y=()=>o.get("state")?.sides.map(p=>p.id)??[],b=(p,C)=>p==="timeline"&&C&&typeof C=="object"&&"columns"in C?Rr(C):C;function T(p,C,S){let _=b(p,C);o.set(Nr(p,_),_),a={...a,last:Date.now()};for(let x of r.get(p)??[])if(!(x.news&&S))try{x.fn(_)}catch(w){console.error(w)}}async function f(p){if(p===d)return;let C=++c;if(g?.(),g=null,o.clear(),d=p,!p)return u({state:"idle",contest:null,attempt:void 0,retryAt:void 0});if(!e.subscribeLive)return u({state:"unavailable",contest:p});u({state:"connecting",contest:p,attempt:void 0,retryAt:void 0});let S=await Pr(n,p);C===c&&(g=e.subscribeLive(S,{message:(_,x,w)=>T(_,x,w),synced:()=>u({last:a.last}),status:_=>u({..._,contest:p})}))}let l=()=>s??e.presentation.liveContest?.trim()??null;f(l()||null);let v=s?()=>{}:e.onPresentationChanged(()=>{f(l()||null)});return{get contest(){return d},get status(){return a},state:()=>o.get("state"),clock:()=>o.get("clock"),sides:()=>y().map(p=>o.get(`side:${p}`)).filter(p=>!!p),moments:()=>o.get("moments")??[],timeline:()=>o.get("timeline")??[],health:()=>o.get("health"),on(p,C,S={}){let _=S.news??Ir.includes(p),x={fn:C,news:_};if(r.set(p,[...r.get(p)??[],x]),!_)for(let[w,h]of o)(w===p||w.startsWith(`${p}:`))&&x.fn(h);return()=>r.set(p,(r.get(p)??[]).filter(w=>w!==x))},onStatus(p){return i.add(p),p(a),()=>i.delete(p)},stop(){c++,v(),g?.(),g=null,u({state:"idle"})}}}St();ls();vs();Vt();Vt();var Dr=new Map,$r=e=>{let t=Dr.get(e);if(t)return t;let n=new Promise((s,o)=>{if(typeof document>"u"){o(new Error("no document"));return}let r=document.createElement("script");r.src=e,r.async=!0,r.crossOrigin="anonymous",r.addEventListener("load",()=>s()),r.addEventListener("error",()=>o(new Error(`could not load ${e}`))),document.head.appendChild(r)});return Dr.set(e,n),n};var pc="https://fantenna.com/signal/v1.js";async function Gr(e){if(!e.serviceUrl||!e.projectId)return null;await(e.load??$r)(pc);let n=globalThis.FantennaSignal;if(!n)throw new Error("the Signal tag loaded without defining itself");let s=n.init({applicationId:e.game,endpoint:"",writeKey:"",fantenna:!1,consent:!0,monterosa:{enabled:!0,serviceUrl:e.serviceUrl,projectId:e.projectId},onObservation:e.onObservation?o=>{e.onObservation?.({name:`signal_${o.type}`,at:(e.now??(()=>Date.now()))(),properties:{...o.properties,signal_event_id:o.id,observed_at:o.occurredAt}})}:void 0});return s.start?.(),{track(o,r){s.track(o,{gamestage_game:e.game,...r??{}})},stop(){s.setConsent(!1),s.stop()}}}var Ss={atCapacity:{title:"Kitchen\'s at capacity",body:"This game is taking more players than it can serve right now. Nothing you did. Try again in a few minutes."},rateLimited:{title:"Too many requests from here",body:"This device is sending more requests than the game will take. Wait a moment and carry on."},cappedToday:{title:"That\'s all the plays for today",body:"This game has taken all the plays it can today. Nothing you did. Come back tomorrow."}};function ws(e){return e==="capped_today"?"cappedToday":"atCapacity"}var lt="gamestage-busy";function Es(e,t=Ss){let n=s=>{let o=e?.[s];return typeof o=="string"&&o.trim()?o:void 0};return{atCapacity:{title:n("busyTitle")??t.atCapacity.title,body:n("busyMessage")??t.atCapacity.body},rateLimited:{title:n("rateLimitedTitle")??t.rateLimited.title,body:n("rateLimitedMessage")??t.rateLimited.body},cappedToday:{title:t.cappedToday.title,body:n("cappedTodayNote")??t.cappedToday.body}}}function Cs(e,t={}){let n=t.document??globalThis.document??void 0,s=t.container??n?.body??null;if(!n||!s)return{close:()=>{}};let o=(t.copy??Ss)[e];n.getElementById(lt)?.remove();let r=n.createElement("div");r.id=lt,r.setAttribute("role","alertdialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-labelledby",`${lt}-title`),r.setAttribute("aria-describedby",`${lt}-body`),r.setAttribute("data-kind",e),t.retryAfterSeconds!==void 0&&r.setAttribute("data-retry-after",String(t.retryAfterSeconds)),r.style.cssText=["position:fixed","inset:0","z-index:2147483000","display:flex","align-items:flex-end","justify-content:center","padding:0","background:rgba(0,0,0,0.6)","font-family:inherit"].join(";");let i=n.createElement("div");i.style.cssText=["max-width:480px","width:100%","box-sizing:border-box","padding:20px 24px calc(24px + env(safe-area-inset-bottom, 0px))","border-radius:16px 16px 0 0","background:#fff","color:#111","text-align:center","box-shadow:0 -18px 40px -20px rgba(0,0,0,0.45)"].join(";");let a=n.createElement("div");a.setAttribute("aria-hidden","true"),a.style.cssText=["width:36px","height:4px","margin:0 auto 16px","border-radius:999px","background:rgba(17,17,17,0.18)"].join(";");let d=n.createElement("h2");d.id=`${lt}-title`,d.textContent=o.title,d.style.cssText="margin:0 0 8px;font-size:1.25rem;line-height:1.2";let g=n.createElement("p");g.id=`${lt}-body`,g.textContent=o.body,g.style.cssText="margin:0 0 20px;font-size:1rem;line-height:1.45";let c=n.createElement("button");c.type="button",c.textContent="Close",c.style.cssText=["appearance:none","border:0","cursor:pointer","padding:10px 20px","border-radius:999px","font:inherit","color:#fff","background:var(--gamestage-primary, #111)"].join(";");let u=()=>{n.removeEventListener("keydown",y),r.remove()},y=b=>{b.key==="Escape"&&u()};return c.addEventListener("click",u),r.addEventListener("click",b=>{b.target===r&&u()}),n.addEventListener("keydown",y),i.append(a,d,g,c),r.append(i),s.append(r),c.focus?.(),{close:u}}Wt();Ht();function Ts(e){return`gamestage:sign-in:v1:${e}`}function Ur(e,t){let n=t.toLowerCase(),s=`${e.toLowerCase()}.apps.`;if(!n.startsWith(s))return;let o=n.slice(s.length);return/^[a-z0-9.-]+\\.[a-z]{2,}$/.test(o)?`https://${o}`:void 0}function mc(e){try{let t=e.split(".")[1],n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),s=JSON.parse(n).exp;return typeof s=="number"?s:void 0}catch{return}}var hc="anon:test.";function yc(e){try{let t=e?.();return t?.startsWith(hc)?t:void 0}catch{return}}function Fr(e){let t=e.site??Ur(e.game,e.hostname),n=e.fetch??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),s=()=>e.messages??e.document?.defaultView??void 0,o=e.now??(()=>Date.now()),r=new Set,i=t&&n?"checking":"off",a,d,g,c=f=>{if(f!==i){i=f;for(let l of r)try{l(f)}catch{}}},u=f=>{try{if(!e.store||!e.mayRemember?.())return;e.store.setItem(Ts(e.game),f)}catch{}},y=()=>{try{return e.store?.getItem(Ts(e.game))??null}catch{return null}},b=()=>!t||!n?Promise.resolve(i):(d??=(async()=>{try{let f=yc(e.session),l=await n(`${t}/hub/game-token`,{credentials:"include",cache:"no-store",...f?{headers:{"x-gamestage-player":f}}:{}}),v=l.ok?await l.json().catch(()=>({})):{};v.state==="granted"&&v.token?(a=v.token,c("granted"),u("granted")):v.state==="signed_out"?(a=void 0,c("signed-out")):v.state==="not_granted"?(a=void 0,c(y()==="dismissed"?"dismissed":"not-granted")):(a=void 0,c("not-available"))}catch{a=void 0,c("not-available")}return i})().finally(()=>{d=void 0}),d),T=()=>{g&&(s()?.removeEventListener("message",g.listener),g.host.remove(),g=void 0)};return{get state(){return i},begin:b,rememberedGranted:()=>y()==="granted",async token(){if(i!=="granted")return;let f=a?mc(a):void 0;return a&&f!==void 0&&f-60>o()/1e3?a:(await b(),i==="granted"?a:void 0)},offer(f,l={}){let v=e.document,p=f.playAs?.trim();if(i!=="not-granted"||!v||!t||!p||g)return;let C=new URL(`${t}/hub/play-as`);C.searchParams.set("game",e.game),C.searchParams.set("label",p),f.detail?.trim()&&C.searchParams.set("detail",f.detail.trim()),f.dismiss?.trim()&&C.searchParams.set("dismiss",f.dismiss.trim()),l.accent&&C.searchParams.set("accent",l.accent),l.onAccent&&C.searchParams.set("on",l.onAccent),l.text&&C.searchParams.set("text",l.text);let S=v.createElement("div");S.setAttribute("data-gamestage-sign-in",""),S.style.cssText=["position:fixed","left:16px","right:16px","bottom:16px","z-index:2147483000","max-width:480px","margin:0 auto","padding:12px 16px","border-radius:16px","box-shadow:0 8px 28px rgba(0,0,0,.18)",`background:${l.surface??"Canvas"}`,"visibility:hidden"].join(";");let _=v.createElement("iframe");_.src=C.toString(),_.title=p.replaceAll("{name}","").trim(),_.style.cssText="display:block;width:100%;height:56px;border:0;background:transparent;color-scheme:normal",_.setAttribute("allowtransparency","true"),S.appendChild(_);let x=w=>{if(w.origin!==t||w.source!==_.contentWindow)return;let h=w.data;if(!(!h||h.type!=="gamestage-sign-in"))switch(h.state){case"ready":typeof h.height=="number"&&h.height>0&&h.height<400&&(_.style.height=`${Math.ceil(h.height)}px`),S.style.visibility="visible",c("offered");return;case"granted":T(),c("checking"),b();return;case"dismissed":T(),u("dismissed"),c("dismissed");return;default:T(),c("not-available")}};s()?.addEventListener("message",x),g={host:S,iframe:_,listener:x},v.body.appendChild(S)},async streak(){if(!(i!=="granted"||!t||!n))try{let f=await n(`${t}/hub/game-streak`,{credentials:"include",cache:"no-store"}),l=f.ok?await f.json().catch(()=>({})):{};return l.state==="granted"?l.streak:void 0}catch{return}},async request(f,l={},v){if(i==="granted"||i==="off"||i==="not-available")return i;if(i==="dismissed"&&c("not-granted"),i==="not-granted")return this.offer(f,l),i;if(i==="signed-out"&&t){let p=e.document,C=`${t}/hub/signin?return_to=${encodeURIComponent("/hub")}`,S=()=>{p?.visibilityState!=="hidden"&&(p?.removeEventListener("visibilitychange",S),b().then(()=>this.offer(f,l)))};p?.addEventListener("visibilitychange",S),(v??(_=>p?.defaultView?.open?.(_,"_blank")))(C)}return i},onChange(f){return r.add(f),()=>r.delete(f)},stop(){T(),r.clear()}}}Tn();function jr(e){return`${ir}:${e}`}function qr(e){return Object.entries(e).filter(t=>typeof t[1]=="boolean").sort(([t],[n])=>t.localeCompare(n))}function xs(e,t,n){return n===!0?!0:!t||!e?!1:e.querySelector(\'script[src*="user-consent"], script[src*="onetrust"], script[src*="cookielaw"]\')!=null}function bc(e){return{declared:!0,categories:{...e.categories}}}function ks(e){let t=e.window??globalThis,n=e.policyVersion?.trim()||us,s=e.now??(()=>new Date),o=new Set,r=e.hostManagesConsent===!0||e.hostOwnsConsent===!0,i=null,a=new Set(Cn([...e.embedOrigins??[]])),d=()=>{try{return t?.localStorage}catch{return}},c=(()=>{try{let S=d()?.getItem(jr(e.scope?.trim()||e.game));if(!S)return null;let _=cr(JSON.parse(S));return!_||_.source!=="fan"||_.policyVersion!==n?null:_}catch{return null}})(),u=null,y=S=>u!==null&&JSON.stringify(qr(S))===u,b=()=>{let S=e.platform.consent();return!S.declared||y(S.categories)?null:S},T=(()=>{try{return!!(t&&t.parent&&t.parent!==t)}catch{return!0}})(),f=()=>{let S=b();return S?qt(S.categories,"host",{policyVersion:n,at:s()}):e.hostOwnsConsent?i:c??i},l=()=>{let S=C.reading();for(let _ of[...o])_(S)},v=S=>{if(!T||S.source!==t?.parent||typeof S.origin!="string"||!a.has(S.origin))return;let _=S.data;!_||_.type!==ar||!_.categories||typeof _.categories!="object"||typeof _.policyVersion!="string"||_.policyVersion.trim()!==n||(i=qt(_.categories,"host",{policyVersion:n,at:s()}),l())};t?.addEventListener?.("message",v);let p=e.platform.onConsentChanged(()=>l()),C={reading(){let S=f();return S?bc(S):e.hostOwnsConsent?{declared:!0,categories:{necessary:!0,functional:!0}}:{declared:!1,categories:{necessary:!0}}},record:()=>f(),needed:()=>!r&&e.policy.analyticsRequiresConsent&&f()===null,hostDecides:()=>r||b()!==null,decide(S){if(C.hostDecides())return!1;let _=qt(S,"fan",{policyVersion:n,at:s()});c=_;try{d()?.setItem(jr(e.scope?.trim()||e.game),JSON.stringify(_))}catch{}try{u=JSON.stringify(qr(_.categories)),e.platform.declareConsent({..._.categories})}catch{}return l(),!0},onChange(S){return o.add(S),()=>o.delete(S)},stop(){t?.removeEventListener?.("message",v),p(),o.clear()}};return C}Tn();var Br="gs-consent-style",_c=`\n.gs-consent{position:fixed;left:0;right:0;bottom:var(--gs-consent-clear,0px);z-index:2147483000;display:flex;justify-content:center;padding:12px 12px calc(12px + env(safe-area-inset-bottom));pointer-events:none;box-sizing:border-box}\n.gs-consent[hidden]{display:none}\n.gs-consent--top{bottom:auto;top:0;padding:calc(12px + env(safe-area-inset-top)) 12px 12px}\n.gs-consent__card{pointer-events:auto;position:relative;width:100%;max-width:26rem;box-sizing:border-box;display:grid;gap:12px;padding:16px 44px 16px 18px;border-radius:20px;border:1px solid rgba(0,0,0,.08);background:var(--gs-consent-surface,#fff);color:var(--gs-consent-ink,#1b1c1f);box-shadow:0 10px 30px rgba(0,0,0,.18);font-family:inherit;font-size:15px;line-height:1.45}\n.gs-consent__title{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n.gs-consent p{margin:0}\n.gs-consent a{color:var(--gs-consent-accent-ink,inherit);text-decoration:underline;text-decoration-color:var(--gs-consent-accent,currentColor);text-decoration-thickness:2px;text-underline-offset:4px}\n.gs-consent__row{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}\n.gs-consent button{font:inherit;cursor:pointer;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;touch-action:manipulation}\n.gs-consent__pill{font-weight:600!important;font-size:15px;min-height:44px;min-width:6.5rem;padding:0 20px;border-radius:999px;box-sizing:border-box}\n.gs-consent__pill:active{transform:translateY(1px)}\n.gs-consent__accept{border:2px solid var(--gs-consent-accent,#1b1c1f);background:var(--gs-consent-accent,#1b1c1f);color:var(--gs-consent-on-accent,#fff)}\n.gs-consent__reject{border:2px solid currentColor;background:transparent;color:inherit}\n.gs-consent__close{position:absolute;top:6px;right:6px;width:40px;height:40px;border:0;border-radius:999px;background:transparent;color:inherit;font-size:22px!important;line-height:1;opacity:.7;display:grid;place-items:center;padding:0}\n.gs-consent__choose{border:0;background:none;color:inherit;text-decoration:underline;text-underline-offset:3px;font-size:14px;padding:4px 2px;min-height:44px}\n.gs-consent button:focus{outline:none}\n.gs-consent button:focus-visible,.gs-consent input:focus-visible,.gs-consent a:focus-visible,.gs-consent__card:focus-visible{outline:3px solid currentColor;outline-offset:2px}\n.gs-consent fieldset{border:0;margin:0;padding:0;display:grid;gap:8px}\n.gs-consent label{display:flex;gap:10px;align-items:flex-start;cursor:pointer}\n.gs-consent input[type=checkbox]{width:22px;height:22px;margin:1px 0 0;flex:none;accent-color:var(--gs-consent-accent,currentColor)}\n.gs-consent__note{font-size:14px}\n@media (min-width:720px){.gs-consent:not(.gs-consent--top) .gs-consent__card--bar{max-width:60rem;grid-template-columns:minmax(0,1fr) auto;align-items:center;column-gap:20px;padding:12px 52px 12px 20px}.gs-consent__card--bar .gs-consent__row{flex-wrap:nowrap}}\n.gs-consent-settings{font:inherit;font-size:inherit;background:none;border:0;color:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;padding:0 .25em;margin:0 0 0 .75em;min-height:0;line-height:inherit;display:inline;vertical-align:baseline}\n.gs-consent-footer{display:block;text-align:center;padding:12px 16px calc(12px + env(safe-area-inset-bottom));font-size:14px}\n.gs-consent-footer .gs-consent-settings{margin:0}\n.gs-copyright-link{display:inline-block;white-space:nowrap;text-decoration:underline}\n.gs-consent-settings:focus{outline:none}\n.gs-consent-settings:focus-visible{outline:3px solid currentColor;outline-offset:2px}\n.gs-consent-room [data-gs-page]::after{content:"";display:block;block-size:var(--gs-consent-room,0px);pointer-events:none}\n`;function vc(e){return e.footCoversMain&&!e.topCoversKept?"top":"foot"}function Os(e,t){let n=e.presentation??{},s={brand:n.consentBrandName,title:n.consentTitle,detail:n.consentDetail,accept:n.consentAcceptLabel,reject:n.consentRejectLabel,choose:n.consentChooseLabel,save:n.consentSaveLabel,analytics:n.consentAnalyticsLabel,marketing:n.consentMarketingLabel,functional:n.consentFunctionalLabel,settings:n.consentSettingsLabel},o={...lr,...t};for(let[r,i]of Object.entries(s))i&&i.trim()&&(o[r]=i);return o}var zr=["analytics","marketing","functional"],Sc=Object.freeze({analytics:!0,marketing:!1,functional:!1});function Is(e,t={}){let n=globalThis.document;if(!n.getElementById(Br)){let P=n.createElement("style");P.id=Br,P.textContent=_c,n.head.append(P)}let s=n.createElement("div");s.className="gs-consent",As(s),s.hidden=!0,s.dataset.gsComponent="consent",s.setAttribute("aria-live","polite"),n.body.append(s);let o=null,r=null,i=P=>{e.consent.decide(P),s.hidden=!0,T(),t.onDecided?.(P)},a=(P,I,G,j="")=>{let D=n.createElement("button");return D.type="button",D.textContent=P,D.dataset.gsPart=I,j&&(D.className=j),D.addEventListener("click",G),D};function d(P){let I=Os(e,t.words),G=e.consent.record()?.categories??{},j=n.createElement("div");j.className=P?"gs-consent__card":"gs-consent__card gs-consent__card--bar",j.setAttribute("role","dialog"),j.setAttribute("aria-modal","false"),j.setAttribute("aria-labelledby","gs-consent-title"),j.tabIndex=-1;let D=n.createElement("h2");D.id="gs-consent-title",D.className="gs-consent__title",D.textContent=I.title;let V=n.createElement("p");V.textContent=ur(I.detail,I.brand);let M=e.presentation?.privacyPolicyUrl;if(M&&/^https?:\\/\\//.test(M)){let K=n.createElement("a");K.href=M,K.target="_blank",K.rel="noopener",K.textContent=I.policy,V.append(" ",K,".")}let oe=a("\\xD7","dismiss",()=>{s.hidden=!0,T()},"gs-consent__close");oe.setAttribute("aria-label",I.dismiss),j.append(D,oe,V);let q=(K,Oe,re,Le)=>a(K,Oe,Le,`gs-consent__pill gs-consent__${re}`);if(P){let K=n.createElement("fieldset"),Oe=n.createElement("legend");Oe.className="gs-consent__note",Oe.textContent=I.necessary,K.append(Oe);let re={};for(let Ee of zr){let De=n.createElement("label"),ve=n.createElement("input");ve.type="checkbox",ve.checked=G[Ee]===!0,ve.dataset.gsPart=Ee,re[Ee]=ve,De.append(ve,n.createTextNode(I[Ee])),K.append(De)}let Le=n.createElement("div");Le.className="gs-consent__row",Le.append(q(I.save,"save","accept",()=>i(Object.fromEntries(zr.map(Ee=>[Ee,re[Ee].checked])))),q(I.reject,"reject","reject",()=>i({analytics:!1,marketing:!1,functional:!1}))),j.append(K,Le)}else{let K=n.createElement("div");K.className="gs-consent__row",K.append(q(I.accept,"accept","accept",()=>i({...Sc})),q(I.reject,"reject","reject",()=>i({analytics:!1,marketing:!1,functional:!1})),a(I.choose,"choose",()=>N(!0,!0),"gs-consent__choose")),j.append(K)}return s.replaceChildren(j),j}let g=n.body,c=n.documentElement,u=g.style.paddingBottom,y=c.style.scrollPaddingBottom,b=()=>n.defaultView,T=()=>{s.hidden&&S();let P=s.querySelector(".gs-consent__card"),I=s.hidden||!P||s.classList.contains("gs-consent--top"),G=I?0:Math.ceil(b().innerHeight-P.getBoundingClientRect().top);g.style.paddingBottom=I?u:`calc(${u||"0px"} + ${G}px)`;let j=I?y:`${G}px`;c.style.scrollPaddingBottom!==j&&(c.style.scrollPaddingBottom=j);let D=I?"":`${G}px`;c.style.getPropertyValue("--gs-consent-room")!==D&&(D?c.style.setProperty("--gs-consent-room",D):c.style.removeProperty("--gs-consent-room")),c.classList.contains("gs-consent-room")===I&&c.classList.toggle("gs-consent-room",!I)},f=32,l=(P,I)=>{let G=Math.min(Math.max(I.left+I.width/2,0),n.documentElement.clientWidth-1),j=Math.min(Math.max(I.top+I.height/2,0),(n.defaultView?.innerHeight??1)-1),V=(typeof n.elementsFromPoint=="function"?n.elementsFromPoint(G,j):[]).find(M=>!s.contains(M));return!V||V===P||P.contains(V)||V.contains(P)},v=()=>{let P=n.defaultView;if(!P)return 0;let I=P.innerHeight,G=[];for(let D of Array.from(n.body.querySelectorAll("body *"))){if(s.contains(D))continue;let V=P.getComputedStyle(D).position;if(V!=="fixed"&&V!=="sticky")continue;let M=D.getBoundingClientRect();M.width===0||M.height===0||M.height>=I*.4||M.bottom<=0||l(D,M)&&G.push(M)}G.sort((D,V)=>V.bottom-D.bottom);let j=0;for(let D of G)I-D.bottom<=j+f&&(j=Math.max(j,I-D.top));return j},p=null,C="",S=()=>{p&&(p.style.paddingBottom=C),p=null},_=P=>{let I=n.querySelector(".gs-boot:not([data-done])");if(!I||!P||s.hidden||s.classList.contains("gs-consent--top"))return S();p!==I&&(S(),p=I,C=I.style.paddingBottom);let G=Math.ceil(b().innerHeight-P.getBoundingClientRect().top);I.style.paddingBottom=`calc(env(safe-area-inset-bottom, 0px) + ${G}px)`},x=()=>{if(!n.defaultView)return;s.style.setProperty("--gs-consent-clear",`${Math.ceil(v())}px`),s.classList.remove("gs-consent--top");let P=s.querySelector(".gs-consent__card");if(_(P),P&&!s.hidden){let I=P.getBoundingClientRect(),G=Array.from(n.querySelectorAll(\'.gs-boot__play, [data-gamestage-start], [data-gs-main], [data-gs-part="commit"]\')),j=(D,V)=>D.some(M=>{let oe=M.getBoundingClientRect();return oe.width===0||oe.height===0||V.right<=oe.left||oe.right<=V.left||V.bottom<=oe.top||oe.bottom<=V.top?!1:l(M,oe)});if(j(G,I)){s.classList.add("gs-consent--top"),S();let D=Array.from(n.querySelectorAll("[data-gs-keep-clear]")),V=D.length>0&&j(D,P.getBoundingClientRect());vc({footCoversMain:!0,topCoversKept:V})==="foot"&&(s.classList.remove("gs-consent--top"),_(P))}}T()},w=typeof ResizeObserver=="function"?new ResizeObserver(()=>{T()}):null;b()?.addEventListener("resize",x),w?.observe(s);let h=!1;function N(P=!1,I=!1){As(s);let G=d(P);h=I||!s.hidden&&h,s.hidden=!1,T(),I&&G.focus({preventScroll:!0}),x()}let R=null,k=()=>{if(t.settingsIn!==void 0)return t.settingsIn;let P=n.querySelector(\'[data-gs-slot="privacy-settings"]\');if(P)return P;let I=n.querySelector(\'[data-gs-part="recovery"]\');if(I?.parentElement&&I.parentElement!==n.body)return I.parentElement;let G=n.querySelectorAll("footer");return G.length?G[G.length-1]:(R||(R=n.createElement("div"),R.className="gs-consent-footer",R.dataset.gsPart="settings-footer",n.body.append(R)),R)},H=()=>{let P=e.consent.hostDecides()?null:k();if(!P){o?.remove(),o=null,r?.remove(),r=null;return}o||(o=a(Os(e,t.words).settings,"settings",()=>N(!0,!0),"gs-consent-settings")),o.parentElement!==P&&P.append(o),r||(r=n.createElement("a"),r.className="gs-consent-settings gs-copyright-link",r.dataset.gsPart="copyright",r.href=dr,r.target="_blank",r.rel="noopener",r.textContent=Os(e,t.words).copyright),r.previousElementSibling!==o&&o.after(r),R&&P!==R&&(R.remove(),R=null)},ue=!1,be=typeof MutationObserver=="function"&&t.settingsIn===void 0?new MutationObserver(P=>{ue||P.every(I=>s.contains(I.target)||(o?.contains(I.target)??!1))||(ue=!0,queueMicrotask(()=>{ue=!1,H()}))}):null;be?.observe(n.body,{childList:!0,subtree:!0});let $=e.consent.onChange(()=>{H(),(e.consent.hostDecides()||!h&&!e.consent.needed())&&(s.hidden=!0,T())});H();let ge=!1,_e=typeof MutationObserver=="function"?new MutationObserver(P=>{s.hidden||ge||P.every(I=>I.target===n.body||s.contains(I.target)||I.target===p&&I.attributeName==="style")||(ge=!0,(b()?.requestAnimationFrame??setTimeout)(()=>{ge=!1,As(s),x()}))}):null;return _e?.observe(n.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","data-done","data-state"]}),e.consent.needed()&&!e.consent.hostDecides()&&N(!1),{open:()=>{e.consent.hostDecides()||N(!0,!0)},close:()=>{s.hidden=!0,T()},stop:()=>{$(),be?.disconnect(),_e?.disconnect(),b()?.removeEventListener("resize",x),w?.disconnect(),S(),s.remove(),o?.remove(),R?.remove(),g.style.paddingBottom=u,c.style.scrollPaddingBottom=y,c.style.removeProperty("--gs-consent-room"),c.classList.remove("gs-consent-room")}}}function Hr(e){let t=e.match(/rgba?\\(\\s*(\\d+)[ ,]+(\\d+)[ ,]+(\\d+)/);if(!t)return null;let[n,s,o]=[t[1],t[2],t[3]].map(r=>{let i=Number(r)/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*n+.7152*s+.0722*o}function Vr(e,t){let n=Hr(e),s=Hr(t);return n===null||s===null?null:(Math.max(n,s)+.05)/(Math.min(n,s)+.05)}function As(e){let t=e.ownerDocument.defaultView;if(!t)return;let n=t.getComputedStyle(e.ownerDocument.documentElement),s=e.ownerDocument.createElement("span");e.append(s);let o=a=>(s.style.color="",s.style.color=a,t.getComputedStyle(s).color),r=[["--gs-backgroundContainerColour","--gs-onBackgroundContainerColour"],["--gs-backgroundMainColour","--gs-onBackgroundColour"]];for(let[a,d]of r){let g=n.getPropertyValue(a).trim(),c=n.getPropertyValue(d).trim();if(!g||!c)continue;let u=Vr(o(g),o(c));if(u!==null&&u>=4.5){e.style.setProperty("--gs-consent-surface",g),e.style.setProperty("--gs-consent-ink",c);break}}let i=[["--gs-highlightMainColour","--gs-onHighlightColour"],["--gamestage-primary",""],["--gs-primaryMainColour","--gs-onPrimaryColour"]];for(let[a,d]of i){let g=n.getPropertyValue(a).trim();if(!g)continue;let c=o(g),u=n.getPropertyValue(d||"--none").trim(),b=(u?[u,"#ffffff","#111111"]:["#ffffff","#111111"]).find(T=>(Vr(c,o(T))??0)>=4.5);if(b){e.style.setProperty("--gs-consent-accent",g),e.style.setProperty("--gs-consent-on-accent",b);break}}s.remove()}var An={heading:"Can\'t load the game right now",body:"Check your connection, then try again.",retry:"Try again"},Yt=class extends Error{code="unavailable";handled=!0;constructor(){super("Interaction Cloud did not answer and this device has no remembered settings, so the game has no words to show. The library has drawn its retry screen."),this.name="GamestageUnavailableError"}},Kr="gamestage-unavailable";function Wr(e){let t=e.document;if(!t?.body||typeof t.createElement!="function"||t.getElementById?.(Kr))return;let n=t.createElement("div");n.setAttribute("id",Kr),n.setAttribute("role","alert"),Object.assign(n.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"24px",background:"#111",color:"#fff",fontFamily:"system-ui, -apple-system, sans-serif",textAlign:"center"});let s=t.createElement("h1");s.textContent=An.heading,Object.assign(s.style,{fontSize:"22px",margin:"0",fontWeight:"700"});let o=t.createElement("p");o.textContent=An.body,Object.assign(o.style,{fontSize:"17px",margin:"0",opacity:"0.8"});let r=t.createElement("button");r.setAttribute("type","button"),r.textContent=An.retry,Object.assign(r.style,{fontSize:"17px",fontWeight:"700",minHeight:"48px",padding:"0 28px",borderRadius:"999px",border:"0",background:"#fff",color:"#111",cursor:"pointer",touchAction:"manipulation",userSelect:"none"}),r.addEventListener("click",()=>e.location?.reload()),n.appendChild(s),n.appendChild(o),n.appendChild(r),t.body.appendChild(n)}async function ae(e){if(e===void 0)return{kind:"anonymous"};try{let t=typeof e=="function"?await e():e;return typeof t=="string"&&t.length>0?{kind:"identified",token:t}:{kind:"anonymous"}}catch{return{kind:"anonymous"}}}function pe(e){return e.kind==="identified"?e.token:void 0}var Yr=e=>e.replace(/\\/+$/,"");async function wc(e){let t=pe(await ae(e.identity));if(!t)return{kind:"anonymous"};let n=e.fetchImpl??globalThis.fetch,s=`${Yr(e.baseUrl)}/api/loyalty/v1/me`,o={Authorization:`Bearer ${t}`},r=await n(`${s}/points`,{headers:o});if(r.status===401||r.status===403)return{kind:"anonymous"};if(!r.ok)throw new Error(`Loyalty points read failed: ${r.status}`);let a=((await r.json()).items??[]).find(T=>T.programmeId===e.programmeId),{unlocked:d,stillToUnlock:g,catalogue:c}=await Ec(n,s,o);if(!a)return{kind:"standing",standing:{programmeId:e.programmeId,balance:0,enrolled:!1,statement:[],catalogue:c,unlocked:d,stillToUnlock:g}};let u=e.statementLimit??20,y=await n(`${s}/points/${encodeURIComponent(e.programmeId)}/statement?limit=${u}`,{headers:o}),b=y.ok?(await y.json()).lines??[]:[];return{kind:"standing",standing:{programmeId:a.programmeId,balance:a.balance,tier:a.tier,tiers:a.tiers,enrolled:!0,statement:b,catalogue:c,unlocked:d,stillToUnlock:g}}}async function Ns(e){if(!e.baseUrl)return null;let t=pe(await ae(e.identity));if(!t)return null;let n=e.fetchImpl??globalThis.fetch;try{let s=await n(`${Yr(e.baseUrl)}/api/loyalty/v1/me/streak`,{headers:{Authorization:`Bearer ${t}`}});return s.ok?Ps(await s.json()):null}catch{return null}}function Ps(e){let t=e??{};return typeof t.current!="number"||typeof t.best!="number"?null:{current:t.current,best:t.best,lastDay:t.lastDay??"",proved:t.proved===!0,nextMilestone:t.nextMilestone}}async function Ec(e,t,n){let[s,o]=await Promise.all([e(`${t}/rewards`,{headers:n}).catch(()=>{}),e(`${t}/products`,{headers:n}).catch(()=>{})]),r=s?.ok?((await s.json()).items??[]).map(c=>({instanceId:c.instance.instanceId,product:{productId:c.instance.product.productId,name:c.instance.product.name,description:c.instance.product.description,type:c.instance.product.type},campaignName:c.campaign?.name,awardedAt:c.awardedAt})):[],i=o?.ok?(await o.json()).items??[]:[],a=new Set(r.map(c=>c.product.productId)),d=i.map(c=>({productId:c.productId,name:c.name,description:c.description,type:c.type})),g=d.filter(c=>!a.has(c.productId));return{unlocked:r,stillToUnlock:g,catalogue:d}}function Cc(e){let t=e.round;if(!t)return"No round has been read yet.";let n=t.origin;return n?n.source==="studio"?`This round came from Studio: element ${n.element_id??"unknown"}`+(n.edition_id?` on edition ${n.edition_id}`:"")+`, as round ${t.id} version ${t.version}.`:`This round came from the game\'s manifest, as ${t.id} version ${t.version}.`:`This round is ${t.id}, and this Engine does not say where it came from. That is older than the field, not a manifest round.`}function Tc(e){return(e.performance?.getEntriesByType?.("resource")??[]).slice(-40).map(n=>{let s=n;return{name:s.name,status:s.responseStatus?String(s.responseStatus):"unknown",ms:Math.round(s.duration)}})}function xc(e,t){let n=[Cc(e),"",`game ${e.game}`,`platform ${e.platform}`];e.offPlatformReason&&n.push(`not on ic ${e.offPlatformReason}`),e.ids?.project&&n.push(`project ${e.ids.project}`),e.ids?.event&&n.push(`edition ${e.ids.event}`),e.ids?.element&&n.push(`element ${e.ids.element}`),e.ids?.host&&n.push(`studio host ${e.ids.host}`),e.endpoints.playerApi&&n.push(`player api ${e.endpoints.playerApi}`),e.endpoints.mesh&&n.push(`mesh ${e.endpoints.mesh}`),n.push(`identity ${e.identity.signedIn?`${e.identity.kind}, signed in`:e.identity.kind}`),n.push(`consent ${e.consent.allowed?"granted":"not granted"}`);let s=Object.entries(e.presentation).filter(([,o])=>o);n.push(`producer ${s.length?s.map(([o])=>o).join(", "):"nothing set"}`),n.push("","requests");for(let o of Tc(t))n.push(` ${o.status.padEnd(7)} ${o.ms.toString().padStart(5)}ms ${o.name}`);return n.push("",`page ${t.location?.href??"unknown"}`),n.push(`when ${new Date().toISOString()}`),n.join(`\n`)}var Qr="gsdebug",kc="gamestage-debug";function Oc(e,t){let n=e.document,s=n.createElement("div");s.id="gamestage-debug",s.setAttribute("role","dialog"),s.setAttribute("aria-label","Gamestage diagnostics"),s.style.cssText=["position:fixed","inset:auto 0 0 0","max-height:70vh","overflow:auto","z-index:2147483647","background:#0b0f1c","color:#e8eaf2","font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace","padding:12px 14px","border-top:2px solid #e5484d","white-space:pre-wrap"].join(";");let o=n.createElement("div");o.style.cssText="display:flex;gap:8px;margin-bottom:10px";let r=n.createElement("button");r.textContent="Copy",r.style.cssText="font:inherit;padding:4px 10px;cursor:pointer",r.onclick=()=>{e.navigator.clipboard?.writeText(t).then(()=>r.textContent="Copied",()=>r.textContent="Select and copy")};let i=n.createElement("button");i.textContent="Close",i.style.cssText=r.style.cssText,i.onclick=()=>s.remove(),o.append(r,i);let a=n.createElement("div");return a.textContent=t,s.append(o,a),s}function Jr(e,t){let n=t.document;if(!n)return()=>{};let s=()=>{n.getElementById("gamestage-debug")?.remove(),n.body?.append(Oc(t,xc(e(),t)))},o="",r=i=>{let a=i.target;a?.isContentEditable||a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||i.key.length!==1||(o=(o+i.key.toLowerCase()).slice(-Qr.length),o===Qr&&s())};return n.addEventListener("keydown",r),t.location&&new URLSearchParams(t.location.search).has(kc)&&t.setTimeout(s,0),()=>n.removeEventListener("keydown",r)}Wt();function Rs(e={}){let t=Kt(),n=new Map,s=[],o=new Set,r=new Set,i=new Set,a={...e.presentation??{}},d={declared:!1,categories:{}},g,c=!1,u=()=>{for(let f of[...o])f()},y=e.setInterval??((f,l)=>setInterval(f,l)),b=e.clearInterval??(f=>clearInterval(f)),T=e.pollMilliseconds??0;return T>0&&(g=y(u,T)),{kind:"local",offPlatformReason:e.offPlatformReason,clock:t,emitted:s,presentation:a,signInSettings:e.signInSettings??{enabled:!1},consent:()=>d,onConsentChanged(f){return r.add(f),()=>r.delete(f)},onPresentationChanged(f){return i.add(f),()=>i.delete(f)},setPresentation(f){for(let l of Object.keys(a))delete a[l];Object.assign(a,f);for(let l of[...i])l(a)},declareConsent(f){d={declared:!0,categories:{...f}};for(let l of[...r])l(d);return!0},onRoundAnnounced(f){return o.add(f),()=>o.delete(f)},subscribeLive(f,l){let v=e.liveSource;if(!v||typeof EventSource>"u")return l.status({state:"unavailable"}),()=>{};let p=!1;l.status({state:"connecting"});let C=`${v}${v.includes("?")?"&":"?"}channel=${encodeURIComponent(f)}`,S=new EventSource(C);return S.onmessage=_=>{try{let x=JSON.parse(_.data);l.message(x.class,x.body,!p)}catch{}},S.addEventListener("synced",()=>{p=!0,l.synced(),l.status({state:"live"})}),S.onerror=()=>{p=!1,l.status({state:typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting"})},()=>S.close()},announce:u,emit(f){s.push(f)},storage:{read:async f=>n.get(f)??null,write:async(f,l)=>{n.set(f,l)},remove:async f=>{n.delete(f)}},stop(){c||(c=!0,g!==void 0&&b(g),o.clear(),r.clear())}}}Ht();Ls();function ni(e,t){let n=new Date(e);if(!Number.isNaN(n.getTime()))try{return n.toLocaleDateString("en-CA",{timeZone:t})}catch{return}}function si(e){let t=new Date(`${e}T12:00:00Z`);return t.setUTCDate(t.getUTCDate()-1),t.toISOString().slice(0,10)}function Ic(e,t={}){let n=t.timeZone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",s=t.now??new Date,o=new Set;for(let u of e){if(u.amount<=0)continue;let y=ni(u.occurredAt,n);y&&o.add(y)}if(o.size===0)return{days:0,capped:!1,today:!1};let r=ni(s.toISOString(),n)??"",i=o.has(r),a=i?r:si(r);if(!o.has(a))return{days:0,capped:!1,today:i};let d=0;for(;o.has(a);)d+=1,a=si(a);let g=[...o].sort()[0],c=a<g;return{days:d,capped:c,today:i}}Vt();$s();Wt();St();function oi(e,t,n=Date.now(),s){if(!e?.can.results_available||!e.finalAt||n>=Date.parse(e.finalAt))return"";let o=new Date(e.finalAt).toLocaleString(s,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit"});return t.replaceAll("{finalAt}",o)}function Nc(e,t,n="label_provisional_result"){let s,o=()=>{clearTimeout(s),t.textContent=oi(e.round,e.presentation?.labels?.[n.replace(/^label_/,"")]??fr,e.now()),t.hidden=!t.textContent;let a=Date.parse(e.round?.finalAt??"")-e.now();a>0&&(s=setTimeout(o,Math.min(a,2147483647)))},r=e.onRoundChanged(o),i=e.onPresentationChanged(o);return o(),()=>{clearTimeout(s),r(),i()}}var ri={open:"Your progress",showTitle:"Keep your progress",showDetail:"Save this code. It brings your name, scores and achievements back on another phone or browser. You only see it once.",private:"Keep it private. Anyone with this code can play as you.",replace:"Getting a new code stops the old one working.",get:"Get a recovery code",issueFailed:"That didn\'t work. Check your connection and try again.",copy:"Copy",copied:"Copied",share:"Share",enterTitle:"I\'ve played before",enterDetail:"Type the recovery code you saved to get your progress back.",submit:"Get my progress back",notRecognised:"That code isn\'t one we know. Check it against the one you saved.",restored:"Welcome back. Your progress is on this device now.",close:"Close"};var ii="gs-recovery-style",Pc=`\n.gs-recovery-open{font:inherit;background:none;border:0;color:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;padding:.5rem 0;min-height:44px}\n.gs-recovery{border:0;border-radius:16px;padding:0;max-width:min(26rem,calc(100vw - 32px));width:100%;color:#1b1c1f;background:#fff;box-shadow:0 18px 48px rgba(0,0,0,.35)}\n.gs-recovery::backdrop{background:rgba(0,0,0,.55)}\n.gs-recovery__body{display:grid;gap:12px;padding:20px;font:17px/1.45 system-ui,sans-serif}\n.gs-recovery h2{margin:0;font-size:1.2rem}\n.gs-recovery p{margin:0}\n.gs-recovery__code{font:700 1.25rem/1.3 ui-monospace,Menlo,monospace;letter-spacing:.02em;text-align:center;padding:12px;border:1.5px solid #c9ccd3;border-radius:10px;background:#f4f5f7;user-select:all;overflow-wrap:anywhere}\n.gs-recovery__row{display:flex;gap:8px;flex-wrap:wrap}\n.gs-recovery button{font:inherit;font-weight:600;min-height:44px;padding:0 16px;border-radius:10px;border:1.5px solid #1b1c1f;background:#fff;color:#1b1c1f;cursor:pointer}\n.gs-recovery button.gs-recovery__primary{background:#1b1c1f;color:#fff}\n.gs-recovery button:disabled{opacity:.5;cursor:default}\n.gs-recovery input{font:16px/1.3 system-ui,sans-serif;min-height:44px;padding:0 12px;border:1.5px solid #c9ccd3;border-radius:10px}\n.gs-recovery input[aria-invalid=true]{border-color:#c62828;border-style:dashed}\n.gs-recovery__note{color:#50535c;font-size:.95rem}\n.gs-recovery__error{color:#c62828}\n.gs-recovery hr{border:0;border-top:1px solid #e3e5e9;margin:4px 0}\n`;function Rc(e,t){let n=e.presentation??{},s={open:n.recoveryOpenLabel,showTitle:n.recoveryShowTitle,showDetail:n.recoveryShowDetail,private:n.recoveryPrivateNote,replace:n.recoveryReplaceNote,enterTitle:n.recoveryEnterTitle,enterDetail:n.recoveryEnterDetail,submit:n.recoverySubmitLabel,notRecognised:n.recoveryNotRecognised,restored:n.recoveryRestored,get:n.recoveryGetLabel,issueFailed:n.recoveryIssueFailed,copy:n.recoveryCopyLabel,copied:n.recoveryCopiedLabel,share:n.recoveryShareLabel,close:n.recoveryCloseLabel},o={...ri,...t};for(let[r,i]of Object.entries(s))i&&i.trim()&&(o[r]=i);return o}function Y(e,t,n={},...s){let o=e.createElement(t),{dataset:r,...i}=n;return Object.assign(o,i),r&&Object.assign(o.dataset,r),o.append(...s),o}function Mc(e,t,n={}){let s=t.ownerDocument;s.getElementById(ii)||s.head.append(Y(s,"style",{id:ii,textContent:Pc}));let o=()=>Rc(e,n.words),r=Y(s,"button",{type:"button",className:"gs-recovery-open",textContent:o().open});r.dataset.gsPart="recovery";let i=Y(s,"dialog",{className:"gs-recovery"});i.setAttribute("aria-labelledby","gs-recovery-title"),t.append(r),s.body.append(i);function a(){let c=o(),u=Y(s,"div",{className:"gs-recovery__body"}),y=Y(s,"h2",{id:"gs-recovery-title",textContent:c.showTitle}),b=Y(s,"p",{className:"gs-recovery__code",hidden:!0});b.setAttribute("aria-label",c.showTitle);let T=Y(s,"button",{type:"button",textContent:c.copy,hidden:!0}),f=Y(s,"button",{type:"button",textContent:c.share,hidden:!0}),l=Y(s,"span",{className:"gs-recovery__note"});l.setAttribute("aria-live","polite");let v=Y(s,"button",{type:"button",className:"gs-recovery__primary",textContent:c.get}),p=Y(s,"p",{className:"gs-recovery__error",hidden:!0});p.setAttribute("role","alert"),v.addEventListener("click",async()=>{v.disabled=!0,p.hidden=!0;try{let R=await e.client.issueRecoveryCode();b.textContent=R.code,b.hidden=!1,T.hidden=!1,f.hidden=typeof navigator.share!="function",v.hidden=!0}catch{p.textContent=c.issueFailed,p.hidden=!1,v.disabled=!1}}),T.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(b.textContent??""),l.textContent=c.copied}catch{l.textContent=""}}),f.addEventListener("click",async()=>{try{await navigator.share({text:b.textContent??""})}catch{}});let C=Y(s,"h2",{textContent:c.enterTitle}),S=Y(s,"form");S.noValidate=!0;let _=Y(s,"label",{htmlFor:"gs-recovery-input",textContent:c.enterTitle});_.hidden=!0;let x=Y(s,"input",{id:"gs-recovery-input",type:"text",placeholder:"four words and two numbers"});x.setAttribute("inputmode","text"),x.setAttribute("autocomplete","off"),x.setAttribute("autocorrect","off"),x.setAttribute("autocapitalize","none"),x.setAttribute("spellcheck","false"),x.setAttribute("enterkeyhint","go");let w=Y(s,"p",{className:"gs-recovery__error",id:"gs-recovery-error",hidden:!0});w.setAttribute("role","alert");let h=Y(s,"button",{type:"submit",className:"gs-recovery__primary",textContent:c.submit});S.addEventListener("submit",async R=>{R.preventDefault();let k=x.value.trim();if(!k)return;let H=k;h.disabled=!0,w.hidden=!0,x.removeAttribute("aria-invalid");try{await e.client.restoreFromRecoveryCode(H),l.textContent=c.restored,w.hidden=!0,S.replaceChildren(Y(s,"p",{textContent:c.restored})),await n.onRestored?.()}catch{w.textContent=c.notRecognised,w.hidden=!1,x.setAttribute("aria-invalid","true"),x.setAttribute("aria-describedby","gs-recovery-error"),h.disabled=!1}}),S.append(_,x,w,h);let N=Y(s,"button",{type:"button",textContent:c.close});N.addEventListener("click",()=>i.close()),u.append(y,Y(s,"p",{textContent:c.showDetail}),v,b,Y(s,"div",{className:"gs-recovery__row"},T,f),l,Y(s,"p",{className:"gs-recovery__note",textContent:`${c.private} ${c.replace}`}),p,Y(s,"hr"),C,Y(s,"p",{textContent:c.enterDetail}),S,Y(s,"div",{className:"gs-recovery__row"},N)),i.replaceChildren(u)}let d=()=>{a(),i.showModal()};r.addEventListener("click",d);let g=e.onPresentationChanged?.(()=>{r.textContent=o().open});return()=>{r.removeEventListener("click",d),g?.(),r.remove(),i.remove()}}St();function In(e){let t=[],n=/\\[([^\\]]*)\\]/g,s=0;for(let o of e.matchAll(n))o.index>s&&t.push({text:e.slice(s,o.index),accent:!1}),o[1]&&t.push({text:o[1],accent:!0}),s=o.index+o[0].length;return s<e.length&&t.push({text:e.slice(s),accent:!1}),t.filter(o=>o.text.length>0)}function Gs(e){return In(e).map(t=>t.text).join("")}var Lc=["displayName","strapline","howToPlay","playButtonLabel","playAgainLabel","resultButtonLabel","shareButtonLabel","editionName","editionStrapline"];function Dc(e,t={},n={}){let s=t.document??globalThis.document??void 0,o=e.displayName||n.displayName||void 0;for(let c of Lc){let u=c==="displayName"?o:e[c],y=t[c];if(y){if(!u){$c(y);continue}Jt.has(y)?Jt.get(y).wrote=u:Jt.set(y,{text:y.textContent??"",hidden:y.hasAttribute?.("hidden")??!1,wrote:u}),y.textContent=u,y.removeAttribute("hidden")}}if(s)if(o)Qt.has(s)?Qt.get(s).wrote=o:Qt.set(s,{before:s.title,wrote:o}),s.title=o;else{let c=Qt.get(s);c&&s.title===c.wrote&&(s.title=c.before),Qt.delete(s)}let r=t.root??s?.documentElement??null;if(!r)return;let i={};if(e.primaryColour&&(i["--gamestage-primary"]=e.primaryColour,Object.assign(i,ci(e.primaryColour))),e.cssVariables){for(let[u,y]of Object.entries(e.cssVariables))y&&(i[`--gs-${u}`]=y);let c=e.cssVariables.highlightMainColour;c&&Object.assign(i,ci(c)),Object.assign(i,yi(e.cssVariables));for(let u of jc){let y=Bt(e.cssVariables[u],e.uploadedFonts??[]);y&&(i[`--gs-${u}`]=y.family)}}let a=_i(e);Object.assign(i,a.vars),Fc(s,a);let d=Bt(e.defaultFontFamily,e.uploadedFonts??[]);d&&(i["--gs-font-default"]=`"${d.family}", system-ui, sans-serif`),s&&Yc(s,e.uploadedFonts),s&&Bc(s,e),e.logoAccentColour&&(i["--gs-title-accent"]=e.logoAccentColour),s&&Zc(s,e.logoText,o),s&&ed(s,e,o),s&&Fs(s,e.logoText,o);let g=ai.get(r)??new Set;for(let c of g)c in i||r.style.removeProperty(c);for(let[c,u]of Object.entries(i))r.style.setProperty(c,u);ai.set(r,new Set(Object.keys(i)))}var ai=new WeakMap,Jt=new WeakMap,Qt=new WeakMap;function $c(e){let t=Jt.get(e);t&&(Jt.delete(e),e.textContent===t.wrote&&(e.textContent=t.text,t.hidden&&e.setAttribute?.("hidden","")))}var Gc={backgroundMainColour:["background"],onBackgroundColour:["ink"],backgroundContainerColour:["surface"],highlightMainColour:["interactive"],highlightVariantColour:["interactive-base"],onHighlightColour:["on-accent"],positiveMainColour:["positive"],positiveVariantColour:["positive-base"],negativeMainColour:["negative"],negativeVariantColour:["negative-base"],secondaryMainColour:["selected"],tertiaryMainColour:["reward"]};function yi(e){let t={};for(let[n,s]of Object.entries(Gc)){let o=e[n];if(o)for(let r of s)t[`--gs-color-${r}`]=o,t[`--gs-color-${r}-solid`]=o}return t}function ci(e){let t={},n=(o,r)=>{t[`--gs-color-${o}`]=r,t[`--gs-color-${o}-solid`]=r};n("interactive",e),n("interactive-hover",`color-mix(in oklab, ${e} 82%, white)`),n("interactive-base",`color-mix(in oklab, ${e} 68%, black)`);let s=Uc(e);return s!==void 0&&n("on-accent",s>.4?"#111111":"#ffffff"),t}function Uc(e){let t=e.trim(),n,s=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(s){let a=s[1].length===3?s[1].split("").map(d=>d+d).join(""):s[1];n=[0,2,4].map(d=>parseInt(a.slice(d,d+2),16))}else{let a=/^rgba?\\(\\s*(\\d+)[\\s,]+(\\d+)[\\s,]+(\\d+)/i.exec(t);a&&(n=a.slice(1,4).map(Number))}if(!n)return;let[o,r,i]=n.map(a=>{let d=a/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*i}var bi="[data-gamestage-title], :root:not(:has([data-gamestage-title])) h1";function _i(e){let t={},n=[],s,o=e.cssVariables??{},r=o.fontTitleFamily??e.titleFont,i=o.fontTitleWeight??e.titleFontWeight,a=o.fontTitleTracking??e.titleLetterSpacing,d=o.fontTitleCase??e.titleCase,g=Bt(r,e.uploadedFonts??[]);if(g){t["--gs-title-font"]=`"${g.family}", var(--gs-font-display, system-ui), sans-serif`,n.push("font-family: var(--gs-title-font)");let b=g.stylesheetHref?xr(r,i)?.weight:i;b!==void 0&&b!==""&&(t["--gs-title-weight"]=String(b),n.push("font-weight: var(--gs-title-weight)")),s=g.stylesheetHref}let c=kr(a);c&&(t["--gs-title-tracking"]=c,n.push("letter-spacing: var(--gs-title-tracking)"));let u=Or(d);u&&(t["--gs-title-case"]=u,n.push("text-transform: var(--gs-title-case)")),e.titleColour&&(t["--gs-title-colour"]=e.titleColour,n.push("color: var(--gs-title-colour)"));let y=n.length?`${bi} { ${n.join("; ")}; }`:"";return e.logoText&&(y+=`${y?" ":""}.gamestage-title-accent { color: var(--gs-title-accent, inherit); }`),{vars:t,css:y,fontHref:s}}var di="gamestage-title-style",li="gamestage-title-font";function Fc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=e.getElementById(di);if(t.css?(n||(n=e.createElement("style"),n.id=di,e.head.appendChild(n)),n.textContent!==t.css&&(n.textContent=t.css)):n?.remove(),!t.fontHref){e.getElementById(li)?.remove();return}Si(e,li,t.fontHref)}var ui="gamestage-font-preconnect",gi="gamestage-role-font-",vi=["fontBodyFamily","fontNumberFamily","fontCTAFamily","fontLabelFamily","fontHighlightFamily"],jc=["fontTitleFamily",...vi];function qc(e){if(e.getElementById(ui))return;let t=e.createElement("link");t.id=ui,t.rel="preconnect",t.href=ms,t.crossOrigin="anonymous",e.head.appendChild(t)}function Si(e,t,n){qc(e);let s=e.getElementById(t);s&&s.href===n||(s||(s=e.createElement("link"),s.id=t,s.rel="stylesheet",e.head.appendChild(s)),s.media="print",s.onload=()=>{s&&(s.media="all")},s.href=n)}function Bc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=t.cssVariables??{},s=t.uploadedFonts??[],o=new Map,r=[t.defaultFontFamily,...vi.map(i=>n[i])];for(let i of r){let a=Bt(i,s);if(!a?.stylesheetHref)continue;let d=a.family.toLowerCase().replace(/[^a-z0-9]+/g,"-");o.set(`${gi}${d}`,a.stylesheetHref)}for(let i of Array.from(e.head.children)){let a=i.id;i.tagName==="LINK"&&a.startsWith(gi)&&!o.has(a)&&i.remove()}for(let[i,a]of o)Si(e,i,a)}var fi="gamestage-font-faces",pi="gamestage-font-preload-",zc={woff2:"woff2",woff:"woff",ttf:"truetype",otf:"opentype"};function Hc(e){let t=e.trim();return!/^(https:)?\\/\\//i.test(t)||/["\'()\\\\\\s<>{}]/.test(t)?null:t}function Vc(e){let t=e.split(/[?#]/)[0]?.split(".").pop()?.toLowerCase();return t?zc[t]:void 0}function Kc(e){let t=[],n=new Set;for(let s of e??[]){let o=hs(s.name??""),r=Hc(s.url??"");if(!o||!r)continue;let i=o.toLowerCase().replace(/[^a-z0-9]+/g,"-");if(n.has(i))continue;n.add(i);let a=String(s.weight??"").trim();t.push({family:o,url:r,weight:/^\\d{2,4}$/.test(a)?a:"400",slug:i})}return t}function Wc(e){let t=Vc(e.url),n=t?`url("${e.url}") format("${t}")`:`url("${e.url}")`;return`@font-face { font-family: "${e.family}"; src: ${n}; font-weight: ${e.weight}; font-display: swap; }`}function Yc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=Kc(t),s=e.getElementById(fi);if(!n.length)s?.remove();else{let r=n.map(Wc).join(" ");s||(s=e.createElement("style"),s.id=fi,e.head.appendChild(s)),s.textContent!==r&&(s.textContent=r)}let o=new Map(n.map(r=>[`${pi}${r.slug}`,r]));for(let r of Array.from(e.head.children)){let i=r.id;r.tagName==="LINK"&&i.startsWith(pi)&&!o.has(i)&&r.remove()}for(let[r,i]of o){if(e.getElementById(r))continue;let a=e.createElement("link");a.id=r,a.rel="preload",a.as="font",a.href=i.url,a.crossOrigin="anonymous",e.head.appendChild(a)}}var Xt=new WeakMap,ze="data-gamestage-logo",Qc="gamestage-title-accent";function wi(e,t,n){let s=Array.from(e.querySelectorAll("[data-gamestage-title]"));if(s.length)return s;let o=new Set([t,Gs(n)].filter(Boolean).map(r=>r.trim().toLowerCase()));return Array.from(e.querySelectorAll("h1")).filter(r=>r.hasAttribute(ze)||o.has((r.textContent??"").trim().toLowerCase()))}function mi(e){let t=Xt.get(e);if(t?.text){for(let n of wi(e,t.name,t.text)){if(n.getAttribute(ze)===t.text&&n.textContent===Gs(t.text))continue;let s=In(t.text).map(o=>{if(!o.accent)return e.createTextNode(o.text);let r=e.createElement("span");return r.className=Qc,r.textContent=o.text,r});n.replaceChildren(...s),n.setAttribute(ze,t.text),t.name&&n.setAttribute("aria-label",t.name)}Fs(e,t.text,t.name)}}var Jc=20,Us="data-gamestage-fit",hi=new WeakSet;function Fs(e,t,n){if(typeof e.querySelectorAll!="function")return;let s=e.defaultView;if(!s||typeof s.getComputedStyle!="function")return;let o=t?.trim()||n;if(o){for(let r of wi(e,n,o))Xc(r,s);if(!hi.has(e)){hi.add(e);let r=()=>{let i=Xt.get(e);Fs(e,i?.text,i?.name??n)};s.addEventListener?.("resize",r),e.fonts?.addEventListener?.("loadingdone",r),e.fonts?.ready?.then(r)}}}function Xc(e,t){if(!e.style)return;e.hasAttribute(Us)&&(e.style.removeProperty("font-size"),e.style.removeProperty("white-space"),e.style.removeProperty("overflow-wrap"),e.removeAttribute(Us));let n=e.clientWidth;if(!n)return;let s=e.style.whiteSpace;e.style.whiteSpace="nowrap";let o=e.scrollWidth;if(o<=n){e.style.whiteSpace=s;return}let r=parseFloat(t.getComputedStyle(e).fontSize);e.style.fontSize=`${Math.max(Jc,Math.floor(r*n/o*.97))}px`,e.setAttribute(Us,""),e.scrollWidth>n?(e.style.whiteSpace="normal",e.style.overflowWrap="anywhere"):e.style.whiteSpace=s}function Zc(e,t,n){if(typeof e.querySelectorAll!="function")return;let s=Xt.get(e)??{},o=t?.trim()||void 0;if(!o){if(s.text)for(let i of Array.from(e.querySelectorAll(`[${ze}]`)))i.removeAttribute(ze),i.removeAttribute("aria-label"),n&&(i.textContent=n);s.observer?.disconnect(),Xt.set(e,{name:n});return}if(s.text!==o)for(let i of Array.from(e.querySelectorAll(`[${ze}]`)))i.removeAttribute(ze);s.text=o,s.name=n,Xt.set(e,s),mi(e);let r=e.defaultView;if(!s.observer&&r?.MutationObserver&&e.body){let i=!1;s.observer=new r.MutationObserver(()=>{i||(i=!0,queueMicrotask(()=>{i=!1,mi(e)}))}),s.observer.observe(e.body,{childList:!0,subtree:!0,characterData:!0})}}function ed(e,t,n){let s=e.defaultView,o=s?.gamestageSplash;if(!o?.update)return;let r=t.cssVariables??{};o.update({start:t.splashGradientStart||r.backgroundMainColour,end:t.splashGradientEnd||r.backgroundContainerColour,ink:t.titleColour,accent:t.logoAccentColour,play:t.splashPlayLabel,resume:t.splashContinueLabel,error:t.splashErrorText,retry:t.splashRetryLabel});let i=e.querySelector(".gs-boot__logo"),a=()=>s?.gamestageSplash?.fit?.(),d=t.logoText?.trim()||n;i&&d&&i.getAttribute(ze)!==d&&(i.replaceChildren(...In(d).map(g=>{if(!g.accent)return e.createTextNode(g.text);let c=e.createElement("span");return c.className="gs-boot__accent",c.textContent=g.text,c})),i.setAttribute(ze,d),n&&i.setAttribute("aria-label",n),a())}ds();var td="US1 1 10;AG1 1 10;AI1 1 10;AS1 1 10;BB1 1 10;BM1 1 10;BS1 1 10;CA1 1 10;DM1 1 10;DO1 1 10;GD1 1 10;GU1 1 10;JM1 1 10;KN1 1 10;KY1 1 10;LC1 1 10;MP1 1 10;MS1 1 10;PR1 1 10;SX1 1 10;TC1 1 10;TT1 1 10;VC1 1 10;VG1 1 10;VI1 1 10;RU7 8 10;KZ7 8 10;EG20 0 10;ZA27 0 5.6.7.8.9;GR30 0 10;NL31 0 9.11;BE32 0 9;FR33 0 9;ES34 0 9;HU36 06 9;IT39 0 9.10;VA39 0 9.10;RO40 0 9;CH41 0 9;AT43 0 7.8.9.10.11.12.13;GB44 0 10;GG44 0 10;IM44 0 10;JE44 0 10;DK45 0 8;SE46 0 9;NO47 0 8;SJ47 0 8;PL48 0 9;DE49 0 10.11;PE51 0 9;MX52 0 10;CU53 0 8;AR54 0 10.11;BR55 0 10.11;CL56 0 9;CO57 0 10;VE58 0 10;MY60 0 9.10;AU61 0 9;CC61 0 9;CX61 0 9;ID62 0 9.10.11.12;PH63 0 10;NZ64 0 8.9.10;SG65 0 8;TH66 0 9;JP81 0 10;KR82 0 9.10;VN84 0 9;CN86 0 11;TR90 0 10;IN91 0 10;PK92 0 10;AF93 0 9;LK94 0 9;MM95 0 7.8.9.10;IR98 0 10;SS211 0 9;MA212 0 9;EH212 0 9;DZ213 0 9;TN216 0 8;LY218 0 9;GM220 0 7.9;SN221 0 9;MR222 0 8;ML223 0 8;GN224 0 9;CI225 10;BF226 0 8;NE227 0 8;TG228 0 8;BJ229 10;MU230 0 8;LR231 0 7.9;SL232 0 8;GH233 0 9;NG234 0 10;TD235 0 8;CF236 0 8;CM237 0 9;CV238 0 7;ST239 0 7;GQ240 0 9;GA241 7.8;CG242 9;CD243 0 7.9;AO244 0 9;GW245 0 9;IO246 0 7;AC247 0 5;SC248 0 7;SD249 0 9;RW250 0 9;ET251 0 9;SO252 0 7.8.9;DJ253 0 8;KE254 0 9;TZ255 0 9;UG256 0 9;BI257 0 8;MZ258 0 9;ZM260 0 9;MG261 0 9;RE262 0 9;YT262 0 9;ZW263 0 9;NA264 0 9;MW265 0 9;LS266 0 8;BW267 0 8;SZ268 0 8;KM269 0 7;SH290 0 5;TA290 0 4;ER291 0 7;AW297 0 7;FO298 0 6;GL299 0 6;GI350 0 8;PT351 0 9;LU352 0 9;IE353 0 9;IS354 0 7.9;AL355 0 9;MT356 0 8;CY357 0 8;FI358 0 6.7.8.9.10;AX358 0 6.7.8.9.10;BG359 0 8.9;LT370 0 8;LV371 0 8;EE372 0 7.8;MD373 0 8;AM374 0 8;BY375 8 9;AD376 0 6.9;MC377 0 8.9;SM378 0 8;UA380 0 9;RS381 0 8.9.10;ME382 0 8;XK383 0 8;HR385 0 8.9;SI386 0 8;BA387 0 8.9;MK389 0 8;CZ420 0 9;SK421 0 9;LI423 0 7.9;FK500 0 5;BZ501 0 7;GT502 0 8;SV503 0 8;HN504 0 8;NI505 0 8;CR506 0 8;PA507 0 7.8;PM508 0 6.9;HT509 0 8;GP590 0 9;BL590 0 9;MF590 0 9;BO591 0 8;GY592 0 7;EC593 0 9;GF594 0 9;PY595 0 9;MQ596 0 9;SR597 0 7;UY598 0 8;CW599 0 7.8;BQ599 0 7;TL670 0 8;NF672 0 6;BN673 0 7;NR674 0 7;PG675 0 8;TO676 0 7;SB677 0 5.7;VU678 0 7;FJ679 0 7;PW680 0 7;WF681 0 6;CK682 0 5;NU683 0 4.7;WS685 0 7.10;KI686 0 8;NC687 0 6;TV688 0 6.7;PF689 0 8;TK690 0 4.5.6.7;FM691 0 7;MH692 1 7;KP850 0 10;HK852 0 8;MO853 0 8;KH855 0 8.9;LA856 0 9.10;BD880 0 10;TW886 0 9;MV960 0 7;LB961 0 7.8;JO962 0 9;SY963 0 9;IQ964 0 10;KW965 0 8;SA966 0 9;YE967 0 9;OM968 0 8;PS970 0 9;AE971 0 9;IL972 0 9;BH973 0 8;QA974 0 8;BT975 0 8;MN976 0 8;NP977 0 10;TJ992 0 9;TM993 8 8;AZ994 0 9;GE995 0 9;KG996 0 9;UZ998 0 9",Nn=td.split(";").map(e=>{let[t,n,s]=e.split(" ");return[t.slice(0,2),t.slice(2),n,s.split(".").map(Number)]});var Zt=new Map(Nn.map(e=>[e[0],e])),nd="GB",sd=`\n.gs-notify-form [hidden]{display:none!important}\n:where(.gs-notify-field){display:grid;gap:12px}\n:where(.gs-notify-via){display:flex;gap:4px;margin:0;padding:4px;border:0;border-radius:10px;background:var(--bg,#fff)}\n:where(.gs-notify-via legend){position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}\n:where(.gs-notify-via label){flex:1;display:block;position:relative;cursor:pointer}\n:where(.gs-notify-via input){position:absolute;inset:0;margin:0;opacity:0;cursor:pointer}\n:where(.gs-notify-via span){display:block;padding:10px 12px;border-radius:8px;text-align:center;font-weight:600}\n:where(.gs-notify-via input:checked+span){background:var(--text,#222);color:var(--bg,#fff)}\n:where(.gs-notify-via input:focus-visible+span){outline:3px solid var(--text,#222);outline-offset:2px}\n:where(.gs-notify-phone){display:flex;gap:8px}\n:where(.gs-notify-country){position:relative;flex:none;display:flex;align-items:center;gap:6px;min-height:48px;padding:0 12px;border-radius:10px;background:var(--bg,#fff);white-space:nowrap}\n:where(.gs-notify-country)::after{content:"";width:7px;height:7px;margin:-4px 0 0 2px;border:solid currentColor;border-width:0 2px 2px 0;transform:rotate(45deg)}\n:where(.gs-notify-country select){position:absolute;inset:0;width:100%;opacity:0;cursor:pointer;font:inherit}\n:where(.gs-notify-country:focus-within){outline:3px solid var(--text,#222);outline-offset:3px}\n:where(.gs-notify-phone input){flex:1}\n.gs-notify-form .gs-notify-secondary{min-height:48px;padding:12px 20px;border:1.5px solid currentColor;border-radius:10px;background:transparent;color:inherit;font:inherit;font-weight:600;cursor:pointer}\n.gs-notify-form .gs-notify-secondary:disabled{opacity:.55;cursor:default}\n.gs-notify-form .gs-notify-link{min-height:0;padding:4px 0;border:0;background:none;color:inherit;font:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;justify-self:start}\n:where(.gs-notify-confirm){margin-top:16px}\n:where(.gs-notify-confirm input[name=code]){letter-spacing:.3em;font-variant-numeric:tabular-nums;max-width:12ch}\n:where(.gs-notify-error){margin:0;color:var(--gs-errorColour,#b3261e);font-weight:600}\n`;function od(e){let t;try{t=new Intl.DisplayNames([e],{type:"region"})}catch{}return Nn.map(([n,s])=>({code:n,name:t?.of(n)??n,dial:`+${s}`})).sort((n,s)=>n.name.localeCompare(s.name,e))}function rd(e){return String.fromCodePoint(...[...e].map(t=>127397+t.charCodeAt(0)))}function id(){let e=typeof navigator>"u"?[]:[...navigator.languages??[],navigator.language];for(let t of e){let n=t?.split("-").slice(1).find(s=>/^[A-Za-z]{2}$/.test(s))?.toUpperCase();if(n&&Zt.has(n))return n}return nd}function Ei(e,t){let n=Zt.get(t);return n&&e.startsWith(n[1])?t:Nn.find(([,s])=>e.startsWith(s))?.[0]}function js(e,t){let n=e.trim().replace(/^00/,"+"),s=n.replace(/\\D/g,""),o=Zt.get(t);if(n.startsWith("+")){let c=Ei(s,t);if(o=c?Zt.get(c):void 0,!o)return;s=s.slice(o[1].length)}else if(!o)return;let[,r,i,a]=o,d=c=>a.includes(c.length);i&&s.startsWith(i)?s=s.slice(i.length):!n.startsWith("+")&&s.startsWith(r)&&!d(s)&&d(s.slice(r.length))&&(s=s.slice(r.length));let g=`+${r}${s}`;return d(s)&&wn(g,"sms")?g:void 0}function ad(e,t){let n=!1,s=!1,o="",r=typeof navigator>"u"?"en-GB":navigator.language||"en-GB",i,a=new Map,d,g=()=>{d!==void 0&&clearInterval(d),d=void 0},c=(f,l)=>{let v=f?.status??0,p=f?.message;return v>=400&&v<500&&p?p:l};if(typeof document<"u"&&document.head&&!document.head.querySelector?.("style[data-gs-notify]")){let f=document.createElement("style");f.setAttribute("data-gs-notify",""),f.textContent=sd,document.head.append(f)}let u=()=>{if(s)return;let f=e.round?.id??"",l=a.get(f)??{email:"",phone:"",country:id(),message:"",pending:!1,saved:!1};a.set(f,l);let v=e.presentation.notify,p=JSON.stringify([f,n,v,l.message,l.pending,l.saved,l.awaiting]);if(p===o)return;o=p;let C=t.contains?.(document.activeElement),S=C?document.activeElement?.name:void 0;if(t.hidden=!n||!v?.enabled||!v.ownerName||!/^https:\\/\\//.test(v.privacyUrl)||!v.channels.length,t.replaceChildren(),t.hidden||!v)return;let _=v.labels,x=v.channels.includes("sms")?"sms":v.channels.includes("rcs")?"rcs":void 0,w=v.channels.includes("email");(!l.channel||(l.channel==="email"?!w:!x))&&(l.channel=x?"phone":"email");let h=(A,U)=>{let X=document.createElement(A);return U&&(X.textContent=U),X},N=t.id||"gs-notify",R=h("h2",_.title);R.id=`${N}-title`,t.setAttribute("aria-labelledby",R.id);let k=h("p");if(k.setAttribute("role","status"),k.hidden=!0,t.append(R,k),g(),l.saved){k.textContent=_.success,k.hidden=!1,C&&(k.tabIndex=-1,k.focus());return}if(l.awaiting){let A=l.awaiting,U=A.channel!=="email";k.textContent=A.note||A.sent,k.hidden=!1;let X=h("form");X.className="gs-notify-form gs-notify-confirm",X.noValidate=!0;let Z=h("input"),te=h("p");if(U){Z.name="code",Z.id=`${N}-code`,Z.autocomplete="one-time-code",Z.inputMode="numeric",Z.maxLength=6,Z.value=A.code,te.id=`${N}-code-error`,te.className="gs-notify-error",te.textContent=A.error,te.hidden=!A.error,Z.setAttribute("aria-describedby",te.id),A.error&&Z.setAttribute("aria-invalid","true");let se=h("label",_.code);se.append(Z);let m=h("div");m.className="gs-notify-field",m.append(se,te);let O=h("button",A.busy?_.pending:_.confirm);O.type="submit",O.disabled=A.busy,X.append(m,O),Z.oninput=()=>{A.code=Z.value.replace(/\\D/g,"").slice(0,6),Z.value!==A.code&&(Z.value=A.code),A.code.length===6&&!A.busy&&yn()}}let ne=h("button");ne.type="button",ne.className="gs-notify-secondary";let Ft=()=>{let se=Math.ceil((A.resendAt-Date.now())/1e3);ne.disabled=se>0||A.busy,ne.textContent=se>0?_.resend_wait.replaceAll("{seconds}",String(se)):U?_.resend_code:_.resend_email,se<=0&&g()};Ft(),A.resendAt>Date.now()&&(d=setInterval(Ft,1e3),d.unref?.());let yt=h("button",_.change_address);yt.type="button",yt.className="gs-notify-link",yt.onclick=()=>{l.awaiting=void 0,l.message="",u()},X.append(ne,yt),t.append(X),U&&C&&Z.focus();let yn=async()=>{if(A.busy||A.code.length!==6){A.code.length!==6&&(A.error=_.code_incomplete,u());return}A.busy=!0,A.error="",u();try{if(await e.client.confirmNotify({roundId:f,channel:A.channel,address:A.address,code:A.code}),s)return;l.awaiting=void 0,l.saved=!0}catch(se){A.error=c(se,_.error),A.code=""}finally{A.busy=!1,!s&&e.round?.id===f&&u()}};X.onsubmit=se=>{se.preventDefault(),yn()},ne.onclick=async()=>{A.busy=!0,u();try{let se=await e.client.resendNotify({roundId:f,channel:A.channel,address:A.address});if(se.status==="confirmed"){l.awaiting=void 0,l.saved=!0;return}A.resendAt=Date.now()+(se.resendAfterSeconds??60)*1e3,A.note=_.resent,A.error=""}catch(se){let m=Number(se.detail?.retryAfterSeconds);Number.isFinite(m)&&m>0&&(A.resendAt=Date.now()+m*1e3),A.note=c(se,_.error)}finally{A.busy=!1,!s&&e.round?.id===f&&u()}};return}let H=h("form");H.className="gs-notify-form",H.noValidate=!0;let ue=new Map,be=A=>{let U=ue.get(A);U&&(U.hidden=!0,U.textContent=""),A.removeAttribute("aria-invalid")},$=h("input");$.type="email",$.name="email",$.autocomplete="email",$.inputMode="email",$.maxLength=254,$.value=l.email,$.oninput=()=>{l.email=$.value,wn($.value.trim(),"email")&&be($)};let ge=(A,U)=>{let X=h("p");return X.id=`${N}-${U}-error`,X.className="gs-notify-error",X.hidden=!0,A.setAttribute("aria-describedby",X.id),ue.set(A,X),X},_e=ge($,"email"),P=h("label",_.email_address);P.append($);let I=h("div");I.className="gs-notify-field",I.append(P,_e),i??=od(r);let G=h("select");G.name="country",G.setAttribute("aria-label",_.country);for(let A of i){let U=h("option",`${A.name} (${A.dial})`);U.value=A.code,U.selected=A.code===l.country,G.append(U)}G.value=l.country;let j=h("span");j.setAttribute("aria-hidden","true");let D=()=>{j.textContent=`${rd(l.country)} +${Zt.get(l.country)?.[1]??""}`};D();let V=h("span");V.className="gs-notify-country",V.append(j,G);let M=h("input");M.type="tel",M.name="phone",M.id=`${N}-phone`,M.autocomplete="tel",M.inputMode="tel",M.maxLength=24,M.value=l.phone,M.oninput=()=>{let A=M.value.trim().replace(/^00/,"+"),U=A.startsWith("+")?Ei(A.replace(/\\D/g,""),l.country):void 0;U&&U!==l.country&&(l.country=U,G.value=U,D()),l.phone=M.value,js(M.value,l.country)&&be(M)},G.onchange=()=>{l.country=G.value,D(),js(M.value,l.country)&&be(M),M.focus?.()};let oe=h("label",_.mobile_number);oe.htmlFor=M.id;let q=h("div");q.className="gs-notify-phone",q.append(V,M);let K=h("div");K.className="gs-notify-field";let Oe=ge(M,"phone");K.append(oe,q,Oe);let re=()=>{be($),be(M)},Le=()=>{I.hidden=l.channel!=="email",K.hidden=l.channel!=="phone"};if(w&&x){let A=h("fieldset");A.className="gs-notify-via",A.append(h("legend",_.via));for(let[U,X]of[["phone",_.sms],["email",_.email]]){let Z=h("label"),te=h("input");te.type="radio",te.name=`${N}-via`,te.value=U,te.checked=l.channel===U,te.onchange=()=>{l.channel=U,l.message="",k.hidden=!0,re(),Le()},Z.append(te,h("span",X)),A.append(Z)}H.append(A)}Le();let Ee=h("p",_.consent.replaceAll("{brand}",v.ownerName)+" "),De=h("a",_.privacy);De.href=v.privacyUrl,De.target="_blank",De.rel="noopener noreferrer",Ee.append(De);let ve=h("button",l.pending?_.pending:_.button);ve.disabled=l.pending,ve.type="submit",H.append(I,K,Ee,ve),t.append(H),k.textContent=l.message,k.hidden=!l.message,(S==="email"||S==="phone")&&(S==="email"?$:M).focus(),H.onsubmit=async A=>{if(A.preventDefault(),l.pending||!e.round||e.round.id!==f)return;l.email=$.value,l.phone=M.value;let U=l.channel==="email",X=U?$:M,Z=U?$.value.trim():js(M.value,l.country),te=U?"email":x;if(re(),!te||!Z||!wn(Z,te)){let ne=U?_e:Oe;ne.textContent=U?_.invalid_email:_.invalid_mobile,ne.hidden=!1,X.setAttribute("aria-invalid","true"),X.focus?.();return}k.hidden=!1,l.pending=!0,o="",ve.disabled=!0,ve.textContent=_.pending,k.textContent="",l.message="";try{let ne=await e.client.subscribeNotify({roundId:f,channel:te,address:Z,consent:{wording:v.wording,termsVersion:v.termsVersion}});if(s)return;["subscribed","already_subscribed"].includes(ne.status)?l.saved=!0:ne.status==="pending_confirmation"?l.awaiting={channel:te,address:Z,sent:ne.fanMessage,code:"",error:"",note:"",busy:!1,resendAt:Date.now()+(ne.resendAfterSeconds??60)*1e3}:l.message=ne.fanMessage}catch(ne){l.message=c(ne,_.error)}finally{l.pending=!1,!s&&e.round?.id===f&&u()}}},y=async()=>{if(s||typeof document>"u"||document.visibilityState!=="visible")return;let f=e.round?.id??"",l=a.get(f),v=l?.awaiting,p=e.presentation.notify;if(!(!l||!v||v.channel!=="email"||v.busy||!p))try{let C=await e.client.subscribeNotify({roundId:f,channel:v.channel,address:v.address,consent:{wording:p.wording,termsVersion:p.termsVersion}});!s&&["subscribed","already_subscribed"].includes(C.status)&&l.awaiting===v&&(l.awaiting=void 0,l.saved=!0,u())}catch{}};typeof document<"u"&&document.addEventListener?.("visibilitychange",y);let b=e.onRoundChanged(()=>{n=!1,u()}),T=e.onPresentationChanged(u);return u(),{update(f){n=f?.finished===!0&&f.outcome==="pending",u()},destroy(){s=!0,g(),b(),T(),typeof document<"u"&&document.removeEventListener?.("visibilitychange",y),t.replaceChildren(),t.hidden=!0}}}var $l=new Set(["comment"]);function $a(e){let n=e.outcome==="accepted"||e.outcome==="duplicate"?e.round_state?.progress?.guesses?.at(-1):void 0;return n?{...e,guessed:n}:e}function Ef(e,t){if(!t?.finished||t.outcome!=="won"||!e||e.plays<2)return null;let n=t.progress?.guesses;if(!Array.isArray(n)||n.length===0)return null;let s=n.length,o=0;for(let[r,i]of Object.entries(e.pick_shares??{}))typeof i!="number"||!(i>0)||(r==="X"||/^\\d+$/.test(r)&&Number(r)>s)&&(o+=i);return Math.max(0,Math.min(100,Math.round(o*100)))}function Gl(e){let t=e.GAMESTAGE_API,n=e.GAMESTAGE_GAME;if(!t||!n)throw new Error("This game has no Gamestage configuration. `window.GAMESTAGE_API` and `window.GAMESTAGE_GAME` are written by `gamestage deploy` and printed by `gamestage dev`.");return{api:t,game:n}}function hn(e,t){let n=new URLSearchParams(t??""),s=o=>{let r=n.get(o);return r&&r.trim()?r.trim():void 0};return{host:s("h")??e.GAMESTAGE_IC_HOST,projectId:s("p")??e.GAMESTAGE_IC_PROJECT,eventId:s("e")??e.GAMESTAGE_IC_EVENT,locale:s("locale")??e.GAMESTAGE_LOCALE,theme:s("theme")??e.GAMESTAGE_THEME}}function Ho(e,t=globalThis.navigator){let n=e.locale??t?.languages?.[0]??t?.language;return n&&n.trim().split(/[-_]/)[0].toLowerCase()||void 0}var Ga=3e4;async function Ul(e,t,n){let s=`${e.replace(/\\/+$/,"")}/public/v1/platform/${encodeURIComponent(t)}`;try{let o=AbortSignal.timeout?AbortSignal.timeout(Ga):void 0,r=await n(s,o?{signal:o}:void 0);if(!r.ok)return{because:r.status===404?`${t} is not on Interaction Cloud: the control plane answered 404.`:`asking for this game\'s platform ids answered ${r.status}.`};let i=await r.json(),a=typeof i.project=="string"?i.project:void 0,d=typeof i.host=="string"?i.host:void 0,g=typeof i.name=="string"&&i.name.trim()?i.name:void 0;if(!a||!d)return{because:"the control plane answered without both a project and a host, so there is nothing connectable to use."};let c=typeof i.analytics_url=="string"&&/^https:\\/\\//.test(i.analytics_url)?i.analytics_url:void 0,u=i.services?.comments,y=typeof u?.topic_id=="string"&&typeof u.api=="string"&&/^https:\\/\\//.test(u.api)?{topicId:u.topic_id,api:u.api}:void 0;return{host:d,projectId:a,name:g,analyticsUrl:c,comments:y}}catch(o){return{because:o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?`the control plane did not answer within ${Ga/1e3}s, so this page is playing the round without a Studio connection. A producer\'s words and live updates will reach the next load.`:`asking for this game\'s platform ids failed: ${o instanceof Error?o.message:String(o)}`}}}async function Fl(e,t,n){let s=hn(e,t),o=s.host,r=s.projectId,i=s.eventId,a,d,g,c;if((!o||!r)&&e.GAMESTAGE_IC_LOOKUP&&n?.api&&n?.game){n?.step?.("looking-up");let u=await Ul(n.api,n.game,n.fetch??fetch);o??=u.host,r??=u.projectId,d=u.name,g=u.analyticsUrl,c=u.comments,a=u.because}else(!o||!r)&&e.GAMESTAGE_IC_LOOKUP&&(a="this page carries no Interaction Cloud ids and no API to ask for them.");if((!o||!r)&&e.GAMESTAGE_IC_LOOKUP)throw new Error(a??"this game could not reach Interaction Cloud and there is no reason recorded.");return!o||!r?{deployedName:d,projectId:r,platform:Rs({pollMilliseconds:5e3,offPlatformReason:a,...typeof e.GAMESTAGE_LIVE_SOURCE=="string"?{liveSource:e.GAMESTAGE_LIVE_SOURCE}:{},presentation:at(e.GAMESTAGE_PRESENTATION,Ho(s)),signInSettings:zt(e.GAMESTAGE_PRESENTATION,Ho(s))})}:{deployedName:d,projectId:r,analyticsUrl:g,comments:c,platform:await jl({host:o,projectId:r,eventId:i,locale:Ho(s),settingsConsent:n?.settingsConsent},n?.step)}}async function jl(e,t){t?.("loading-kits");let n=await Promise.resolve().then(()=>(Da(),La));return t?.("opening"),n.createMonterosaPlatform(e)}async function Cf(e={}){let t=e.globals??globalThis.window??globalThis,{api:n,game:s}=Gl(t),o=e.search??globalThis.location?.search,r=m=>{try{e.onStep?.(m)}catch{}},i=()=>({declared:!1,categories:{}}),a=e.platform!==void 0?Promise.resolve({platform:e.platform,deployedName:void 0}):Fl(t,o,{api:n,game:s,fetch:e.fetch,step:r,settingsConsent:()=>i()});a.catch(()=>{});let d=t.location??globalThis.location,g=e.signIn!==!0||typeof document>"u"||!d?.hostname?void 0:Fr({game:s,hostname:d.hostname,fetch:e.fetch,document,store:globalThis.localStorage,mayRemember:()=>Et(i(),"functional"),session:()=>rs(s)});g?.state==="off"&&g.stop();let c=g&&g.state!=="off"?g:void 0,y=!pe(await ae(e.identity))&&c?c.begin():void 0;y&&c?.rememberedGranted()&&await Promise.race([y,new Promise(m=>setTimeout(m,1500))]);let b=async()=>pe(await ae(e.identity))??await c?.token()??void 0,T=await ae(b),f=t.GAMESTAGE_HOST_OWNS_CONSENT===!0,l={analyticsRequiresConsent:f||(e.consent?.analyticsRequiresConsent??!0)},v,p=()=>v?.reading()??{declared:!1,categories:{necessary:!0}},C=Lr({policy:l,destinations:e.destinations??[],consent:p}),S=null,_=!1,x=()=>{if(S||_)return;let m=k.presentation?.analyticsUrl?.trim()||be;!m||!ue||ct(l,p())&&(_=!0,Gr({game:s,projectId:ue,serviceUrl:m,now:()=>k.clock.now(),onObservation:O=>{C.track(O)}}).then(O=>{S=O}).catch(()=>{}).finally(()=>{_=!1}))},w=()=>{S?.stop(),S=null},h=Zo({baseUrl:n,game:s,fetch:e.fetch,identity:async()=>(T=await ae(b),pe(T))}),N=t.GAMESTAGE_FORMAT==="arcade"||t.GAMESTAGE_FORMAT==="mystery"||t.GAMESTAGE_FORMAT==="quiz";N||r("fetching-round");let R=N?Promise.resolve({ok:"none"}):h.getCurrentRound().then(m=>({ok:!0,value:m}),m=>({ok:!1,cause:m})),{platform:k,deployedName:H,projectId:ue,analyticsUrl:be,comments:$}=await a;if(k.settingsSource?.()==="none"){let m=t,O=globalThis;throw Wr({document:m.document??O.document,location:m.location??O.location}),new Yt}let ge=ts(t),_e=()=>or(sr(k.presentation?.gate,ge),f),P=_e(),I=bn(P,s),G=async(m=P)=>{if(!m)return!1;try{return await h.declare(jt(m)),!0}catch{return!1}},j=I.then(()=>G()),D,V=()=>{if(D)return D;let m=_e()??P;return m?(P=m,D=(async()=>(os(s),await bn(m,s),G(m)))().finally(()=>{D=void 0}),D):Promise.resolve(!1)};v=ks({platform:k,policy:l,game:s,scope:e.consentScope,policyVersion:k.presentation?.consentPolicyVersion,embedOrigins:k.presentation?.embedOrigins,hostManagesConsent:xs(typeof document>"u"?void 0:document,k.presentation?.oneTrustId,f),hostOwnsConsent:f}),i=p,v.onChange(m=>{ct(l,m)?x():w(),k.rememberSettings?.()}),k.rememberSettings?.(),x();let M,oe={reading:p,allowed:()=>dt(l,p()),record:()=>v?.record()??null,needed:()=>v?.needed()??l.analyticsRequiresConsent,hostDecides:()=>v?.hostDecides()??!1,decide:m=>v?.decide(m)??!1,declare:m=>v?.decide(m)??!1,onChange:m=>v?.onChange(m)??(()=>{}),openSettings:()=>M?.open()};if(await I,typeof document<"u"&&e.consentBanner!==!1&&!f&&(M=Is({presentation:k.presentation,consent:oe},e.consentBanner??{})),c&&y){let m=()=>{if(oe.needed())return;let O=k.presentation??{},fe=O.cssVariables??{};c.offer({playAs:O.signInPlayAsLabel,detail:O.signInDetail,dismiss:O.signInDismissLabel},{accent:fe.highlightMainColour??O.primaryColour,onAccent:fe.onHighlightMainColour,surface:fe.backgroundMainColour,text:fe.onBackgroundMainColour})};y.then(m),oe.onChange(()=>m()),c.onChange(O=>{O==="granted"&&ae(b).then(fe=>{T=fe})})}let q,K=new Set,Oe=async(m=!1)=>{if(!N)try{let O=await h.getCurrentRound();return Ct(k.clock,O.server_time),q=O,O}catch(O){if(m)throw O;return}},re=await R,Le=re.ok==="none"||re.ok===!1&&re.cause instanceof Error&&re.cause.status===404&&["not_found","no_round"].includes(re.cause.code??"");if(re.ok===!1&&!Le)throw re.cause;re.ok===!0&&(Ct(k.clock,re.value.server_time),q=re.value);let Ee=(m,O)=>m!==void 0&&m.id===O.id&&m.version===O.version&&(m.settled_revision??0)===(O.settled_revision??0)&&m.provisional===O.provisional&&m.challenge_instance_id===O.challenge_instance_id,De,ve=k.onRoundAnnounced(()=>{(async()=>{let m=q,O=await Oe();if(O&&!Ee(m,O))for(let fe of[...K])fe(O)})()},()=>!!(q&&(q.provisional===!0||q.awaits_settlement===!0&&!q.can.results_available&&(q.can.closed||(q.locks_at?k.clock.now()>=Date.parse(q.locks_at):De===q.id))))),A=!1,U=(()=>{let m=Es(k.presentation),O=e.busy?.copy;return{atCapacity:{...m.atCapacity,...O?.atCapacity??{}},rateLimited:{...m.rateLimited,...O?.rateLimited??{}},cappedToday:{...m.cappedToday,...O?.cappedToday??{}}}})();function X(m,O){if(e.busy?.enabled!==!1)try{Cs(m,{copy:U,...e.busy?.container===void 0?{}:{container:e.busy.container},...e.busy?.document?{document:e.busy.document}:{},...O===void 0?{}:{retryAfterSeconds:O}})}catch{}}let Z=typeof globalThis.document>"u"?()=>{}:Jr(()=>({game:s,platform:k.kind,offPlatformReason:k.offPlatformReason,ids:{project:k.projectId??hn(t,o).projectId,event:hn(t,o).eventId,host:hn(t,o).host},round:q?{id:q.id,version:q.version,number:q.number,origin:q.origin}:void 0,endpoints:{playerApi:n,mesh:hn(t,o).host},identity:{kind:T.kind,signedIn:T.kind!=="anonymous"},consent:{allowed:dt(l,p())},presentation:k.presentation}),globalThis),te=!!e?.optimistic&&q?.can.optimistic_play===!0,ne,Ft=as({api:n,game:s,fetch:e.fetch,token:async()=>pe(await ae(e.identity))??h.spaceToken(),gameToken:async()=>pe(await ae(e.identity))?void 0:await c?.token()}),yt=ys({api:n,game:s,fetch:e.fetch,token:async()=>pe(await ae(e.identity))??h.spaceToken(),gameToken:async()=>pe(await ae(e.identity))?void 0:await c?.token(),words:async m=>(await k.elementFields?.(m)??[]).flatMap(O=>bs(O.id,O.fields)??[]),outcomeWords:async m=>(await k.elementFields?.(m)??[]).flatMap(O=>_s(O.id,O.fields)??[])}),yn=t.GAMESTAGE_FORMAT==="arcade"?Bl(h,Ft,{returning:rs(s)!==void 0||!!pe(T)}):h,se=$?cs({api:$.api,topicId:$.topicId,fanToken:()=>h.commentsToken(),fetch:e.fetch}):null;return await j,{platform:k.kind,optimistic:te,id:s,get eventId(){return k.eventId},client:yn,arcade:Ft,quiz:yt,comments:se,streak:async()=>!pe(await ae(e.identity))&&c?.state==="granted"?Ps(await c.streak()):Ns({baseUrl:e.loyalty?.baseUrl,identity:b,fetchImpl:e.fetch}),presentation:k.presentation,get signInSettings(){return k.signInSettings},get needsSignIn(){return!!k.signInSettings?.enabled&&!pe(T)},settingsSource:()=>k.settingsSource?.()??"studio",analytics:C,now:()=>k.clock.now(),deployedName:H,offPlatformReason:k.offPlatformReason,get identity(){return T},async refreshIdentity(){return T=await ae(b),T},signIn:{get state(){return c?.state??"off"},onChange(m){return c?.onChange(m)??(()=>{})},requiredFor(m){return $l.has(m)},async request(){if(!c)return"off";let m=k.presentation??{},O=m.cssVariables??{};return c.request({playAs:m.signInPlayAsLabel,detail:m.signInDetail,dismiss:m.signInDismissLabel},{accent:O.highlightMainColour??m.primaryColour,onAccent:O.onHighlightMainColour,surface:O.backgroundMainColour,text:O.onBackgroundMainColour})}},get round(){return q},onRoundChanged(m){return K.add(m),()=>K.delete(m)},async playNext(){let m=await h.getNextRound();if(m.status!=="ready"||!m.round)return"exhausted";Ct(k.clock,m.server_time),q=m.round;for(let O of K)O(m.round);return"ready"},onPresentationChanged(m){return k.onPresentationChanged(m)},live(m){return m?kn(k,m):ne??=kn(k)},async play(m){let O=q??await Oe();if(!O)throw new Error("There is no round to play. The Engine did not return one.");let fe=m.idempotencyKey??is(),Ae=async()=>{try{return await h.play(O.id,{...m.picks?{picks:m.picks}:{},...m.answers?{answers:m.answers}:{},...m.op?{op:m.op}:{},...m.centre!==void 0?{centre:m.centre}:{},...m.board!==void 0?{board:m.board}:{},...m.operation?{operation:m.operation}:{},...m.room?{room:m.room}:{},roundVersion:O.version},fe)}catch(Ie){throw Ie?.status===429&&X("rateLimited"),Ie&&typeof Ie=="object"&&(Ie.idempotency_key=fe),Ie}},$e=await Ae();if($e.outcome==="rejected"&&$e.reason==="declaration_required"&&await V()&&($e=await Ae()),$e.outcome==="busy"){let Ie=$e;X(ws(Ie.reason),Ie.retry_after_seconds)}return Ct(k.clock,$e.server_time),($e.outcome==="accepted"||$e.outcome==="duplicate")&&(De=O.id),{...$e,idempotency_key:fe}},async shoot(m){let{idempotencyKey:O,...fe}=m,Ae=await this.play({operation:bt(fe),idempotencyKey:O}),Ie=Ae.outcome==="accepted"||Ae.outcome==="duplicate"?vn(_n(Ae.round_state)):void 0;return Ie?{...Ae,shot:Ie}:Ae},async draw(m={}){let O=await this.play({operation:{op:"draw"},idempotencyKey:m.idempotencyKey}),Ae=O.outcome==="accepted"||O.outcome==="duplicate"?O.round_state?.progress?.drawn?.at(-1):void 0;return Ae?{...O,drawn:Ae}:O},async solve(m,O={}){return this.play({operation:{op:"solve",text:m},idempotencyKey:O.idempotencyKey})},async guess(m,O={}){return $a(await this.play({operation:{op:"guess",value:m},idempotencyKey:O.idempotencyKey}))},async skip(m={}){return $a(await this.play({operation:{op:"skip"},idempotencyKey:m.idempotencyKey}))},track(m,O={}){return S?.track(m,O),C.track({name:m,properties:O,at:k.clock.now()})},consent:oe,storage:{read:m=>dt(l,p())?k.storage.read(m):Promise.resolve(null),write:async(m,O)=>dt(l,p())?(await k.storage.write(m,O),!0):!1,remove:async m=>dt(l,p())?(await k.storage.remove(m),!0):!1},stop(){Z(),!A&&(A=!0,ve(),K.clear(),w(),M?.stop(),v?.stop(),c?.stop(),k.stop())}}}var ql=5e3;function Bl(e,t,{returning:n}){let s=async()=>{try{let{ticket:r}=await e.getNameTicket();await t.setName(r)}catch(r){let i=r?.code??"unknown";console.warn(`gamestage: the chosen name did not reach the board (${i}). Play carries on.`)}},o=async()=>{let r;try{await Promise.race([s(),new Promise(i=>r=setTimeout(i,ql))])}finally{clearTimeout(r)}};return n&&e.getProfile().then(r=>r.name_chosen?s():void 0).catch(()=>{}),{...e,async setIdentity(r){let i=await e.setIdentity(r);return r.name&&await o(),i}}}export{Mr as ANALYTICS_CATEGORY,vt as ArcadeError,lt as BUSY_MODAL_ID,Ss as DEFAULT_BUSY_COPY,Xo as GOAL_GEOMETRY,Yt as GamestageUnavailableError,wt as QuizError,Zr as SETTINGS_CACHE_CATEGORY,Jo as SHOOT_INPUT,bi as TITLE_SELECTOR,An as UNAVAILABLE_COPY,ct as analyticsAllowed,Dc as applyPresentation,ws as busyKindFor,as as createArcadeClient,Kt as createClock,cs as createCommentsClient,ks as createConsentState,kn as createLiveContest,Rs as createLocalPlatform,jl as createMonterosaPlatform,ys as createQuizClient,Za as editionBoard,On as flatten,os as forgetGate,yi as gamestageUiTokens,ts as gateFrom,jt as gateKey,Et as granted,Ef as guessBetterThan,Yo as hasDeclared,xs as hostRunsConsentManager,Ds as hostname,vn as latestShot,Ho as localeFor,Is as mountConsent,ad as mountNotify,Nc as mountProvisionalResult,Mc as mountRecovery,is as newIdempotencyKey,bn as passGate,ns as placeNames,hn as platformIds,oi as provisionalResultText,_s as quizOutcomeFromFields,bs as quizWordsFromFields,wc as readLoyalty,Ns as readStreak,Es as resolveBusyCopy,ae as resolveIdentity,Ct as sampleIso,ei as settingsCacheAllowed,bt as shootOperation,_n as shootProgressOf,Cs as showBusyModal,Ts as signInMemoryKey,Ur as siteForGame,Cf as start,dt as storageAllowed,Ic as streakFrom,_i as titleTreatment,pe as tokenOf};\n/*! Bundled license information:\n\n@monterosa/sdk-util/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @preserve\n * Global object polyfill.\n * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\n *\n * @internal\n *\n * @returns typeof globalThis\n *)\n (**\n * @license\n * fromentries.ts\n * util\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * checksum.ts\n * util\n *\n * Copyright \xA9 2025 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2022-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-core/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2023-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2021-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-bridge-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2022-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-storage-kit/dist/index.js:\n (**\n * @license\n * types.ts\n * storage-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * storage_impl.ts\n * storage-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-storage-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * api.ts\n * storage-kit\n *\n * Copyright \xA9 2025-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-enmasse-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-enmasse-kit\n *\n * Copyright \xA9 2023-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-connect-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-connect-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-connect-kit\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-consent-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-consent-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-analytics-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-analytics-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-analytics-kit\n *\n * Copyright \xA9 2025-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-interact-interop/dist/index.js:\n (**\n * @license\n * api.ts\n * interact-interop\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-interact-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n*/\n//# sourceMappingURL=https://gamestage.ai/client/0.111.0/gamestage.js.map\n',cs="d1c2164f59559aad",Tn="gamestage.js",us="0.111.0",Ice=`<!doctype html>
899
+ `,tu="48fd8242624ce764",Bo="gamestage-player.js",Ws='/**\n * @monterosa/gamestage, bundled for a browser.\n * Gamestage client 0.112.0.\n *\n * Generated by the Gamestage CLI. Do not edit: it is replaced whenever the CLI\n * writes it again, and it carries no game logic of yours. Minified; its source\n * map is beside it on gamestage.ai.\n */\nvar es=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Fa=Object.getOwnPropertyNames;var ja=Object.prototype.hasOwnProperty;var ee=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(s){throw n=[s],s}};var Vo=(e,t)=>{for(var n in t)es(e,n,{get:t[n],enumerable:!0})},qa=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fa(t))!ja.call(e,o)&&o!==n&&es(e,o,{get:()=>t[o],enumerable:!(s=Ua(t,o))||s.enumerable});return e};var Ba=e=>qa(es({},"__esModule",{value:!0}),e);function er(e,t){let n=a=>{let d=e[a],u=d&&typeof d=="object"?d:void 0,c=u?[t,"all","en",...Object.keys(u)].filter(g=>!!g).map(g=>u[g]).find(g=>typeof g=="boolean"||typeof g=="string"&&g.trim()):d;return typeof c=="boolean"?String(c):typeof c=="string"?c.trim():""},s=Object.fromEntries(Object.entries(tc).map(([a,d])=>[a,n(`label_notify_${a}`)||d])),o=n("consent_brand_name"),r=n("privacy_policy_url"),i=(n("notify_channels")||"email").split(",").map(a=>a.trim()).filter(a=>["email","sms","rcs"].includes(a));return{enabled:["true","yes","1"].includes(n("notify_enabled")),channels:i,ownerName:o,privacyUrl:r,labels:s,termsVersion:n("notify_terms_version")||"2",wording:`${s.consent.replaceAll("{brand}",o)} ${s.privacy}`}}function wn(e,t){return t==="email"?e.length<=254&&/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(e):/^\\+[1-9]\\d{6,14}$/.test(e)}var tc,ds=ee(()=>{"use strict";tc={title:"Tell me my result",via:"Send my result by",email:"Email",sms:"Text message",email_address:"Email address",mobile_number:"Mobile number",country:"Country",consent:"{brand} will use these details to tell you your result. You can unsubscribe at any time.",privacy:"Privacy policy",button:"Notify Me",pending:"Saving\\u2026",success:"Done. We\'ll tell you after full time.",error:"That did not work. Please try again.",invalid_email:"Enter an email address, such as name@example.com.",invalid_mobile:"Enter a complete mobile number for the country you picked.",code:"6-digit code",code_incomplete:"Enter all 6 digits.",confirm:"Confirm",resend_code:"Send a new code",resend_email:"Send the email again",resend_wait:"Send again in {seconds}s",resent:"Sent. Check again.",change_address:"Use a different number or email"}});function En(e,t){if(!e||typeof e!="object"||Array.isArray(e))return e;let n=e;for(let s of[t,"all","en",...Object.keys(n)])if(s&&n[s]!==void 0&&n[s]!==null&&n[s]!=="")return n[s]}function nr(e,t){if(!e)return{};let n={},s=En(e.gate_age_required,t),o=typeof s=="boolean"?s:typeof s=="string"?s.trim().toLowerCase():void 0;o===!0||o==="true"||o==="yes"||o==="1"?n.ageRequired=!0:(o===!1||o==="false"||o==="no"||o==="0")&&(n.ageRequired=!1);let r=En(e.gate_minimum_age,t),i=typeof r=="number"?r:typeof r=="string"&&r.trim()?Number(r.trim()):NaN;Number.isInteger(i)&&i>0&&i<=120&&(n.minimumAge=i);let a=En(e.gate_territories,t);if(typeof a=="string"&&a.trim()){let u=a.split(/[\\s,;]+/).map(c=>c.trim().toUpperCase()).filter(c=>/^[A-Z]{2}$/.test(c));n.territories=[...new Set(u)]}let d=En(e.gate_note,t);return typeof d=="string"&&d.trim()&&(n.note=d.trim().slice(0,200)),n}function sr(e,t){let n=e??{},s=n.ageRequired!==void 0;if(!(s||n.minimumAge!==void 0||n.territories!==void 0||n.note!==void 0))return t?{...t}:void 0;let i=n.ageRequired??!!t?.minimumAge?n.minimumAge??t?.minimumAge??nc:void 0,a=n.territories?.length?n.territories:n.territories!==void 0||!s?t?.territories:void 0,d=n.note??(s?void 0:t?.note);if(!(!i&&!a?.length))return{...i?{minimumAge:i}:{},...a?.length?{territories:[...a]}:{},...d?{note:d}:{}}}function or(e,t){if(!e||t!==!0||!e.minimumAge)return e;if(e.territories?.length)return{territories:[...e.territories],...e.note?{note:e.note}:{}}}var tr,nc,ls=ee(()=>{"use strict";tr=["gate_age_required","gate_minimum_age","gate_territories","gate_note"];nc=18});function Cn(e){let t=Array.isArray(e)?e.filter(s=>typeof s=="string"):typeof e=="string"?e.split(/[\\s,]+/):[],n=new Set;for(let s of t){let o=s.trim();if(!/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#@*\\s]+\\/?$/i.test(o))continue;let r;try{r=new URL(o)}catch{continue}let i=r.hostname==="localhost"||r.hostname==="127.0.0.1";r.protocol!=="https:"&&!(r.protocol==="http:"&&i)||n.add(r.origin)}return[...n]}function oc(){return{necessary:!0,analytics:!1,marketing:!1,functional:!1}}function qt(e,t,n={}){let s=oc();for(let o of rr)o!=="necessary"&&(s[o]=e[o]===!0);return{version:1,categories:s,source:t,decidedAt:(n.at??new Date).toISOString(),policyVersion:n.policyVersion??us,jurisdiction:n.jurisdiction??sc}}function cr(e){if(!e||typeof e!="object")return null;let t=e;if(t.version!==1||t.source!=="host"&&t.source!=="fan"&&t.source!=="default"||typeof t.decidedAt!="string"||typeof t.policyVersion!="string"||typeof t.jurisdiction!="string"||!t.categories||typeof t.categories!="object")return null;let n=t.categories;for(let s of rr)if(typeof n[s]!="boolean")return null;return qt(n,t.source,{policyVersion:t.policyVersion,jurisdiction:t.jurisdiction,at:new Date(t.decidedAt)})}function ur(e,t){let n=t.trim();if(e.includes("{brand}")){let s=!n||n.toLowerCase()==="monterosa";return e.includes("{brand} and Monterosa, who run")?s?e.replace("{brand} and Monterosa, who run","Monterosa, who runs").replaceAll("{brand}","Monterosa"):e.replaceAll("{brand}",n):e.replaceAll("{brand}",n||"Monterosa")}return e}var rr,ir,ar,sc,us,dr,lr,Tn=ee(()=>{"use strict";rr=["necessary","analytics","marketing","functional"],ir="gamestage:consent:v1",ar="gamestage:consent";sc="GB",us="1";dr="https://gamestage.ai/copyright",lr={brand:"",title:"Your privacy",detail:"{brand} would like to record analytics on how you play, so we can improve the game. We only do this if you agree. Data needed to run the game, such as your scores, is processed on the basis of legitimate interests.",accept:"Accept",reject:"Reject",dismiss:"Close",choose:"Manage preferences",save:"Save my choices",necessary:"Needed for the game to work. Always on.",analytics:"Measure how the game is played",marketing:"Offers and news from the game\'s owner",functional:"Remember my preferences",settings:"Privacy settings",policy:"Privacy policy",copyright:"Report copyright infringement"}});function Ce(e,t){if(typeof e=="string")return e.trim()||void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"]){if(!s)continue;let o=n[s];if(typeof o=="string"&&o.trim())return o.trim()}}function ac(e,t){if(typeof e=="boolean")return e;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"])if(s&&typeof n[s]=="boolean")return n[s]}function cc(e,t=ms){return`${t}/fonts/${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}.css`}function hs(e){return e.replace(/[^\\p{L}\\p{N} \\-]/gu,"").trim()}function xr(e,t){if(!e)return;let n=Object.keys(fs).find(i=>i.toLowerCase()===e.trim().toLowerCase());if(!n)return;let s=fs[n],o=Number(t);if(!Number.isFinite(o))return{family:n,weight:s[s.length-1]};let r=[...s].sort((i,a)=>Math.abs(i-o)-Math.abs(a-o)||a-i)[0];return{family:n,weight:r}}function kr(e){if(e===void 0)return;let t=/^\\s*(-?(?:\\d+\\.?\\d*|\\.\\d+))(?:em)?\\s*$/i.exec(e);if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return`${Math.min(.4,Math.max(-.1,n))}em`}function Or(e){let t=e?.trim().toLowerCase();if(t)return["upper","uppercase","capitals","caps"].includes(t)?"uppercase":["none","uppercase","lowercase","capitalize"].includes(t)?t:"none"}function dc(e,t){let n=Ce(e.sponsor_name,t);if(!n)return;let s=Ce(e.sponsor_logo,t),o=Ce(e.sponsor_link,t);return{name:n,label:Ce(e.sponsor_intro,t)||"In association with",...s&&ps.test(s)?{logoUrl:s}:{},...o&&ps.test(o)?{link:o}:{}}}function Bt(e,t){let n=e?.trim();if(!n)return null;let s=t.find(r=>r.name.trim().toLowerCase()===n.toLowerCase());if(s){let r=hs(s.name);if(r)return{family:r}}let o=Object.keys(fs).find(r=>r.toLowerCase()===n.toLowerCase());return o?{family:o,stylesheetHref:cc(o)}:null}function at(e,t){let n={};if(!e)return n;if("notify_enabled"in e&&(n.notify=er(e,t)),tr.some(b=>b in e)){let b=nr(e,t);Object.keys(b).length>0&&(n.gate=b)}for(let[b,T]of Object.entries(rc)){let f=Ce(e[b],t);f&&(n[T]=f)}for(let[b,T]of Object.entries(ic)){if(n[T])continue;let f=Ce(e[b],t);f&&(n[T]=f)}let s=Ce(e.analytics_oneTrustId,t);s&&(n.oneTrustId=s);let o=Cn(Ce(e.embed_origins,t));o.length&&(n.embedOrigins=o);let r=Ce(e.logo_url,t)?.replace(/^\\/\\//,"https://");r&&ps.test(r)&&(n.logoUrl=r);let i=dc(e,t);i&&(n.sponsor=i);let a=Ce(e.default_font_family,t);a&&(n.defaultFontFamily=a);let d=e.uploaded_fonts;if(Array.isArray(d)){let b=f=>typeof f=="string"?f.trim():f==null?"":String(f),T=d.map(f=>f&&typeof f=="object"?f:{}).map(f=>({name:b(f.name),url:b(f.file),weight:b(f.weight)})).filter(f=>f.name&&f.url);T.length&&(n.uploadedFonts=T)}let u="css_variables_",c={};for(let b of Object.keys(e)){if(!b.startsWith(u))continue;let T=Ce(e[b],t);T&&(c[b.slice(u.length)]=T)}Object.keys(c).length>0&&(n.cssVariables=c);let g={};for(let b of Object.keys(e)){if(!b.startsWith(gr))continue;let T=Ce(e[b],t);T&&(g[b.slice(gr.length)]=T)}Object.keys(g).length>0&&(n.labels=g);let y={};for(let b of Object.keys(e)){if(!b.startsWith(gs)||b===gs)continue;let T=ac(e[b],t);T!==void 0&&(y[b.slice(gs.length)]=T)}return Object.keys(y).length>0&&(n.options=y),n}var fr,pr,mr,hr,yr,br,_r,vr,Sr,wr,Er,Cr,Tr,rc,ic,gr,gs,fs,ms,ps,St=ee(()=>{"use strict";ds();ls();Tn();fr="Provisional result. Final at {finalAt}.",pr=["a","b","c","d","e","f"],mr=e=>`quiz_option_${e}`,hr="quiz_question",yr="quiz_image",br="quiz_image_alt",_r="quiz_media",vr=e=>`quiz_option_${e}_image`,Sr="quiz_outcome_name",wr="quiz_outcome_verdict",Er="quiz_outcome_why",Cr="quiz_outcome_image",Tr="quiz_outcome_image_alt",rc={display_name:"displayName",title_font:"titleFont",title_font_weight:"titleFontWeight",title_letter_spacing:"titleLetterSpacing",title_colour:"titleColour",title_case:"titleCase",logo_text:"logoText",logo_accent_colour:"logoAccentColour",splash_gradient_start:"splashGradientStart",splash_gradient_end:"splashGradientEnd",splash_play_label:"splashPlayLabel",splash_continue_label:"splashContinueLabel",splash_error_text:"splashErrorText",splash_retry_label:"splashRetryLabel",consent_brand_name:"consentBrandName",consent_title:"consentTitle",consent_detail:"consentDetail",consent_accept_label:"consentAcceptLabel",consent_reject_label:"consentRejectLabel",consent_choose_label:"consentChooseLabel",consent_save_label:"consentSaveLabel",consent_analytics_label:"consentAnalyticsLabel",consent_marketing_label:"consentMarketingLabel",consent_functional_label:"consentFunctionalLabel",consent_settings_label:"consentSettingsLabel",consent_policy_version:"consentPolicyVersion",privacy_policy_url:"privacyPolicyUrl",signin_play_as_label:"signInPlayAsLabel",signin_detail:"signInDetail",signin_dismiss_label:"signInDismissLabel",recovery_open_label:"recoveryOpenLabel",recovery_show_title:"recoveryShowTitle",recovery_show_detail:"recoveryShowDetail",recovery_private_note:"recoveryPrivateNote",recovery_replace_note:"recoveryReplaceNote",recovery_enter_title:"recoveryEnterTitle",recovery_enter_detail:"recoveryEnterDetail",recovery_submit_label:"recoverySubmitLabel",recovery_not_recognised:"recoveryNotRecognised",recovery_restored:"recoveryRestored",recovery_get_label:"recoveryGetLabel",recovery_issue_failed:"recoveryIssueFailed",recovery_copy_label:"recoveryCopyLabel",recovery_copied_label:"recoveryCopiedLabel",recovery_share_label:"recoveryShareLabel",recovery_close_label:"recoveryCloseLabel",analytics_url:"analyticsUrl",strapline:"strapline",how_to_play:"howToPlay",primary_colour:"primaryColour",play_button_label:"playButtonLabel",play_again_label:"playAgainLabel",result_button_label:"resultButtonLabel",share_button_label:"shareButtonLabel",edition_name:"editionName",edition_strapline:"editionStrapline",edition_live_contest:"liveContest",margin_over:"marginOver",margin_exact:"marginExact",margin_under:"marginUnder",result_over:"resultOver",result_exact:"resultExact",result_under:"resultUnder",share_over:"shareOver",share_exact:"shareExact",share_under:"shareUnder",result_bust_note:"resultBustNote",share_bust_note:"shareBustNote",capped_today_note:"cappedTodayNote",share_dare:"shareDare",result_dare:"resultDare"},ic={primary_color:"primaryColour"},gr="label_",gs="option_";fs={"Abril Fatface":[400],Anton:[400],"Archivo Black":[400],"Bebas Neue":[400],Bungee:[400],"Chakra Petch":[300,400,500,600,700],"DM Serif Display":[400],Fraunces:[400,600,700,900],Oswald:[400,500,600,700],"Playfair Display":[400,700,900],"Russo One":[400],"Space Grotesk":[400,500,700],Teko:[400,500,600,700],Unbounded:[400,700,900]},ms="https://gamestage.ai";ps=/^https:\\/\\//i});function Te(e,t){if(typeof e=="string")return e.trim()||void 0;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;for(let s of[t,"all","en"]){if(!s)continue;let o=n[s];if(typeof o=="string"&&o.trim())return o.trim()}}function fc(e){return typeof e=="boolean"?e:Te(e)?.toLowerCase()==="true"}function zt(e,t){if(!e)return{enabled:!1};let n={web:Te(e.userAccessSignInUrlWeb,t),iOS:Te(e.userAccessSignInUrlNativeIOS,t),android:Te(e.userAccessSignInUrlNativeAndroid,t)},s={web:Te(e.userAccessSignUpUrlWeb,t),iOS:Te(e.userAccessSignUpUrlNativeIOS,t),android:Te(e.userAccessSignUpUrlNativeAndroid,t)},o=r=>Object.values(r).some(Boolean);return{enabled:fc(e.mIdEnabled),frontendUrl:Te(e.mIdFrontendUrl,t),apiUrl:Te(e.mIdApiUrl,t),clientId:Te(e.xClientId,t),title:Te(e.userAccessTitle,t),subtitle:Te(e.userAccessSubtitle,t),...o(n)?{signInUrl:n}:{},...o(s)?{signUpUrl:s}:{}}}var vs=ee(()=>{"use strict"});function Et(e,t){return e.declared?e.categories[t]===!0:!1}function ct(e,t){return e.analyticsRequiresConsent?Et(t,Mr):!0}function dt(e,t){return ct(e,t)}var Mr,Ht=ee(()=>{"use strict";Mr="analytics"});function Lr(e){let t=0,n=0;return{track(s){if(!ct(e.policy,e.consent()))return t+=1,!1;for(let o of e.destinations)try{o.send(s)}catch{}return e.destinations.length>0&&(n+=1),e.destinations.length>0},get withheld(){return t},get sent(){return n}}}function On(e){let t={};for(let[n,s]of Object.entries(e))if(s===null)t[n]=null;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")t[n]=s;else{if(s===void 0)continue;try{t[n]=JSON.stringify(s)??null}catch{t[n]=null}}return t}var Vt=ee(()=>{"use strict";Ht()});function Kt(){let e=0,t=!1;return{now:()=>Date.now()+e,sample(n){Number.isFinite(n)&&(e=n-Date.now(),t=!0)},get synchronised(){return t}}}function Ct(e,t){if(!t)return;let n=Date.parse(t);Number.isNaN(n)||e.sample(n)}var Wt=ee(()=>{"use strict"});function Xr(e){return`gamestage:settings:v${Ms}:${e}`}function ei(e){return Et(e,Zr)}function ti(e){let t=e.now??(()=>Date.now()),n=e.readTimeoutMs??300;return{async read(s){let o;try{o=await Promise.race([e.store.read(Xr(s)),new Promise(r=>setTimeout(()=>r(null),n))])}catch{return null}if(!o)return null;try{let r=JSON.parse(o);if(r.format!==Ms||typeof r.savedAt!="number"||t()-r.savedAt>Ac)return null;let i=r.presentation;return!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).length===0?null:i}catch{return null}},async write(s,o){if(ei(e.consent())&&Object.keys(o).length!==0)try{await e.store.write(Xr(s),JSON.stringify({format:Ms,savedAt:t(),presentation:o}))}catch{}}}}var Ms,Zr,Ac,Ls=ee(()=>{"use strict";Ht();Ms=1,Zr="functional",Ac=720*60*60*1e3});function Ds(e){return e.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i,"").replace(/\\/+$/,"")}var $s=ee(()=>{"use strict"});var xi={};Vo(xi,{TextDecoder:()=>Ti,TextEncoder:()=>Ci,default:()=>cd});var Ci,Ti,cd,ki=ee(()=>{"use strict";Ci=globalThis.TextEncoder,Ti=globalThis.TextDecoder,cd={TextEncoder:Ci,TextDecoder:Ti}});function Ve(){if(typeof self<"u")return self;if(typeof globalThis<"u")return globalThis;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}function ut(e){return Rn.localStorage.getItem(Vs(e))}function tn(e,t){return Rn.localStorage.setItem(Vs(e),t)}function Ks(e){return Rn.localStorage.removeItem(Vs(e))}function Ws(){return Rn.localStorage.clear()}function nn(){try{return tn(Pn,Pn),ut(Pn),Ks(Pn),!0}catch{return!1}}function Ge(e,t,...n){let s=t[e](...n);return new Ze(e,s)}function Ne(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return"Unknown error"}}function Ys(){return Date.now()/1e3}function Ii(e){return Math.floor(e)+.5}function fd(){return(Ii(Tt)+1-Tt)*1e3}function Ni(){clearTimeout(en);let e=Ys(),t=e-Bs;Tt+=t,Bs=e,en=setTimeout(Ni,fd()),typeof en=="object"&&"unref"in en&&en.unref(),Ai.emit("tick",Tt)}function Qs(e){Bs=Ys(),Tt=Ii(e)}function Ke(){return Math.floor(Tt)}function Mn(e){return He(Ai,"tick",e)}function Ri(e){let s=2166136261,o=new zs().encode(e);for(let r=0;r<o.length;r++)s^=o[r],s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Ln(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ue(e){return e.trim()}function et(e){let t=Oi.get(e);if(t!==void 0)return t;let n=new Hs(e);return n.logLevel=hd,n.logHandler=yd,Oi.set(e,n),n}var z,He,ye,dd,Pn,Rn,Vs,Ze,ld,ud,Zu,gd,eg,Ai,Tt,Bs,en,Pi,qs,pd,zs,B,md,Mi,Hs,Oi,hd,yd,We=ee(()=>{z=class{constructor(){this.listeners=new Map}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>this.off(t,n)}off(t,n){var s;if(n===void 0){this.listeners.delete(t);return}(s=this.listeners.get(t))===null||s===void 0||s.delete(n)}emit(t,...n){var s;(s=this.listeners.get(t))===null||s===void 0||s.forEach(o=>o(...n))}once(t,n){let s=(...o)=>{n(...o),this.off(t,s)};return this.on(t,s)}},He=(e,t,n)=>(e.on(t,n),()=>e.off(t,n));ye=(e,t,n={})=>{var s,o;let r=(s=n.clearOnResolve)!==null&&s!==void 0?s:!1,i=(o=n.clearOnReject)!==null&&o!==void 0?o:!0,a=new Map,d=(...u)=>{let c=t(...u);if(a.has(c))return a.get(c);let g=e(...u);return a.set(c,g),g.then(()=>r&&a.delete(c)).catch(()=>i&&a.delete(c)),g};return d.cache=a,d};dd="monterosa_sdk_",Pn="bait",Rn=Ve(),Vs=e=>`${dd}${e}`;Ze=class e extends Error{constructor(t,n){super(n),this.name="MonterosaError",this.code=t,Object.setPrototypeOf(this,e.prototype)}};ld=typeof global=="object"&&global&&global.Object===Object&&global,ud=typeof self=="object"&&self&&self.Object===Object&&self,Zu=ld||ud||Function("return this")(),gd=Object.prototype,eg=gd.toString;Ai=new z,Tt=0,Bs=0;Qs(Ys());Ni();Pi=e=>{let t=e.reduce((r,i)=>r+i,0),n=e.map((r,i)=>{let a=100*r/t||0;return{idx:i,votes:r,percentage:Math.floor(a),remainder:a%1}}),s=n.reduce((r,{percentage:i})=>r+i,0);s=s||100;let o=100-s;n.sort((r,i)=>r.remainder!==i.remainder?i.remainder-r.remainder:r.idx-i.idx);for(let r=0;r<o;r++)n[r].percentage+=1;return n.sort((r,i)=>r.idx-i.idx),n.map(r=>r.percentage)};pd=typeof process<"u"&&((qs=process.versions)===null||qs===void 0?void 0:qs.node)!=null;pd?zs=(ki(),Ba(xi)).TextEncoder:zs=TextEncoder;(function(e){e[e.Verbose=0]="Verbose",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Silent=5]="Silent"})(B||(B={}));md={[B.Verbose]:"log",[B.Debug]:"log",[B.Info]:"info",[B.Warn]:"warn",[B.Error]:"error"},Mi=(e,t,...n)=>{let s=md[t],o=e.name.replace("@monterosa/sdk-","monterosa/");console[s](`[${o}]`,...n)},Hs=class{constructor(t){this.name=t,this._logLevel=B.Warn,this._logHandler=Mi}get logLevel(){return this._logLevel}set logLevel(t){this._logLevel=t}get logHandler(){return this._logHandler}set logHandler(t){this._logHandler=t}emit(t,...n){this._logLevel>t||this._logHandler(this,t,...n)}log(...t){this.emit(B.Verbose,...t)}debug(...t){this.emit(B.Debug,...t)}info(...t){this.emit(B.Info,...t)}warn(...t){this.emit(B.Warn,...t)}error(...t){this.emit(B.Error,...t)}},Oi=new Map,hd=B.Warn,yd=Mi});function sn(e=Li){let t=Zs.get(e);if(!t)throw new Error(`No Monterosa Sdk "${e}" has been configured.\n You need to call configure() first`);return t}function Di(e,t=Li){let n=Zs.get(t);if(n)return n;let s=new Xs(e,t);return Zs.set(t,s),s}var bd,Li,_d,Js,Xs,Zs,Dn=ee(()=>{We();bd="2.0.0-rc.9";Li="[DEFAULT]",_d=bd;if(typeof document<"u"){let e=document.title||((Js=document.location)===null||Js===void 0?void 0:Js.hostname)||"",t=e?` \\u2014 "${e}"`:"";console.debug(`Monterosa SDK v${_d}${t}`)}Xs=class{constructor(t,n){this._isDestroyed=!1,this._options=Object.assign(Object.assign({},t),{host:Ue(t.host),projectId:Ue(t.projectId)}),this._name=n,this._kits=new Map}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get isDestroyed(){return this._isDestroyed}get kits(){return this._kits}set isDestroyed(t){this._isDestroyed=t}deleteKits(){this.kits.forEach((t,n)=>{this.kits.delete(n),t.delete()})}checkDestroyed(){if(this.isDestroyed)throw new Error(`SDK named ${this.name} destroyed`)}};Zs=new Map});function ji(e){if(e<=0)throw Ge(tt.InvalidRequestTimeoutError,Fi);lo.requestTimeout=e}function xd(e){return e instanceof Object&&Object.prototype.hasOwnProperty.call(e,"bridgeId")}function kd({data:e}){try{if(typeof e!="string")return;let t=JSON.parse(e);uo(t)}catch(t){Gn.error(Ne(t))}}function Ad(e){if(rn.has(e))return rn.get(e);let t=new Fn(e);return rn.set(e,t),t}function Id(){if(typeof window>"u")return null;if(on!==void 0)return on;let t=new URL(window.location.href).searchParams.get(Sd);return t===null?null:(on=new Fn(t),on.send(ft.OnBridgeInitialised,{},xe.Sdk),on)}function qi(e,t={}){rn.forEach(n=>{n.isConnected&&n.send(e,t,xe.Sdk)})}function xt(e){return He(Od.monterosaSdk.emitter,"message",t=>{t.sourceName===xe.Sdk&&t.action!==ft.OnBridgeInitialised&&rn.has(t.bridgeId)&&e(t)})}function go(e,t,n={}){return e.bridge.send(t,n,xe.Sdk)}function jn(e,t,n={},s=lo.requestTimeout){return e.bridge.request(t,n,s,xe.Sdk)}function an(e,t={}){Nd(xe.Sdk,e,t)}function Nd(e,t,n){Ad(t.bridgeId).send(t.action,n,e,t.id)}function Pd(e,t,n){return He(e.bridge,"message",s=>{s.sourceName===t&&n(s)})}function Bi(e,t){return Pd(e,xe.Sdk,t)}function Se(){if($n!==void 0)return $n;let e=Id();return e===null?null:($n=new co(e),$n)}var ft,xe,eo,to,no,so,Un,vd,Sd,wd,Ed,Cd,Td,tt,Fi,lo,Gn,oo,ro,io,ao,$i,Gi,Ui,Fe,uo,gt,Fn,Od,on,rn,co,$n,kt=ee(()=>{We();(function(e){e.OnBridgeInitialised="onBridgeInitialised",e.OnExperienceInitialised="onExperienceInitialised",e.OnReady="onReady",e.OnResize="onIntrinsicSizeChanged",e.OnMoreDataRequested="onMoreDataRequested",e.OnShare="onShare"})(ft||(ft={}));(function(e){e.Sdk="sdk",e.User="user"})(xe||(xe={}));Un=Ve(),vd="micBridge",Sd="micBridgeId",wd=!!(!((no=(to=(eo=Un.webkit)===null||eo===void 0?void 0:eo.messageHandlers)===null||to===void 0?void 0:to.monterosaSdk)===null||no===void 0)&&no.postMessage),Ed=!!(!((so=Un.monterosaSdk)===null||so===void 0)&&so.postMessage),Cd=Un.self!==Un.parent,Td="1.0.0";(function(e){e.InvalidRequestTimeoutError="invalid_request_timeout_error",e.RequestTimeoutError="request_timeout_error"})(tt||(tt={}));Fi={[tt.InvalidRequestTimeoutError]:()=>"Request timeout must be greater than 0",[tt.RequestTimeoutError]:(e,t)=>`Request timeout: action "${e}" did not receive a response within ${t}ms`};lo={requestTimeout:2e4};Gn=et("@monterosa/sdk-bridge-kit");Fe=Ve(),uo=e=>{xd(e)&&Fe.monterosaSdk.emitter.emit("message",e)};(oo=Fe.monterosaSdk)!==null&&oo!==void 0||(Fe.monterosaSdk={initialised:!1,emitter:new z,receiveMessage:uo});(ro=($i=Fe.monterosaSdk).initialised)!==null&&ro!==void 0||($i.initialised=!1);(io=(Gi=Fe.monterosaSdk).emitter)!==null&&io!==void 0||(Gi.emitter=new z);(ao=(Ui=Fe.monterosaSdk).receiveMessage)!==null&&ao!==void 0||(Ui.receiveMessage=uo);Fe.monterosaSdk.initialised||(typeof Fe.addEventListener<"u"&&Fe.addEventListener("message",kd),Fe.monterosaSdk.initialised=!0);gt=Ve(),Fn=class extends z{constructor(t=Ln()){super(),this.id=t,this.recipientInitialised=!1,this.messagesQueue=[],gt.monterosaSdk.emitter.on("message",this.handleMessage.bind(this))}static isMessage(t){return t instanceof Object&&Object.prototype.hasOwnProperty.call(t,"bridgeId")&&Object.prototype.hasOwnProperty.call(t,"action")}get iFrameId(){return`${vd}-${this.id}`}get iFrameSelector(){return`iframe#${this.iFrameId}`}get childIFrame(){return document.querySelector(this.iFrameSelector)}handleMessage(t){let{id:n,bridgeId:s,action:o,respondingTo:r}=t;if(s===this.id){if(Gn.log(`Received a ${r===null?"message":"response"}`,t),o===ft.OnBridgeInitialised){r===null&&this.send(ft.OnBridgeInitialised,{},xe.Sdk,n),this.connect();return}this.emit("message",t)}}createMessage(t,n,s,o=null){return{id:Ln(),respondingTo:o,action:t,sourceName:s,bridgeId:this.id,payload:n,version:Td,timestamp:Date.now()}}get isConnected(){return this.recipientInitialised}connect(){for(this.recipientInitialised=!0;this.messagesQueue.length>0;)this.postMessage(this.messagesQueue.shift())}disconnect(){this.recipientInitialised=!1}postMessage(t){var n,s,o,r;if(!this.recipientInitialised&&t.action!==ft.OnBridgeInitialised){this.messagesQueue.push(t);return}let i=JSON.stringify(t);wd&&((s=(n=gt.webkit)===null||n===void 0?void 0:n.messageHandlers)===null||s===void 0||s.monterosaSdk.postMessage(i)),Ed&&!((o=gt.monterosaSdk)===null||o===void 0)&&o.postMessage&&gt.monterosaSdk.postMessage(i),Cd&&gt.parent.postMessage(i,"*"),this.childIFrame&&((r=this.childIFrame.contentWindow)===null||r===void 0||r.postMessage(i,"*"))}send(t,n={},s=xe.Sdk,o){let r=this.createMessage(t,n,s,o);return Gn.log(`Sending a ${r.respondingTo===null?"message":"response"}`,r),this.postMessage(r),r}async request(t,n={},s=lo.requestTimeout,o=xe.Sdk){let r,i,a=this.createMessage(t,n,o);Gn.log("Sending a request",a);let d=new Promise((c,g)=>{r=setTimeout(()=>{g(Ge(tt.RequestTimeoutError,Fi,t,s))},s)}),u=new Promise(c=>{i=g=>{g.respondingTo===a.id&&c(g)},gt.monterosaSdk.emitter.on("message",i),this.postMessage(a)});return Promise.race([d,u]).finally(()=>{clearTimeout(r),gt.monterosaSdk.emitter.off("message",i)})}};Od=Ve(),rn=new Map;co=class{constructor(t){this.bridge=t}};});function Rd(e){var t;if(Object.values(je).includes(e.action))try{let n={};switch(e.action){case je.Read:n={key:e.payload.key,value:Pe.getItem(e.payload.key)};break;case je.Write:n={key:e.payload.key},Pe.setItem(e.payload.key,e.payload.value);break;case je.Remove:n={key:e.payload.key},Pe.removeItem(e.payload.key);break;case je.Clear:Pe.clear();break}an(e,n)}catch(n){let s=Ne(n),o=(t=e.payload)===null||t===void 0?void 0:t.key,r=o?` for key "${o}"`:"";qn.error(`Unable to handle storage action ${e.action}${r} with error: ${s}`),an(e,{error:s})}}async function po(e,t,n){try{let s=await jn(e,t,n),{value:o,error:r}=s.payload;if(r!==void 0)throw Ge(we.ParentAppError,cn,r);return o}catch(s){if(s instanceof Ze&&s.code===tt.RequestTimeoutError){let o=Ne(s);throw Ge(we.ParentTimeoutError,cn,o)}throw s}}async function Ot(e){let t=Se(),n=null;try{t!==null?n=await po(t,je.Read,{key:e}):n=Pe.getItem(e)}catch(s){let o=Ne(s);throw qn.error(`Unable to read storage item "${e}" with error: ${o}`),Ge(we.ReadError,cn,o)}return n}async function At(e,t){let n=Se();try{n!==null?await po(n,je.Write,{key:e,value:t}):Pe.setItem(e,t)}catch(s){let o=Ne(s);throw qn.error(`Unable to write storage item "${e}" with error: ${o}`),Ge(we.WriteError,cn,o)}}async function Bn(e){let t=Se();try{t!==null?await po(t,je.Remove,{key:e}):Pe.removeItem(e)}catch(n){let s=Ne(n);throw qn.error(`Unable to remove storage item "${e}" with error: ${s}`),Ge(we.RemoveError,cn,s)}}var je,we,cn,fo,qn,Pe,zn=ee(()=>{We();kt();(function(e){e.Read="storageRead",e.Write="storageWrite",e.Remove="storageRemove",e.Clear="storageClear"})(je||(je={}));(function(e){e.ParentAppError="parent_app_error",e.ParentTimeoutError="parent_timeout_error",e.ReadError="read_error",e.WriteError="write_error",e.RemoveError="remove_error",e.ClearError="clear_error"})(we||(we={}));cn={[we.ParentAppError]:e=>`Parent application error: ${e}`,[we.ParentTimeoutError]:e=>`Parent application timeout: ${e}. Please check if the storage-kit is imported on the parent page.`,[we.ReadError]:e=>`Storage read error: ${e}`,[we.WriteError]:e=>`Storage write error: ${e}`,[we.RemoveError]:e=>`Storage remove error: ${e}`,[we.ClearError]:e=>`Storage clear error: ${e}`};fo=class{constructor(){this.memoryStore={},this.accessible=nn(),this._persistent=!0}set persistent(t){if(this._persistent===t)return;let s=t===!0&&this.accessible,o=t===!1&&this.accessible;if(s)for(let[r,i]of Object.entries(this.memoryStore))tn(r,i);o&&Ws(),this._persistent=t}get persistent(){return this._persistent}getItem(t){return this.persistent&&this.accessible?ut(t):Object.prototype.hasOwnProperty.call(this.memoryStore,t)?this.memoryStore[t]:null}setItem(t,n){this.persistent&&this.accessible&&tn(t,n),this.memoryStore[t]=n}removeItem(t){this.persistent&&this.accessible&&Ks(t),delete this.memoryStore[t]}clear(){this.persistent&&this.accessible&&Ws(),this.memoryStore={}}};qn=et("@monterosa/sdk-storage-kit");Pe=new fo;xt(Rd)});function E(e,...t){var n;switch((n=jd[e])!==null&&n!==void 0?n:B.Verbose){case B.Info:ln.info(...t);break;case B.Debug:ln.debug(...t);break;default:ln.log(...t);break}}function dn(e,t){ln.error(`EnMasse: ${e}: ${Ne(t)}`)}function qd(e){ln.warn(`EnMasse: ${e}`)}var Md,Ld,Vi,So,Ki,Wi,Vn,wo,Yi,Eo,Dd,$d,Co,Gd,Qi,Ud,zi,Hi,Fd,Re,Q,ce,de,pt,Ji,Me,It,Xi,ln,jd,mo,Kn,Zi,ea,Bd,ho,J,Hn,le,me,zd,yo,Hd,bo,Vd,Kd,Wd,_o,vo,Yd,Qd,Pt,Rt,Nt,L,ta=ee(()=>{We();zn();kt();Md="enmasse_override_methods",Ld="enmasse_config",Vi="auth",So="authr",Ki="authok",Wi="ping",Vn="sub",wo="unsub",Yi="eoc",Eo="login",Dd="login_ok",$d="login_fail",Co="logout",Gd="counter",Qi=e=>{if(nn()){let n=ut(e);if(n!==null)return n}if(typeof window>"u")return null;let{searchParams:t}=new URL(window.location.href);return t.has(e)?t.get(e):!1},Ud=()=>{let e=Qi(Md);if(typeof e=="string")return e.split(",")},zi=Ud(),Hi=Qi(Ld),Fd="2.0.0-rc.9";Re=1,Q=2,ce=4,de=8,pt=16,Ji=32,Me=64,It=128,Xi=256,ln=et("@monterosa/sdk-enmasse-kit"),jd={[Re]:B.Info,[Q]:B.Debug,[ce]:B.Debug,[de]:B.Debug,[Me]:B.Verbose,[It]:B.Verbose,[pt]:B.Verbose,[Ji]:B.Verbose,[Xi]:B.Verbose};mo=class{constructor(t={}){this.queue=[],this.stashed=[],this.running=!1,this.runner=typeof t.runner=="function"?t.runner:null,this._subscriptions=[]}push(t,n=!1){E(pt,"Queue::push",t,n);let{klass:s,channel:o}=t;if(!n)switch(s){case Eo:case Co:case So:break;case Vn:if(this._subscriptions.indexOf(o)===-1)this._subscriptions.push(o);else return;break;case wo:{let r=this._subscriptions.indexOf(o);if(r!==-1)this._subscriptions.splice(r,1);else return;break}default:if(this._subscriptions.indexOf(o)===-1)return;break}this.queue.push(t)}get subscriptions(){return this._subscriptions}run(){E(pt,"Queue::run",`running=${this.running}, head=${this.queue[0]}`),!(this.runner===null||this.running||!this.queue[0])&&(this.running=!0,this.runner(this.queue.shift()))}success(){E(pt,"Queue::success"),this.running=!1,this.run()}failure(){E(pt,"Queue::failure"),this.running=!1}stash(){E(pt,"Queue::stash");let t;for(;(t=this.queue.shift())!==void 0;)this.stashed.push(t)}unstash(){E(pt,"Queue::unstash");let t;for(;(t=this.stashed.shift())!==void 0;)this.queue.push(t)}},Kn=()=>Date.now()/1e3,Zi=Kn(),ea=Kn(),Bd=e=>{E(Ji,"Time::setTime",e),Zi=e,ea=Kn()},ho=()=>{let e=Kn()-ea;return Math.round(Zi+e)},J=class e extends z{constructor(){super(...arguments),this.state=e.STATE_DISCONNECTED,this.trigger=this.emit,this.bind=this.on,this.unbind=this.off}connect(){}disconnect(){}init(){}send(t,n,s){}};J.ON_READY="ready";J.ON_MESSAGE="message";J.ON_CONNECTED="connected";J.ON_CONNECT_FAILED="connect_failed";J.ON_CONNECT_LOST="connect_lost";J.ON_DISCONNECTED="disconnected";J.STATE_CONNECTED="connected";J.STATE_CONNECTING="connecting";J.STATE_DISCONNECTED="disconnected";J.STATE_DISCONNECTING="disconnecting";Hn=[0,3,5,10,20,30,45,60],le=class e extends z{constructor(t){super(),this._handleTransportMessage=s=>{E(Q,"ConnectionManager::handleTransportMessage",s);let o=s.split("\\0");for(let r=0;r<o.length;r+=1)o[r].length>0&&(this._inactivityTimeout.reset(),E(Q,"ConnectionManager::handleTransportMessage","send upstream m:",o[r]),this.emit(e.ON_MESSAGE,o[r]))},this._handleTransportConnected=()=>{E(Q,"ConnectionManager::handleTransportConnected"),this._setStateToConnected()},this._handleTransportConnectFailed=()=>{E(Q,"ConnectionManager::handleTransportConnectFailed"),this._disconnectingOnConnectFailed()},this._handleTransportConnectLost=()=>{E(Q,"ConnectionManager::handleTransportConnectLost"),this._disconnectingOnConnectLost()},this._handleTransportDisconnected=()=>{switch(E(Q,"ConnectionManager::handleTransportDisconnected"),this._state){case e.STATE_CONNECTED:this._disconnectedOnConnectLost();break;case e.STATE_CONNECTING:this._disconnectedOnConnectFailed();break;case e.STATE_DISCONNECTING:this._setStateToDisconnected();break}},this._handleVisibilityChange=()=>{switch(E(Q,"ConnectionManager::handleVisibilityChange()",document.visibilityState),document.visibilityState){case"visible":if(this._backgroundedAt===null||this._state!==e.STATE_CONNECTED)return;Date.now()-this._backgroundedAt>this._config.background_timeout*1e3&&(E(Q,"ConnectionManager::handleVisibilityChange()","disconnecting due to background timeout"),this._disconnect()),this._backgroundedAt=null;break;case"hidden":this._backgroundedAt=Date.now();break}},this._handleNetworkStatus=()=>{!navigator.onLine&&this._state===e.STATE_CONNECTED&&(E(Q,"ConnectionManager::handleNetworkStatus()","disconnecting due to network loss"),this._disconnect())},this._transportManager=t,this._state=e.STATE_DISCONNECTED,this._transport=null,this._attempt=1,this._backgroundedAt=null;let n=this;this._inactivityTimeout={start(){E(Me,"ConnectionManager::inactivityTimeout::start");let s=ho();this.interval=setInterval(()=>{ho()-s>=n._config.inactivity_timeout&&this.resolve()},1e3)},stop(){E(Me,"ConnectionManager::inactivityTimeout::stop"),clearInterval(this.interval)},reset(){E(Me,"ConnectionManager::inactivityTimeout::reset"),this.stop(),this.start()},resolve(){E(Me,"ConnectionManager::inactivityTimeout::resolve"),n._disconnectingOnConnectLost()}},this._connectTimeout={start(){E(Me,"ConnectionManager::connectTimeout::start"),this.timeout=setTimeout(()=>{this.resolve()},n._config.connect_timeout*1e3)},stop(){E(Me,"ConnectionManager::connectTimeout::stop"),clearTimeout(this.timeout)},resolve(){E(Me,"ConnectionManager::connectTimeout::resolve"),n._disconnectingOnConnectFailed()}},this._connectDelay={active:!1,start(s){E(Me,"ConnectionManager::connectDelay::start"),this.active=!0,this.timeout=setTimeout(()=>{this.resolve()},s*1e3)},stop(){E(Me,"ConnectionManager::connectDelay::stop"),this.active=!1,clearTimeout(this.timeout)},resolve(){E(Me,"ConnectionManager::connectDelay::resolve"),this.stop(),n._connect()}}}_initTransport(t){E(Q,"ConnectionManager::initTransport"),this._transport=t,t.bind(J.ON_MESSAGE,this._handleTransportMessage),t.bind(J.ON_CONNECTED,this._handleTransportConnected),t.bind(J.ON_CONNECT_FAILED,this._handleTransportConnectFailed),t.bind(J.ON_CONNECT_LOST,this._handleTransportConnectLost),t.bind(J.ON_DISCONNECTED,this._handleTransportDisconnected)}_teardownTransport(){E(Q,"ConnectionManager::teardownTransport"),this._transport!==null&&(this._transport.unbind(J.ON_MESSAGE,this._handleTransportMessage),this._transport.unbind(J.ON_CONNECTED,this._handleTransportConnected),this._transport.unbind(J.ON_CONNECT_FAILED,this._handleTransportConnectFailed),this._transport.unbind(J.ON_CONNECT_LOST,this._handleTransportConnectLost),this._transport.unbind(J.ON_DISCONNECTED,this._handleTransportDisconnected),this._transport=null)}_disconnectingOnConnectFailed(){E(Q,"ConnectionManager::disconnectingOnConnectFailed()"),this._disconnect()}_disconnectingOnConnectLost(){E(Q,"ConnectionManager::disconnectingOnConnectLost()"),this._disconnect()}_disconnectedOnConnectLost(){E(Q,"ConnectionManager::disconnectedOnConnectLost()"),this._teardownTransport(),this._setStateToConnecting()}_disconnectedOnConnectFailed(){E(Q,"ConnectionManager::disconnectedOnConnectFailed()"),this._transportManager.addUnsuccessful(this._transport),this._teardownTransport(),this._transportManager.next()===!1?this._setStateToConnecting():this._connect()}_setStateToConnecting(){E(Q,"ConnectionManager::setStateToConnecting()");let t;this._attempt>=Hn.length?t=Hn[Hn.length-1]:t=Hn[this._attempt-1],this._state=e.STATE_CONNECTING,this.emit(e.ON_STATE,this._state,this._attempt,t),this._transportManager.reset(),this._attempt+=1,this._connectDelay.start(t)}_setStateToConnected(){E(Q,"ConnectionManager::setStateToConnected()"),this._attempt=1,this._transportManager.reset(),this._inactivityTimeout.reset(),this._connectTimeout.stop(),this._connectDelay.stop(),this._state=e.STATE_CONNECTED,this.emit(e.ON_STATE,this._state)}_setStateToDisconnecting(){E(Q,"ConnectionManager::setStateToDisconnecting()"),this._state=e.STATE_DISCONNECTING,this.emit(e.ON_STATE,this._state),this._disconnect()}_setStateToDisconnected(){E(Q,"ConnectionManager::setStateToDisconnected()"),this._attempt=1,this._teardownTransport(),this._transportManager.reset(),this._state=e.STATE_DISCONNECTED,this.emit(e.ON_STATE,this._state)}_connect(){var t;this._state===e.STATE_CONNECTING&&(this._connectTimeout.start(),this._initTransport(this._transportManager.current),(t=this._transport)===null||t===void 0||t.connect())}_disconnect(){this._inactivityTimeout.stop(),this._connectTimeout.stop(),this._connectDelay.stop(),this._transport?this._transport.disconnect():this._setStateToDisconnected()}connect(){E(Q,"ConnectionManager::connect()"),this._connectDelay.active?this._connectDelay.resolve():this._state===e.STATE_DISCONNECTED&&this._setStateToConnecting(),window.addEventListener("online",this._handleNetworkStatus),window.addEventListener("offline",this._handleNetworkStatus),window.addEventListener("visibilitychange",this._handleVisibilityChange)}disconnect(){E(Q,"ConnectionManager::disconnect()"),this._setStateToDisconnecting(),window.removeEventListener("online",this._handleNetworkStatus),window.removeEventListener("offline",this._handleNetworkStatus),window.removeEventListener("visibilitychange",this._handleVisibilityChange)}send(t,n=()=>{},s=()=>{}){var o;E(Q,"ConnectionManager::send",t),(o=this._transport)===null||o===void 0||o.send(t,n,s)}get connectAttempt(){return this._attempt}init(t){E(Q,"ConnectionManager::init()",t),this._config=t}};le.STATE_DISCONNECTED="state_disconnected";le.STATE_DISCONNECTING="state_disconnecting";le.STATE_CONNECTING="state_connecting";le.STATE_CONNECTED="state_connected";le.ON_MESSAGE="message";le.ON_STATE="state";me=class e extends z{constructor(){super(...arguments),this.connected=!1,this.trigger=this.emit,this.bind=this.on,this.unbind=this.off}connect(t,n,s){}disconnect(){}send(...t){}init(){this.trigger(e.ON_READY)}};me.ON_READY="ready";me.ON_MESSAGE="message";me.ON_CONNECTED="connected";me.ON_DISCONNECTED="disconnected";zd=Ve(),yo=class e extends me{constructor(t={}){super(),this.config=t,this.requests={},this.requestIdx=0}_request(t,n=()=>{},s=()=>{},o=()=>{}){this.requestIdx+=1,E(It,`XHRDriver::request url=${t}, idx=${this.requestIdx}`);let r=new XMLHttpRequest,i="POST";if(typeof XDomainRequest<"u")r=new XDomainRequest,r.open(i,t);else if("withCredentials"in r)r.open(i,t,!0),r.setRequestHeader("Content-type","application/x-www-form-urlencoded");else return null;return r._idx=this.requestIdx,r.onload=()=>{E(It,`XHRDriver::request::onload idx=${r._idx}, response=${r.responseText}`),r.responseText.length>0?n(this._parseResponse(r.responseText)):s(r.responseText)},r.onerror=()=>{E(It,`XHRDriver::request::onerror idx=${r._idx}, response=${r.responseText}`),s(r.responseText)},r._onabort=()=>{E(It,`XHRDriver::request::onabort idx=${r._idx}`),o()},r}_parseResponse(t){let n={},s=t.split("&");for(let o=0,r=s.length;o<r;o++){let[i,a]=s[o].split("="),d=decodeURIComponent((a??"").replace("\\0",""));i in n?(n[i].constructor!==Array&&(n[i]=[n[i]]),n[i].push(d)):n[i]=d}return n}_removeRequest(t){E(It,"XHRDriver::removeRequest",t),Object.prototype.hasOwnProperty.call(this.requests,t)&&delete this.requests[t]}connect(){if(E(de,"XHRDriver::connect"),this.connected){E(de,"XHRDriver::connect already been connected!");return}this.connected=!0,this.trigger(e.ON_CONNECTED)}disconnect(){if(E(de,"XHRDriver::disconnect"),this.connected){for(let t in this.requests)Object.prototype.hasOwnProperty.call(this.requests,t)&&typeof this.requests[t].abort=="function"&&(this.requests[t].abort(),typeof this.requests[t]._onabort=="function"&&this.requests[t]._onabort(),this._removeRequest(t));this.connected=!1}this.trigger(e.ON_DISCONNECTED)}send(t,n,s=()=>{},o=()=>{}){E(de,"XHRDriver::send",n);let r,i=1,a=()=>{r=this._request(t,d,u,c),this.requests[r._idx]=r,setTimeout(()=>{r.send(n)},0)},d=g=>{E(de,"XHRDriver::success",n),this._removeRequest(r._idx),s(g)},u=g=>{var y,b;E(de,"XHRDriver::failure, retry: ",i),this._removeRequest(r._idx),i<=((y=this.config.request_retries)!==null&&y!==void 0?y:0)?setTimeout(()=>{a(),i++},((b=this.config.request_retry_delay)!==null&&b!==void 0?b:0)*1e3):o(g)},c=()=>{E(de,"XHRDriver::abort",n),this._removeRequest(r._idx),o()};a()}static hasSupport(){return"XDomainRequest"in zd||"withCredentials"in new XMLHttpRequest}},Hd=Ve(),bo=class e extends me{constructor(){super(...arguments),this.websocket=null,this.closeTimeout=void 0}_onMessage(t){E(de,"WebSocketDriver::onMessage",t.data),this.trigger(e.ON_MESSAGE,t.data)}_onOpen(){E(de,"WebSocketDriver::onOpen"),this.connected=!0,this.trigger(e.ON_CONNECTED)}_onClose(){E(de,"WebSocketDriver::onClose"),this._disconnect()}_onError(){E(de,"WebSocketDriver::onError")}_disconnect(){E(de,"WebSocketDriver::disconnect"),this.connected=!1,this.websocket!==null&&(this.websocket.onmessage=()=>{},this.websocket.onopen=()=>{},this.websocket.onclose=()=>{},this.websocket.onerror=()=>{},this.websocket=null),clearTimeout(this.closeTimeout),this.trigger(e.ON_DISCONNECTED)}connect(t,n,s){if(this.connected)return;E(de,"WebSocketDriver::connect",t,n);let o=`${s?"wss":"ws"}://${t}:${n}/ws`;this.websocket=new WebSocket(o),this.websocket.onmessage=this._onMessage.bind(this),this.websocket.onopen=this._onOpen.bind(this),this.websocket.onclose=this._onClose.bind(this),this.websocket.onerror=this._onError.bind(this)}disconnect(){var t;E(de,"WebSocketDriver::disconnect"),this.connected?((t=this.websocket)===null||t===void 0||t.close(),this.closeTimeout=setTimeout(this._disconnect.bind(this),750)):this._disconnect()}send(t,n=()=>{}){var s;E(de,"WebSocketDriver::send",t),(s=this.websocket)===null||s===void 0||s.send(t),n()}static hasSupport(){return"WebSocket"in Hd}},Vd="connect",Kd="pass",Wd="poll",_o=class e extends J{constructor(t={}){E(ce,"ProxyTransport::constructor",t),super(),this.driver=t.driver,this.host=t.host,this.port=t.port,this.secure=t.secure||!1,this.proxyIp=null,this.childId=null,this.clientId=null,this.sessionId=null,this.driver.bind(me.ON_READY,this._handleDriverReady.bind(this)),this.driver.bind(me.ON_CONNECTED,this._handleDriverConnected.bind(this)),this.driver.bind(me.ON_DISCONNECTED,this._handleDriverDisconnected.bind(this))}_url(){let t=this.childId===null?"":`${this.childId}/`;return`${this.secure?"https":"http"}://${this.proxyIp?this.proxyIp:this.host}:${this.port}/${t}?_r=${new Date().getTime()}`}_request(t="",n=()=>{},s=()=>{}){let o=i=>{i.sscp.constructor===String&&(i.sscp=[i.sscp]);for(let a=0,d=i.sscp.length;a<d;a++)i.sscp[a]!==""&&this.trigger(e.ON_MESSAGE,i.sscp[a]);n(i)},r=()=>{switch(this.state){case e.STATE_CONNECTED:case e.STATE_CONNECTING:this.state=e.STATE_DISCONNECTING,this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.state=e.STATE_DISCONNECTED,this.trigger(e.ON_DISCONNECTED);break}s()};this.driver.send(this._url(),t,o,r)}_poll(){let t=`command=${Wd}&clientid=${this.clientId}&sid=${this.sessionId}`;this._request(t,this._poll.bind(this))}_connect(){let t=o=>{o&&(this.proxyIp=o.proxy,this.clientId=Number.parseInt(o.clientid,10),this.childId=Number.parseInt(o.childid,10),this.sessionId=o.sid,this.state=e.STATE_CONNECTED,this.trigger(e.ON_CONNECTED),this._poll())},n=()=>{this.state=e.STATE_DISCONNECTED,this.trigger(e.ON_CONNECT_FAILED)},s=`command=${Vd}`;this._request(s,t,n)}_handleDriverReady(){this.trigger(e.ON_READY)}_handleDriverConnected(){this._connect()}_handleDriverDisconnected(){E(ce,"ProxyTransport::handleDriverDisconnected");let{state:t}=this;switch(this.state=e.STATE_DISCONNECTED,t){case e.STATE_CONNECTED:this.trigger(e.ON_CONNECT_LOST);break;case e.STATE_CONNECTING:this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.trigger(e.ON_DISCONNECTED);break}}send(t,n=()=>{},s=()=>{}){E(ce,"ProxyTransport::send",t);let o=`command=${Kd}&clientid=${this.clientId}&sscp=${t}&sid=${this.sessionId}`;this._request(o,n,s)}connect(){E(ce,"ProxyTransport::connect",this.host,this.port),this.state=e.STATE_CONNECTING,this.driver.connect()}disconnect(){E(ce,"ProxyTransport::disconnect"),this.proxyIp=null,this.childId=null,this.sessionId=null,this.state=e.STATE_DISCONNECTING,this.driver.disconnect()}init(){E(ce,"ProxyTransport::init"),this.driver.init()}},vo=class e extends J{constructor(t={}){E(ce,"SocketTransport::constructor",t),super(),this.driver=t.driver,this.host=t.host,this.port=t.port,this.secure=t.secure||!1,this.driver.bind(me.ON_READY,this._handleDriverReady.bind(this)),this.driver.bind(me.ON_MESSAGE,this._handleDriverMessage.bind(this)),this.driver.bind(me.ON_CONNECTED,this._handleDriverConnected.bind(this)),this.driver.bind(me.ON_DISCONNECTED,this._handleDriverDisconnected.bind(this))}_handleDriverReady(){E(ce,"SocketTransport::_handleDriverReady"),this.trigger(e.ON_READY)}_handleDriverMessage(t){E(ce,"SocketTransport::handleDriverMessage"),this.trigger(e.ON_MESSAGE,t)}_handleDriverConnected(){E(ce,"SocketTransport::handleDriverConnected"),this.state=e.STATE_CONNECTED,this.trigger(e.ON_CONNECTED)}_handleDriverDisconnected(){E(ce,"SocketTransport::handleDriverDisconnected");let{state:t}=this;switch(this.state=e.STATE_DISCONNECTED,t){case e.STATE_CONNECTED:this.trigger(e.ON_CONNECT_LOST);break;case e.STATE_CONNECTING:this.trigger(e.ON_CONNECT_FAILED);break;case e.STATE_DISCONNECTING:this.trigger(e.ON_DISCONNECTED);break}}send(t,n=()=>{},s=()=>{}){E(ce,"SocketTransport::send",t),this.driver.send(t,n,s)}connect(){E(ce,"SocketTransport::connect",this.host,this.port),this.state=e.STATE_CONNECTING,this.driver.connect(this.host,this.port,this.secure)}disconnect(){E(ce,"SocketTransport::disconnect"),this.state=e.STATE_DISCONNECTING,this.driver.disconnect()}init(){E(ce,"SocketTransport::init"),this.driver.init()}},Yd="proxy",Qd="websocket",Pt=class e extends z{constructor(){super(),this.idx=0,this.methods={},this.transports={},this.loaded=0,this.sequence=[],this.allowed=[],this.secure=!0,this.unsuccessful=[],typeof window<"u"&&(this.secure=window.location.protocol.startsWith("https"))}_instantiate(){E(Q,"TransportManager::instantiate"),this.allowed.forEach(t=>{let n=this._getMethodConfig(t),s=n.hosts[Math.floor(Math.random()*n.hosts.length)],o=this.methods[t].transport,r=this.methods[t].driver,i=new o({driver:new r(n.driver||{}),host:s,port:this.secure?n.secure_port:n.port,secure:this.secure});this.transports[t]=i,i.bind(J.ON_READY,this._handleTransportReady.bind(this))});for(let t in this.transports)Object.prototype.hasOwnProperty.call(this.transports,t)&&this.transports[t].init()}_getMethodConfig(t){return this.config.methods.find(n=>n.type===t)}_handleTransportReady(){this.loaded+=1,this.loaded===this.allowed.length&&this.emit(e.ON_READY)}get current(){return this.transports[this.allowed[this.idx]]}next(){return this.idx+=1,this.idx>=this.allowed.length?!1:this.current}reset(){this.allowed=[],this.unsuccessful=[];for(let t=0,n=this.sequence.length;t<n;t+=1){let s=this.sequence[(t+this.idx)%n];this.methods[s].driver.hasSupport()&&this.allowed.push(s)}this.idx=0}addUnsuccessful(t){for(let n in this.transports)Object.prototype.hasOwnProperty.call(this.transports,n)&&this.transports[n]===t&&this.unsuccessful.push(n)}init(t={}){this.config=t,this.idx=0,this.loaded=0,this.sequence=[],this.secure=t.forceSecure===!0?!0:this.secure,this.methods[Yd]={driver:yo,transport:_o},this.methods[Qd]={driver:bo,transport:vo},zi?this.sequence=zi:this.config.methods.forEach(s=>this.sequence.push(s.type));let n=s=>Object.prototype.hasOwnProperty.call(this.methods,s);this.sequence=this.sequence.filter(n),this.reset(),this._instantiate()}};Pt.ON_READY="ready";Rt=class e extends z{addCounter(t,n,s,o,r=null,i=null,a=null){if(E(Xi,"Demographics::addCounter",t,n,s,o,r,i,a),!t||!n||!Array.isArray(s)||!s.length||s.length%2!==0||o!==Number.parseInt(String(o),10))return;let d=s.filter((c,g)=>(g+1)%2).join(":"),u=s.filter((c,g)=>g%2).join(":");this.emit(e.ON_ADD_COUNTER,t,[n,i,a,r,d,u,o])}};Rt.ON_ADD_COUNTER="add-counter";Nt="enmasse_session_id",L=class e extends z{constructor({transportManager:t=new Pt,demographics:n=new Rt,connectionManager:s}={}){super(),this._runner=o=>{let r=()=>{this._queue.success()},i=()=>{this._queue.failure()};this._connectionManager.send(this._stringifySSCP(o),r,i)},this._handleTransportManagerReady=()=>{E(Re,"Enmasse::handleTransportManagerReady"),this.emit(e.ON_READY)},this._handleConnectionManagerState=(o,r,i)=>{switch(E(Re,"Enmasse::handleConnectionManagerState",o,r,i),o){case le.STATE_DISCONNECTED:this._setStateToDisconnected();break;case le.STATE_CONNECTING:this._setStateToConnecting(r,i);break;case le.STATE_CONNECTED:break}},this._handleConnectionManagerMessage=async o=>{E(Re,"Enmasse::handleConnectionManagerMessage",o);let r=this._parseSSCP(o);switch(r.klass){case Vi:{let i=r.sent_at,a=[`enmassejs-${e.VERSION}`,navigator.userAgent].concat(this._info);this._sysChannel=r.channel,a.forEach((d,u)=>{a[u]=encodeURIComponent(d)}),this._sessionId===null&&([this._sessionId]=r.body,await this._storeSession(this._sessionId)),Bd(i),this._queue.stash(),this._queue.push({channel:this._sysChannel,klass:So,body:[this._sessionId,e.PROTOCOL_VERSION,a.join(",")]},!0),this._queue.run();break}case Ki:{let{subscriptions:i}=this._queue;i.forEach(a=>{this._queue.push({channel:a,klass:Vn,body:[]},!0)}),this._queue.unstash(),this._queue.run(),this._setStateToConnected();break}case Dd:this._resolveLogin();break;case $d:this._rejectLogin();break;case Wi:break;case Yi:this.emit(e.ON_EOC,r.channel);break;default:this.emit(e.ON_MESSAGE,r);break}},this._handleDemographicsCounter=(o,r)=>{this.send(o,"avgcounter",r)},this._transportManager=t,this._demographics=n,this._connectionManager=s||new le(t),this.Demographics=this._demographics,this._configFile=null,this._info=[],this._sessionId=null,this._state=e.STATE_DISCONNECTED,this._sysChannel=null,this._forceSecure=!1,this._loginContext={inProgress:!1,success:()=>{},failure:()=>{}},this._initPromise=null}async _storeSession(t){try{await At(Nt,t)}catch(n){dn("Failed to persist session to shared storage",n)}}async _restoreSession(){let t=null;try{t=await Ot(Nt)}catch(n){dn("Failed to read session from shared storage",n)}if(t!==null)return t;if(Se()===null)return null;try{t=ut(Nt)}catch(n){dn("Failed to read local session during migration",n)}if(t===null)return null;try{await At(Nt,t)}catch(n){dn("Failed to persist session to shared storage during migration",n)}return t}async resetSession(){this._sessionId=null;try{await Bn(Nt)}catch(t){dn("Failed to remove session from shared storage",t)}}_validateSession(t){return/^[a-f\\d]{8}\\-[a-f\\d]{4}\\-[a-f\\d]{4}-[a-f\\d]{4}\\-[a-f\\d]{12}$/i.test(t)}_finaliseLogin(t){this._loginContext.inProgress!==!1&&(this._loginContext={inProgress:!1,success:()=>{},failure:()=>{}},typeof t=="function"&&t())}_resolveLogin(){this._finaliseLogin(this._loginContext.success)}_rejectLogin(){this._finaliseLogin(this._loginContext.failure)}_setStateToDisconnected(){E(Re,"Enmasse::setStateToDisconnected()"),this._state=e.STATE_DISCONNECTED,this._sysChannel=null,this._rejectLogin(),this.emit(e.ON_STATE,this._state)}_setStateToConnected(){E(Re,"Enmasse::setStateToConnected()");let t=ho();this._state=e.STATE_CONNECTED,this.emit(e.ON_STATE,this._state,t)}_setStateToConnecting(t,n){E(Re,"Enmasse::setStateToConnecting()"),this._state=e.STATE_CONNECTING,this._rejectLogin(),this.emit(e.ON_STATE,this._state,t,n)}_parseSSCP(t){let n={channel:"",klass:"",sent_at:0,body:[]},s=t.indexOf("/");if(s!==-1){let o=t.indexOf("/",s+1);if(o!==-1){n.channel=t.substr(0,s),n.klass=t.substr(s+1,o-s-1);let r=t.indexOf("/",o+1);if(r!==-1){n.sent_at=Number.parseInt(t.substr(o+1,r-o-1),10);let i=t.substr(r+1);if(i!==""){let a=i.split("|");for(let d=0,u=a.length;d<u;d+=1)n.body[d]=decodeURIComponent(a[d])}}}}return n}_stringifySSCP(t){var n;return[t.channel,t.klass,Math.floor(Date.now()/1e3),((n=t.body)!==null&&n!==void 0?n:[]).join("|")].join("/")}connect(){E(Re,"Enmasse::connect"),this._connectionManager.connect()}disconnect(){E(Re,"Enmasse:disconnect"),this._connectionManager.disconnect()}teardown(){E(Re,"Enmasse::teardown"),this.disconnect(),this._transportManager.off(Pt.ON_READY,this._handleTransportManagerReady),this._connectionManager.off(le.ON_STATE,this._handleConnectionManagerState),this._connectionManager.off(le.ON_MESSAGE,this._handleConnectionManagerMessage),this._demographics.off(Rt.ON_ADD_COUNTER,this._handleDemographicsCounter)}send(t,n,s=[]){E(Re,"Enmasse::send",t,n,s),this._queue.push({channel:t,klass:n,body:s}),this._state===e.STATE_CONNECTED&&this._queue.run()}get sessionId(){return this._sessionId}get state(){return this._state}subscribe(t){this.send(t,Vn)}unsubscribe(t){this.send(t,wo)}login(t,n,s,o,r){let i=this._sysChannel;if(i!==null){if(this._loginContext.inProgress){qd("Login is already in progress");return}this._loginContext={inProgress:!0,success:o,failure:r},this.send(i,Eo,[t,n,s])}}logout(){let t=this._sysChannel;t!==null&&(this._loginContext.inProgress&&this._rejectLogin(),this.send(t,Co))}init(t={}){return this._initPromise||(this._initPromise=this._init(t)),this._initPromise}async _init(t={}){if(this._configFile=Hi||t.config||null,this._info=t.info||[],this._sessionId=await this._restoreSession(),typeof t.forceSecure=="boolean"&&(this._forceSecure=t.forceSecure),this._configFile===null)throw new Error("EnMasse config file is not set");let n=this._configFile;this._sessionId!==null&&!this._validateSession(this._sessionId)&&await this.resetSession(),this._queue=new mo({runner:this._runner}),this._transportManager.on(Pt.ON_READY,this._handleTransportManagerReady),this._connectionManager.on(le.ON_STATE,this._handleConnectionManagerState),this._connectionManager.on(le.ON_MESSAGE,this._handleConnectionManagerMessage),this._demographics.on(Rt.ON_ADD_COUNTER,this._handleDemographicsCounter);try{let s=await fetch(n),{status:o,statusText:r}=s,i;try{i=await s.json()}catch{this.emit(e.ON_ERROR,`Invalid JSON from config ${n}`);return}let a=o>=200&&o<=300||o===0&&!!r||o==="";i.forceSecure=this._forceSecure,i.background_timeout===void 0&&(i.background_timeout=0),a?(this._connectionManager.init(i),this._transportManager.init(i)):this.emit(e.ON_ERROR,`Failed to load config ${n}`)}catch(s){this.emit(e.ON_ERROR,`Error loading config: ${s.message}`)}}};L.VERSION=Fd;L.PROTOCOL_VERSION="8";L.SSCP_KLASS_AUTH=Vi;L.SSCP_KLASS_AUTHR=So;L.SSCP_KLASS_AUTHOK=Ki;L.SSCP_KLASS_PING=Wi;L.SSCP_KLASS_SUB=Vn;L.SSCP_KLASS_UNSUB=wo;L.SSCP_KLASS_EOC=Yi;L.SSCP_KLASS_LOGIN=Eo;L.SSCP_KLASS_LOGOUT=Co;L.SSCP_KLASS_COUNTER=Gd;L.ON_STATE="on_state";L.ON_MESSAGE="on_message";L.ON_EOC="on_eoc";L.ON_READY="on_ready";L.ON_ERROR="on_error";L.STATE_DISCONNECTED="disconnected";L.STATE_CONNECTED="connected";L.STATE_CONNECTING="connecting";L.PARAM_SESSION_ID=Nt});function xo(e,t,n){let s=(o,...r)=>{o===t&&n(...r)};return e.on("state",s),()=>e.off("state",s)}function Wn(e){return e===void 0&&(e=sn().options.host),Jd(Ue(e))}function un(e,t){return xo(e,ie.Connected,t)}function sa(e,t){return xo(e,ie.Connecting,t)}function oa(e,t){return xo(e,ie.Disconnected,t)}function ra(e,t){let n=s=>{t(s)};return e.on("message",n),()=>e.off("message",n)}function Yn(e){return e.connect()}function Qn(e){e.disconnect()}function Mt(e,t){return Xd(e,Ue(t))}function Lt(e,t){e.unsubscribe(Ue(t))}function ia(e,t,n,s){e.send(Ue(t),n,s)}var Ye,ie,na,To,Jd,Xd,ko=ee(()=>{Dn();We();ta();(function(e){e.NotInitialised="not_initialised",e.Initialised="initialised",e.Initialising="initialising"})(Ye||(Ye={}));(function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected"})(ie||(ie={}));(function(e){e.Authenticate="auth",e.AuthenticateResponse="authr",e.AuthenticateSuccess="authok",e.Ping="ping",e.Subscribe="sub",e.Unsububscribe="unsub",e.EndOfCache="eoc",e.Login="login",e.LoginSuccess="login_ok",e.LoginFail="login_fail",e.Counter="counter",e.Vote="v"})(na||(na={}));To=class extends z{constructor(t=new L){super(),this.enmasse=t,this.initState=Ye.NotInitialised,this.initPromise=Promise.resolve(),this.connectPromise=null,this.enmasse.on(L.ON_STATE,(n,...s)=>{if(n===L.STATE_CONNECTED){let[o]=s;Qs(o)}this.emit("state",this.toConnState(n),...s)}),this.enmasse.on(L.ON_MESSAGE,n=>{this.emit("message",n)})}get state(){return this.toConnState(this.enmasse.state)}get sessionId(){return this.enmasse.sessionId}toConnState(t){switch(t){case L.STATE_CONNECTING:return ie.Connecting;case L.STATE_CONNECTED:return ie.Connected;case L.STATE_DISCONNECTED:default:return ie.Disconnected}}async init(t){return this.initState===Ye.Initialising||this.initState===Ye.Initialised?this.initPromise:(this.initPromise=new Promise((n,s)=>{this.initState=Ye.Initialising,this.enmasse.on(L.ON_READY,()=>{this.initState=Ye.Initialised,this.enmasse.off(L.ON_READY),this.enmasse.off(L.ON_ERROR),n()}),this.enmasse.on(L.ON_ERROR,o=>{this.initState=Ye.NotInitialised,this.enmasse.off(L.ON_READY),this.enmasse.off(L.ON_ERROR),s(new Error(`Unable to initialise connect kit: ${o}`))}),this.enmasse.init({config:`https://${t}/config/enmasse.json`})}),this.initPromise)}connect(){return this.initState!==Ye.Initialised?Promise.reject(new Error("must be initialised before connecting")):this.state===ie.Connected?Promise.resolve():this.state===ie.Connecting?this.connectPromise?this.connectPromise:Promise.reject(new Error("BUG: Connection state is Connecting but connectPromise is null - this indicates an internal inconsistency")):(this.connectPromise=new Promise((t,n)=>{let s=o=>{switch(o){case ie.Connected:this.enmasse.off(L.ON_STATE,s),this.connectPromise=null,t();break;case ie.Disconnected:this.enmasse.off(L.ON_STATE,s),this.connectPromise=null,n(new Error("disconnected"));break;case ie.Connecting:break}};this.enmasse.on(L.ON_STATE,s),this.enmasse.connect()}),this.connectPromise)}disconnect(){this.enmasse.disconnect()}subscribe(t){return new Promise(n=>{let s=o=>{o===t&&(this.enmasse.off(L.ON_EOC,s),n())};this.enmasse.on(L.ON_EOC,s),this.enmasse.subscribe(t)})}unsubscribe(t){this.enmasse.unsubscribe(t)}send(t,n,s){this.enmasse.send(t,n,s)}async login(t,n,s){return new Promise((o,r)=>{this.enmasse.login(t,n,s,o,()=>{r(new Error("Login failure"))})})}async logout(){this.enmasse.logout()}delete(){this.enmasse.teardown()}};Jd=ye(async e=>{let t=new To;return await t.init(e),t},e=>e);Xd=ye(async(e,t)=>e.subscribe(t),(e,t)=>t)});function gn(){let e=Oo.getInstance();if(!ca){for(let t of da)t(e);ca=!0}return e}function Zd(e){da.push(e)}function la(e){if(Se()!==null)throw new Ze(nt.CannotSetFromChild,aa[nt.CannotSetFromChild]());if("necessary"in e&&e.necessary===!1)throw new Ze(nt.NecessaryCategoryRequired,aa[nt.NecessaryCategoryRequired]());let n=gn();n.state=e}function ua(){var e;return(e=gn().state)!==null&&e!==void 0?e:{}}function Ao(e){return gn().on(Jn.ConsentChanged,e)}function ga(e){let t=gn();t.state=e}function el(){Ao(e=>{qi(Dt.OnConsentUpdated,{state:e})}),xt(e=>{if(e.action!==Dt.RequestConsent)return;let t=gn();an(e,{state:t.isActive?t.state:null})})}async function tl(){let e=Se();if(e!==null)try{let t=await jn(e,Dt.RequestConsent),{state:n}=t.payload;n!=null&&ga(n)}catch{}}function nl(e){let t=Se();if(t===null)return()=>{};let n=Bi(t,s=>{if(s.action===Dt.OnConsentUpdated){let{state:o}=s.payload;ga(o)}});return tl(),n}var Dt,Jn,nt,aa,Oo,da,ca,fa=ee(()=>{kt();We();(function(e){e.OnConsentUpdated="consentOnConsentUpdated",e.SetConsent="consentSetConsent",e.RequestConsent="consentRequestConsent"})(Dt||(Dt={}));(function(e){e.ConsentChanged="consent_changed"})(Jn||(Jn={}));(function(e){e.NecessaryCategoryRequired="necessary_category_required",e.CannotSetFromChild="cannot_set_from_child"})(nt||(nt={}));aa={[nt.NecessaryCategoryRequired]:()=>"Cannot set \'necessary\' category to false. Strictly necessary functionality cannot be disabled.",[nt.CannotSetFromChild]:()=>"Cannot set consent state from embedded experience. Consent is managed by the parent application."};Oo=class e extends z{get state(){return this._state}set state(t){let n=this._state;this._state=t,t!==null&&!e.isConsentStateEqual(n,t)&&this.emit(Jn.ConsentChanged,t)}get isActive(){return this._state!==null}constructor(){super(),this._state=null}static isConsentStateEqual(t,n){if(t===null&&n===null)return!0;if(t===null||n===null)return!1;let s=Object.keys(t),o=Object.keys(n);if(s.length!==o.length)return!1;let r=t,i=n;return s.every(a=>r[a]===i[a])}static getInstance(){return e.instance||(e.instance=new e),e.instance}};da=[],ca=!1;Zd(nl);el()});function pa(e){if(Io.has(e))return Io.get(e);let t=new No(e);return Io.set(e,t),t}function sl(e){return pa(e===void 0?"__SELF__":e.bridge.id)}function ma(e,t){sl().emit(st.OnEvent,e,t);let s=Se();s!==null&&go(s,st.OnEvent,{eventName:e,properties:t})}var st,No,Io,ha=ee(()=>{kt();We();(function(e){e.OnEvent="onAnalyticsEvent"})(st||(st={}));No=class extends z{constructor(t){super(),this.id=t}};Io=new Map;xt(e=>{if(!Object.values(st).includes(e.action))return;let t=pa(e.bridgeId);if(e.action===st.OnEvent){let{eventName:n,properties:s}=e.payload;t.emit(st.OnEvent,n,s);let o=Se();o!==null&&go(o,st.OnEvent,{eventName:n,properties:s})}})});async function Po(e,t){return await(await fetch(`https://${e}/projects/${t.substring(0,2)}/${t}/settings.json`)).json()}var ya=ee(()=>{});function ht(e){return ol(e)}function ba(e){return e.split(/[-_]/)[0]}function il(e){let t=[navigator.language,...navigator.languages];for(let n of t)if(e.includes(n))return n;for(let n of t){let s=ba(n);for(let o of e)if(ba(o)===s)return o}return e[0]}function pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:e.all}async function al(e,t){let{id:n,host:s}=e;if($t.has(n))return $t.get(n);let o=new Do(e,t);$t.set(n,o);try{if(await(await cl(s)).subscribeProject(n),!o.listings)throw new Error(`Unable to fetch project ${n} listings. Possibly wrong project id.`);return o.fields=await Po(o.host,o.id),o}catch(r){throw Xn.has(n)&&Xn.get(n).unsubscribeProject(n),$t.delete(n),r}}async function cl(e){if(Xn.has(e))return Xn.get(e);let t=await ht(e);return t.on("message",dl),t}async function dl(e){let{id:t,klass:n,data:s}=e,o=$t.get(t);o&&n===Xe.Listings&&await ll(o,s[0])}async function ll(e,t){var n;let s=JSON.parse(t),o=s.project.app_settings_digest,r=(n=e.listings)===null||n===void 0?void 0:n.project.app_settings_digest;e.listings=s;try{r!==void 0&&o!==r&&(e.fields=await Po(e.host,e.id))}catch{Sa.warn(`Unable to fetch project ${e.id} settings`)}}function Ut(e=sn()){return ul(e)}function wa(e,t){return He(e,"updated",t)}async function Zn(e,t){let n=await fetch(`https://${e}/events/${t.substring(0,2)}/${t}/history.json`);if(!n.ok)throw new Error(`Failed to fetch event ${t} history`);return await n.json()}function Go(e,t){if(Gt.has(e.id))return Gt.get(e.id);let n=new $o(e,t);return n.on("internal_state",hl.bind(n)),Gt.set(e.id,n),n}async function gl(e){if(e.initState===it.Initialising)throw new Error("can\'t initialise event, event is already being initialised");if(e.initState===it.Initialised)throw new Error("can\'t initialise event, event is already initialised");if(e.initState=it.Initialising,e.canLoadHistory&&e.history===null){let t=await Zn(e.context.project.host,e.id);e.history=t}e.canSubscribe&&await fl(e),await ml(e),e.initState=it.Initialised}async function fl(e){if(!e.canSubscribe)throw new Error("Event can\'t be subscribed");await(await ht(e.context.project.host)).subscribeEvent(e.id)}async function pl(e){(await ht(e.context.project.host)).unsubscribeEvent(e.id)}async function ml(e){let{project:t}=e.context;if(_a.has(t.id))return;let n=await ht(t.host);if(n.enmasse!==null){let s=un(n.enmasse,yl);_a.set(t.id,s)}}async function hl(e){e===he.Finished&&await pl(this)}async function yl(){for(let e of Array.from(Gt.values()))if(e.initState===it.Initialised){let t=await Zn(e.context.project.host,e.id);e.history=t}}function Ea(e){return bl(e)}function mn(e,t){return _l(Ue(e),t)}function Ca(e,t){return He(e,"updated",t)}async function Ta(e,t){if(ke.has(e.id))return ke.get(e.id);let n=new jo(e,t);return await Ol(n),ke.set(n.id,n),n}function xa(e){return Array.from(ke.values()).find(t=>t.pollId===e)}async function Bo(e){return vl(e)}async function wl(e){return Sl(e)}async function El(e){let{klass:t}=e;switch(t){case Xe.Create:await Cl(e);break;case Xe.Revoke:Tl(e);break;case Xe.Feedback:await xl(e);break;case Xe.Reveal:kl(e);break}}async function Cl(e){let{id:t,data:n}=e,s=JSON.parse(n[0]),o=await mn(t);if(o!==null)if(ke.has(s.id)){let r=ke.get(s.id);(s.updated_at>r.updatedAt||s.duration!==r.duration)&&(r.update(s),o.emit("update",r))}else{let r=Object.assign(Object.assign({},o.context),{event:o}),i=await Ta(s,r);o.emit("publish",i)}}function Tl(e){let{data:t}=e,{id:n}=JSON.parse(t[0]);if(!ke.has(n))return;let s=ke.get(n);ke.delete(n),s.destroy(),s.context.event.emit("revoke",s)}async function xl(e){let{data:t}=e,n=+t[0],s=t[3],o=xa(n);if(!o)return;let r=s.split(":").map(d=>+d),i=Pi(r),a=r.map((d,u)=>({percentage:i[u],votes:d}));o.results=a}function kl(e){let{data:t}=e,n=+t[0],s=+t[1]-1,o=xa(n);o&&o.correctOption!==s&&(o.correctOption=s,o.context.event.emit("update",o))}async function va(e){if(e.timeline.length===0)return;let t=await mn(e.config.id);if(t===null)return;let n=Object.assign(Object.assign({},t.context),{event:t});for(let s of e.timeline)ke.has(s.id)||await Ta(s,n)}async function Ol(e){let t=await Ot(`element_${e.id}_vote`);t!==null&&(e.userAnswer=Uo.fromJSON(t))}function ka(e){return Al(e)}function Oa(e,t){return Bo(e),He(e,"update",t)}var rt,Xe,Qe,Mo,ol,fn,Lo,Ag,rl,Do,Sa,$t,Xn,ul,he,it,$o,Gt,_a,bl,_l,qe,Ig,mt,Uo,Fo,ot,jo,ke,vl,Sl,Ng,Al,Je,qo,Ro,Pg,Aa=ee(()=>{We();ko();Dn();ya();zn();(function(e){e.Ok="ok",e.Error="error"})(rt||(rt={}));(function(e){e.Listings="listings",e.History="history",e.Create="create",e.Revoke="revoke",e.Stop="stop",e.Reveal="reveal",e.Poll="p",e.Feedback="fb",e.Eoc="eoc",e.Vote="v",e.SubsCounter="subscounter"})(Xe||(Xe={}));(function(e){e.Poll="p",e.Live="l"})(Qe||(Qe={}));Mo=class extends z{constructor(t){super(),this.host=t,this._state=rt.Ok,this._enmasse=null}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this.emit("state",this._state))}get enmasse(){if(this._enmasse===null)throw new Error("Connect is not initialised, init() method should be called first.");return this._enmasse}set enmasse(t){this._enmasse=t}async init(){this.enmasse=await Wn(this.host),this.enmasse.on("message",this.handleMessage.bind(this)),this.enmasse.on("state",this.handleState.bind(this))}async connect(){await Yn(this.enmasse)}disconnect(){Qn(this.enmasse)}async subscribeProject(t){await Mt(this.enmasse,`${Qe.Live}-${t}`)}unsubscribeProject(t){Lt(this.enmasse,`${Qe.Live}-${t}`)}async subscribeEvent(t){await Promise.all([Mt(this.enmasse,`${Qe.Live}-${t}`),Mt(this.enmasse,`${Qe.Poll}-${t}`)])}unsubscribeEvent(t){Lt(this.enmasse,`${Qe.Live}-${t}`),Lt(this.enmasse,`${Qe.Poll}-${t}`)}sendVote(t,n,s){ia(this.enmasse,`${Qe.Poll}-${t}`,Xe.Vote,[n,s,""])}handleMessage(t){let{klass:n,body:s,channel:o}=t,r=o.substring(o.indexOf("-")+1);this.emit("message",{id:r,klass:n,data:s})}handleState(t,...n){switch(t){case ie.Disconnected:this.state=rt.Error;break;case ie.Connecting:{let[s]=n;s>1&&(this.state=rt.Error);break}case ie.Connected:this.state=rt.Ok;break}}};ol=ye(async e=>{let t=new Mo(e);return await t.init(),await t.connect(),t},e=>e);(function(e){e.Ok="ok",e.Error="error"})(fn||(fn={}));Lo=class extends z{constructor(t){super(),this.connect=t,this._state=fn.Ok,this.connect.on("state",this.handleState.bind(this))}get state(){return this._state}set state(t){this._state=t,this.emit("state",t)}handleState(){switch(this.connect.state){case rt.Error:this.state=fn.Error;break;case rt.Ok:default:this.state=fn.Ok;break}}};Ag=ye(async e=>{let t=await ht(e.options.host);return new Lo(t)},e=>e.options.host);rl=30;Do=class extends z{constructor(t,n){super(),this.eventsChecksum=null,this.id=t.id,this.host=t.host,this._context=n}get context(){return this._context}get embedUrl(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.embed}get uuid(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.uuid}get events(){var t;return((t=this._listings)===null||t===void 0?void 0:t.events)||[]}get listings(){return this._listings}set listings(t){let n=this._calculateCreatedEvents(t),s=this._calculateUpdatedEvents(t),o=this._calculateDeletedEvents(t);this._listings=Object.assign({},t),this._updateLocales(t),this._updateEventsChecksum(t),this._emitListingsEvents(n,s,o)}_calculateCreatedEvents(t){return this._listings?t.events.filter(({id:n})=>!this._listings.events.some(s=>n===s.id)):[]}_calculateUpdatedEvents(t){return this._listings?t.events.filter(n=>{let s=this._listings.events.find(({id:o})=>n.id===o);return s&&n.digest!==s.digest}):[]}_calculateDeletedEvents(t){return this._listings?this._listings.events.filter(({id:n})=>!t.events.some(s=>n===s.id)):[]}_updateLocales(t){this._locales=t.project.locales.map(n=>Object.assign({},n)).sort(n=>n.default?-1:0).map(n=>n.key),this._locale=il(this._locales)}_updateEventsChecksum(t){this.eventsChecksum=Ri(t.events.map(n=>n.digest).join(""))}_emitListingsEvents(t,n,s){let o=t.length>0,r=s.length>0,i=n.length>0,a=o||r||i;o&&this.emit("listings_events_created",t),r&&this.emit("listings_events_deleted",s),i&&this.emit("listings_events_updated",n),a&&this.emit("listings")}get isLocalisationSupported(){var t;return(t=this._listings)===null||t===void 0?void 0:t.project.is_localisation_supported}get locale(){return this._locale}set locale(t){if(!this.locales.includes(t))throw new Error(`Unknown locale name "${t}"`);this._locale=t}get locales(){return this._locales}get fields(){return this._fields!==void 0?pn(this._fields,this.locale):{}}set fields(t){let n=typeof this._fields<"u";this._fields=Object.assign({},t),n&&this.emit("updated")}get extensions(){var t;return(t=this._listings)===null||t===void 0?void 0:t.assets}get historyIgnore(){var t;let n=(t=this._listings)===null||t===void 0?void 0:t.project.history_ignore;return n&&n>0?n:rl}delete(){}};Sa=et("@monterosa/sdk-interact-kit");$t=new Map,Xn=new Map;ul=ye(async e=>await al({id:e.options.projectId,host:e.options.host},{sdk:e}),e=>e.options.projectId);(function(e){e.Upcoming="upcoming",e.Active="active",e.Prolonged="prolonged",e.Finished="finished"})(he||(he={}));(function(e){e.Uninitialised="uninitialised",e.Initialising="initialising",e.Initialised="initialised"})(it||(it={}));$o=class extends z{constructor(t,n){super(),this._initState=it.Uninitialised,this._history=null,this._data=t,this._context=n,this._state=this.calculateState(),this._internalState=this.calculateInternalState(),this.boundHandleState=this.handleState.bind(this),this.boundHandleInternalState=this.handleInternalState.bind(this),this.boundHandleEventsUpdated=this.handleEventsUpdated.bind(this),this.unsubscribeStateHandler=Mn(this.boundHandleState),this.unsubscribeInternalStateHandler=Mn(this.boundHandleInternalState),this.unsubscribeListingsHandler=He(this.context.project,"listings_events_updated",this.boundHandleEventsUpdated)}calculateState(){return!this._data.started||Ke()<this.startAt?he.Upcoming:Ke()<this.endAt?he.Active:he.Finished}calculateInternalState(){return!this._data.started||Ke()<this.startAt?he.Upcoming:Ke()<this.endAt?he.Active:Ke()<this.endAt+this._data.extra_time?he.Prolonged:he.Finished}handleState(){let t=this.calculateState();t===he.Finished&&this.unsubscribeStateHandler(),t!==this._state&&(this._state=t,this.emit("state",t))}handleInternalState(){let t=this.calculateInternalState();t===he.Finished&&this.unsubscribeInternalStateHandler(),t!==this._internalState&&(this._internalState=t,this.emit("internal_state",t))}handleEventsUpdated(t){let n=t.find(({id:s})=>s===this.id);n&&this._data.digest!==n.digest&&(this._data=n,this.handleState(),this.handleInternalState(),this.emit("updated"))}destroy(){this.unsubscribeStateHandler(),this.unsubscribeInternalStateHandler(),this.unsubscribeListingsHandler()}get context(){return this._context}get id(){return this._data.id}get name(){return this._data.name}get startAt(){return this._data.start_at}get startAtIso(){return this._data.start_at_iso}get endAt(){return this._data.end_at}get endAtIso(){return this._data.end_at_iso}get duration(){return this._data.duration}get fields(){let{locale:t}=this.context.project;return pn(this._data.custom_fields,t)}get state(){return this._state}get internalState(){return this._internalState}get initState(){return this._initState}set initState(t){this._initState=t}get history(){return this._history}set history(t){this._history=t,this.emit("history",t)}get canSubscribe(){return this._internalState===he.Active||this._internalState===he.Prolonged}get canLoadHistory(){return Ke()>=this.startAt+this.context.project.historyIgnore}};Gt=new Map,_a=new Map;bl=ye(async e=>{e===void 0&&(e=await Ut());let t=Object.assign(Object.assign({},e.context),{project:e});return e.events.map(n=>Go(n,t)).sort((n,s)=>n.startAt-s.startAt)},e=>{var t,n;if(e!==void 0)return(t=e.eventsChecksum)!==null&&t!==void 0?t:e.id;let s=sn(),o=$t.get(s.options.projectId);return o?(n=o.eventsChecksum)!==null&&n!==void 0?n:o.id:s.options.projectId});_l=ye(async(e,t)=>{if(Gt.has(e))return Gt.get(e);t===void 0&&(t=await Ut());let n=Object.assign(Object.assign({},t.context),{project:t}),s=t.events.find(o=>o.id===e);if(s!==void 0){let o=Go(s,n);if(o.canLoadHistory){let r=await Zn(t.host,e);o.history=r}return o}try{let o=await Zn(t.host,e),r=Go(o.config,n);return r.history=o,r}catch{return null}},e=>e);(function(e){e.OptionIndexOutOfRange="out_of_range",e.BelowMinVoteOptions="below_min_vote_options",e.AboveMaxVoteOptions="above_max_vote_options",e.AboveMaxVotesPerUser="above_max_per_user",e.AboveMaxVotesPerOption="above_max_per_option",e.VotedOnNonInteractiveElement="non_interactive_element",e.VotedOnClosedElement="closed_element",e.EmptyVote="empty_vote"})(qe||(qe={}));Ig={[qe.OptionIndexOutOfRange]:(e,t)=>`Options index ${t} is out of range [0..${e}]`,[qe.BelowMinVoteOptions]:(e,t)=>`Below min (${e}) vote options: ${t}`,[qe.AboveMaxVoteOptions]:(e,t)=>`Above max (${e}) vote options: ${t}`,[qe.AboveMaxVotesPerUser]:(e,t)=>`Above max (${e}) votes per user: ${t}`,[qe.AboveMaxVotesPerOption]:(e,t)=>`Above max (${e}) votes per option: ${t}`,[qe.VotedOnNonInteractiveElement]:e=>`Non interact element ${e}`,[qe.VotedOnClosedElement]:e=>`Element ${e} is closed`,[qe.EmptyVote]:e=>`Empty value for options indices: ${e}`};(function(e){e.Opened="opened",e.Closed="closed"})(mt||(mt={}));Uo=class e{constructor(t=[]){this._answers=new Map;for(let{option:n,value:s}of t)this._answers.set(n,s)}get answers(){return Array.from(this._answers.entries()).map(([t,n])=>({option:t,value:n}))}static fromIndices(t){return new e(t.map(n=>({option:n,value:1})))}set(t,n){return this._answers.set(t,n),this}remove(t){return this._answers.delete(t),this}toJSON(){return this.answers}static fromJSON(t){return new e(JSON.parse(t))}};(function(e){e.Data="data",e.Poll="poll",e.RegularPoll="rpoll",e.DiametricPoll="dpoll",e.EmotingPoll="emo",e.Powerbar="powerbar",e.Prediction="prediction",e.Trivia="trivia"})(Fo||(Fo={}));(function(e){e.OnVote="vote",e.OnClose="close",e.OnEventEnd="event_end",e.Manual="manual",e.Never="never",e.Always="always"})(ot||(ot={}));jo=class extends z{constructor(t,n){var s,o;super(),this._results=null,this._userAnswer=null,this._correctOption=null,this._data=t,this._context=n,this._results=((s=t.data)===null||s===void 0?void 0:s.results)||null,this._correctOption=!((o=t.data)===null||o===void 0)&&o.correct_option?t.data.correct_option-1:null,this._state=this.calculateState(),this.unsubscribeStateHandler=Mn(()=>this.handleState())}calculateState(){return Ke()<this.publishedAt+this.duration?mt.Opened:mt.Closed}handleState(){let t=this.calculateState();t===mt.Closed&&this.unsubscribeStateHandler(),t!==this._state&&(this._state=t,this.emit("state",t))}update(t){this._data=t,this.handleState()}destroy(){this.unsubscribeStateHandler()}get context(){return this._context}get id(){return this._data.id}get eventId(){return this.context.event.id}get state(){return this._state}get type(){return this._data.type}get contentType(){return this._data.content_type}get publishedAt(){return this._data.published_at}get publishedAtIso(){return this._data.published_at_iso}get updatedAt(){return this._data.updated_at}get updatedAtIso(){return this._data.updated_at_iso}get duration(){return this._data.duration}get fields(){let{locale:t}=this.context.project;return pn(this._data.custom_fields,t)}get interactive(){return this.type!==Fo.Data}get pollId(){return this._data.data.id||null}get question(){let{locale:t}=this.context.project;return this._data.data.question===void 0?null:pn(this._data.data.question,t)}get answerOptions(){let{locale:t}=this.context.project;return this._data.data.options===void 0?null:pn(this._data.data.options,t)}get minOptionsPerVote(){return this._data.data.min_options_per_vote||1}get maxOptionsPerVote(){return this._data.data.max_options_per_vote||1}get maxVotesPerOption(){return this._data.data.max_votes_per_option||1}get maxVotesPerUser(){return this._data.data.max_votes_per_user||null}get userAnswer(){return this._userAnswer}set userAnswer(t){this._userAnswer=t}get hasBeenAnswered(){return this._userAnswer!==null}get showResultsMode(){return this._data.data.reveal_results_mode||null}get canShowResults(){switch(this.showResultsMode){case ot.OnVote:return this.hasBeenAnswered||this.state===mt.Closed;case ot.OnClose:return this.state===mt.Closed;case ot.Manual:return this._results!==null;case ot.OnEventEnd:return this.context.event.state===he.Finished;case ot.Never:return!1;case ot.Always:default:return!0}}get results(){return this.canShowResults?this._results:null}set results(t){JSON.stringify(t)!==JSON.stringify(this.results)&&(this._results=t,this.canShowResults&&this.emit("results"))}get correctOption(){return this._correctOption}set correctOption(t){this._correctOption=t}get isCorrectOptionRevealed(){return this._correctOption!==null}};ke=new Map;vl=ye(async e=>{e.on("history",va),e.history!==null&&va(e.history),await wl(e.context.sdk.options.host),await gl(e)},e=>e.id);Sl=ye(async e=>{(await ht(e)).on("message",El)},e=>e);Ng=ye(async(e,t)=>(await Bo(e),Array.from(ke.values()).find(s=>s.id===t)||null),(e,t)=>t),Al=ye(async e=>(await Bo(e),Array.from(ke.values()).filter(t=>t.eventId===e.id).sort((t,n)=>t.publishedAt-n.publishedAt)),e=>e.id,{clearOnResolve:!0});(function(e){e.Opened="opened",e.Closed="closed"})(Je||(Je={}));qo=class extends z{constructor(t,n){super(),this.host=t,this.id=n,this.state=Je.Closed,this.lastCount=0,this.connect=null,this.boundHandleMessage=this.handleMessage.bind(this),this.boundHandleTimeout=this.handleTimeout.bind(this)}async init(){this.connect=await ht(this.host),this.connect.on("message",this.boundHandleMessage)}get isOpened(){return this.state===Je.Opened}handleMessage(t){let{id:n,klass:s,data:o}=t;if(!(n!==this.id||s!==Xe.SubsCounter))try{let r=JSON.parse(o[0]);this.handleCounterUpdate(r.counter),this.resetTimeout(r.next_update_at)}catch{Sa.warn("Couldn\'t parse subscounter message.")}}handleCounterUpdate(t){if(t<0)return;let n=!1,s=!1;this.lastCount!==t&&(n=!0,this.lastCount=t),this.state===Je.Closed&&(s=!0,this.state=Je.Opened),n&&this.emit("updated",this.lastCount),s&&this.emit("state",Je.Opened)}handleTimeout(){this.state=Je.Closed,this.emit("state",Je.Closed)}resetTimeout(t){clearTimeout(this.closeTimeout),this.closeTimeout=setTimeout(this.boundHandleTimeout,(t-Ke()+3)*1e3)}destroy(){this.connect!==null&&this.connect.off("message",this.boundHandleMessage)}};Ro=new Map,Pg=ye(async(e,t)=>{if(Ro.has(t))return Ro.get(t);let n=new qo(e,t);return await n.init(),Ro.set(t,n),n},(e,t)=>t)});function Ia(e=15e3){let t=new Map,n,s=!1;return{announce:()=>{for(let r of[...t.keys()])r()},subscribe(r,i){return t.set(r,i),()=>{t.delete(r)}},start(r){s||n!==void 0||(n=setInterval(()=>{for(let[i,a]of[...t])(!r||a?.())&&i()},e))},stop(){s=!0,clearInterval(n),t.clear()}}}var Na=ee(()=>{"use strict"});function Il(e){let t;try{t=new URL(e??"").searchParams}catch{return"none"}return t.get("micBridgeId")===null?"none":parseInt(t.get("micBridgeVersion")??"",10)>=2?"v2":"legacy"}function Pl(e){let{kit:t,local:n,timeout:s=()=>{}}=e;if(e.bridge==="none")return t;let o=e.answerMs??1500,r,i=()=>{r=!1,s(1)};e.bridge==="legacy"?i():s(o+500);let a=d=>{if(r===!1)return d(n);if(r)return d(t);let u=d(t).finally(()=>{r===void 0&&(r=!0,s(Nl))});return new Promise((c,g)=>{let y=setTimeout(()=>{i(),u.catch(()=>{}),d(n).then(c,g)},o);u.then(c,g).finally(()=>clearTimeout(y))})};return{read:d=>a(u=>u.read(d)),write:(d,u)=>a(c=>c.write(d,u)),remove:d=>a(u=>u.remove(d))}}var Nl,Rl,Pa,Ra=ee(()=>{"use strict";kt();zn();Nl=2e4;Pa=()=>Rl??=Pl({bridge:Il(globalThis.location?.href),kit:{read:Ot,write:At,remove:Bn},local:{read:async e=>Pe.getItem(e),write:async(e,t)=>Pe.setItem(e,t),remove:async e=>Pe.removeItem(e)},timeout:ji})});var La={};Vo(La,{createMonterosaPlatform:()=>Ll});function zo(){let t={...ua()};return{declared:Object.keys(t).length>0,categories:t}}async function Ma(e,t){return t?await mn(t,e):(await Ea(e)).find(s=>s.state==="active")}function Ml(e,t){return Di({host:e,projectId:t},`gamestage:${e}:${t}`)}async function Ll(e){let t=Kt(),n={},s=[],o=Ia(e.pollMilliseconds),r=o.announce;s.push(o.stop);let i=new Set,a,d={enabled:!1},u=Ds(e.host),c=Ml(u,e.projectId),g=Pa(),y=async()=>{try{let w=await Ut(c);b(w);let h=at(w?.fields);d=zt(w?.fields);let N=await Ma(w,e.eventId);if(a=N?.id??a,N){let R=at(N.fields),k={...h.labels,...R.labels},H={...h.options,...R.options};Object.assign(h,R),Object.keys(k).length>0&&(h.labels=k),Object.keys(H).length>0&&(h.options=H)}for(let R of Object.keys(n))delete n[R];Object.assign(n,h);for(let R of[...i])R(n);f="studio",l=h,v?.write(e.projectId,h)}catch{}},b=w=>{if(!(!e.locale||!w||typeof w!="object"))try{w.locale=e.locale}catch{}},T=w=>{for(let h of Object.keys(n))delete n[h];Object.assign(n,w);for(let h of[...i])h(n)},f="none",l,v=e.rememberSettings===!1?void 0:ti({store:g,consent:e.settingsConsent??zo}),p=v?await v.read(e.projectId):null;p&&(Object.assign(n,p),f="device");let C,S=new Promise(w=>C=w),_=(async()=>{let w=!1;try{let h=await Wn(u);C(h),s.push(un(h,N=>t.sample(N*1e3))),s.push(()=>Qn(h)),await Promise.race([Yn(h),new Promise((N,R)=>setTimeout(()=>R(new Error("mesh connect timed out")),e.connectTimeoutMs??8e3))]),w=!0}catch{C(null)}try{let h=await Promise.race([Ut(c),new Promise((k,H)=>setTimeout(()=>H(new Error("studio settings read timed out")),e.connectTimeoutMs??8e3))]);b(h);let N=at(h?.fields);d=zt(h?.fields);let R=await Ma(h,e.eventId);if(a=R?.id,R){let k=at(R.fields),H={...N.labels,...k.labels},ue={...N.options,...k.options};Object.assign(N,k),Object.keys(H).length>0&&(N.labels=H),Object.keys(ue).length>0&&(N.options=ue)}return T(N),f="studio",l=N,v?.write(e.projectId,N),R&&w&&(s.push(Oa(R,r)),s.push(Ca(R,()=>{y()}))),h&&w&&s.push(wa(h,()=>{y()})),w&&!!R}catch{return!1}})();p?_.then(o.start):o.start(await _);let x=new Set;return s.push(Ao(()=>{let w=zo();for(let h of[...x])h(w)})),{kind:"monterosa",projectId:c.options.projectId,get eventId(){return a},async elementFields(w){let h=await Ut(c),N=await mn(w,h);return N?(await ka(N)).map(k=>({id:k.id,contentType:String(k.contentType),fields:k.fields??{}})):[]},clock:t,presentation:n,get signInSettings(){return d},settingsSource:()=>f,rememberSettings(){l&&v?.write(e.projectId,l)},consent:zo,onConsentChanged(w){return x.add(w),()=>x.delete(w)},onPresentationChanged(w){return i.add(w),()=>i.delete(w)},declareConsent(w){try{return la(w),!0}catch{return!1}},onRoundAnnounced:o.subscribe,subscribeLive(w,h){let N=!1,R=!1,k=null,H=!1,ue=[];h.status({state:"connecting"});let be=async $=>{R=!1;try{await Mt($,w)}catch{return}N||(R=!0,h.synced(),h.status({state:"live"}))};return S.then($=>{if(!N){if(!$)return h.status({state:"unavailable"});k=$,ue.push(ra($,ge=>{if(ge.channel!==w)return;let _e;try{_e=JSON.parse(ge.body[0]??"")}catch{return}h.message(String(ge.klass),_e,!R)}),sa($,(ge,_e)=>h.status({state:typeof navigator<"u"&&navigator.onLine===!1?"offline":ge>1?"reconnecting":"connecting",attempt:ge,retryAt:Date.now()+_e*1e3})),oa($,()=>{R=!1,H=!0,h.status({state:"reconnecting"})}),un($,()=>{H&&(H=!1,be($))})),be($)}}),()=>{if(N=!0,ue.forEach($=>$()),k)try{Lt(k,w)}catch{}}},emit(w){ma(w.name,{...On(w.properties),at:w.at})},storage:g,stop(){for(let w of s.splice(0))w();x.clear()}}}var Da=ee(()=>{"use strict";Dn();ko();fa();ha();Aa();Vt();$s();St();vs();Wt();Ls();Na();Ra()});var Ko="gs-gate-style",za=`\n.gs-gate{position:fixed;inset:0;z-index:2147483100;display:grid;place-items:center;padding:16px;background:rgba(10,10,14,.72);box-sizing:border-box}\n.gs-gate__card{width:100%;max-width:24rem;box-sizing:border-box;display:grid;gap:14px;padding:22px 20px;border-radius:20px;background:var(--gs-gate-surface,#fff);color:var(--gs-gate-ink,#1b1c1f);font-family:inherit;font-size:17px;line-height:1.45;box-shadow:0 10px 30px rgba(0,0,0,.25)}\n.gs-gate__title{margin:0;font-size:22px;line-height:1.25}\n.gs-gate__note{margin:0;font-weight:600}\n.gs-gate__choice{display:flex;gap:12px;align-items:flex-start;cursor:pointer}\n.gs-gate__choice input{width:22px;height:22px;margin:2px 0 0;flex:none;accent-color:var(--gs-gate-accent,#1b1c1f)}\n.gs-gate__continue{min-height:48px;padding:12px 20px;border:0;border-radius:12px;background:var(--gs-gate-accent,#1b1c1f);color:var(--gs-gate-on-accent,#fff);font:inherit;font-weight:650;cursor:pointer}\n.gs-gate__continue:disabled{opacity:.45;cursor:default}\n.gs-gate [hidden]{display:none!important}\n.gs-gate__not-me{justify-self:center;min-height:44px;padding:8px 12px;border:0;background:none;color:inherit;font:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer}\n.gs-gate__sorry{margin:0;font-size:19px;font-weight:600}\n.gs-gate :is(input,button):focus-visible{outline:3px solid var(--gs-gate-accent,#1b1c1f);outline-offset:3px}\n`;function ts(e){let t=e.GAMESTAGE_GATE;if(!t||typeof t!="object")return;let n=t,s=typeof n.minimumAge=="number"&&n.minimumAge>0?n.minimumAge:void 0,o=Array.isArray(n.territories)?n.territories.filter(r=>typeof r=="string"&&/^[A-Z]{2}$/.test(r)):[];if(!(!s&&!o.length))return{...s?{minimumAge:s}:{},...o.length?{territories:o}:{},...typeof n.note=="string"&&n.note.trim()?{note:n.note.trim()}:{}}}function ns(e,t="en-GB"){let n;try{n=new Intl.DisplayNames([t],{type:"region"})}catch{}let s=new Set(["GB","US","AE","NL","PH","CZ","DO","BS","GM","MV"]),o=e.map(r=>`${s.has(r)?"the ":""}${n?.of(r)??r}`);return o.length<=1?o.join(""):`${o.slice(0,-1).join(", ")} or ${o[o.length-1]}`}var ss=e=>`gamestage:gate:${e}`,jt=e=>JSON.stringify([e.minimumAge??null,e.territories??[]]);function Wo(e,t,n){try{let s=n?.getItem(ss(e));if(!s)return;let o=JSON.parse(s);return o.gate!==jt(t)?void 0:o.qualified===!1?"not_qualified":"qualified"}catch{return}}function Yo(e,t,n){return Wo(e,t,n)==="qualified"}function os(e,t=Ha()){try{t?.removeItem(ss(e))}catch{}}function Ha(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Va(e,t){let n=e.minimumAge?` aged ${e.minimumAge} and over`:"",s=e.territories?.length?` in ${ns(e.territories,t)}`:"";return`Sorry, this game is for people${n}${s}.`}function bn(e,t,n={}){let s=n.document??(typeof document>"u"?void 0:document),o=n.storage??(typeof localStorage>"u"?void 0:localStorage);if(!e||!s||Yo(t,e,o))return Promise.resolve();let r=x=>{try{o?.setItem(ss(t),JSON.stringify({gate:jt(e),qualified:x,at:i().toISOString()}))}catch{}},i=n.now??(()=>new Date);if(!s.getElementById?.(Ko)){let x=s.createElement("style");x.id=Ko,x.textContent=za,s.head?.append(x)}let a=(x,w)=>{let h=s.createElement(x);return w&&(h.textContent=w),h},d=a("div");d.className="gs-gate",d.setAttribute("role","dialog"),d.setAttribute("aria-modal","true"),d.setAttribute("aria-labelledby","gs-gate-title");let u=a("form");u.className="gs-gate__card";let c=a("h2","Before you play");if(c.id="gs-gate-title",c.className="gs-gate__title",u.append(c),e.note){let x=a("p",e.note);x.className="gs-gate__note",u.append(x)}let g=[],y=(x,w)=>{let h=a("label");h.className="gs-gate__choice";let N=a("input");N.type="checkbox",N.setAttribute("data-gs-declare",x),h.append(N,a("span",w)),g.push(N),u.append(h)};e.territories?.length&&y("territory",`I\'m in ${ns(e.territories,n.locale)}.`),e.minimumAge&&y("age",`I\'m ${e.minimumAge} or over.`);let b=a("button","Continue");b.type="submit",b.className="gs-gate__continue",b.setAttribute("data-gs-gate-continue",""),b.disabled=!0,u.append(b);let T=a("button","I don\'t meet these");T.type="button",T.className="gs-gate__not-me",T.setAttribute("data-gs-gate-not-me",""),u.append(T);let f=a("div");f.className="gs-gate__card gs-gate__exit";let l=a("p",Va(e,n.locale));l.className="gs-gate__sorry";let v=a("button","Go back");v.type="button",v.className="gs-gate__not-me",v.setAttribute("data-gs-gate-back",""),f.append(l,v);let p=x=>{u.hidden=x,f.hidden=!x};T.onclick=()=>{r(!1),p(!0)},v.onclick=()=>{p(!1),g[0]?.focus?.()},p(Wo(t,e,o)==="not_qualified"),d.append(u,f);let C=()=>Array.from(d.querySelectorAll?.("input, button")??[]).filter(x=>!x.disabled&&!x.closest?.("[hidden]"));d.onkeydown=x=>{if(x.key!=="Tab")return;let w=C();if(!w.length)return;let h=w[0],N=w[w.length-1],R=s.activeElement;x.shiftKey&&(R===h||!d.contains?.(R))?(x.preventDefault(),N.focus()):!x.shiftKey&&(R===N||!d.contains?.(R))&&(x.preventDefault(),h.focus())};let S=x=>{d.isConnected&&!d.contains?.(x.target)&&C()[0]?.focus()};s.addEventListener?.("focusin",S);let _=()=>s.removeEventListener?.("focusin",S);for(let x of g)x.onchange=()=>{b.disabled=!g.every(w=>w.checked)};return new Promise(x=>{u.onsubmit=w=>{w.preventDefault?.(),g.every(h=>h.checked)&&(r(!0),_(),d.remove?.(),x())},(s.body??s.documentElement)?.append(d),g[0]?.focus?.()})}var W={notify:"/play/v1/games/{game}/notify",notifyConfirm:"/play/v1/games/{game}/notify/confirm",notifyResend:"/play/v1/games/{game}/notify/resend",runtime:"/play/v1/games/{game}/runtime",currentRound:"/play/v1/games/{game}/rounds/current",rounds:"/play/v1/games/{game}/rounds",roundsMine:"/play/v1/games/{game}/rounds/mine",nextRound:"/play/v1/games/{game}/rounds/next",round:"/play/v1/games/{game}/rounds/{round}",plays:"/play/v1/games/{game}/rounds/{round}/plays",session:"/play/v1/games/{game}/session",restoreSession:"/play/v1/games/{game}/session/restore",guestToken:"/play/v1/games/{game}/guest-token",gameToken:"/play/v1/games/{game}/game-token",commentsToken:"/play/v1/games/{game}/comments-token",commentsKeys:"/play/v1/comments-keys",roundState:"/play/v1/games/{game}/rounds/{round}/players/me",profile:"/play/v1/games/{game}/players/me/profile",identityOptions:"/play/v1/games/{game}/identity",identity:"/play/v1/games/{game}/players/me/identity",nameTicket:"/play/v1/games/{game}/name-ticket",recoveryCode:"/play/v1/games/{game}/players/me/recovery-code",declaration:"/play/v1/games/{game}/players/me/declaration",roundStats:"/play/v1/games/{game}/rounds/{round}/stats",leaderboard:"/play/v1/games/{game}/leaderboard",editionLeaderboard:"/play/v1/games/{game}/leaderboard/edition"};var Be={rooms:"/play/v1/games/{game}/rooms",roomJoin:"/play/v1/games/{game}/rooms/join",room:"/play/v1/games/{game}/rooms/{room}",roomStart:"/play/v1/games/{game}/rooms/{room}/start",roomLeave:"/play/v1/games/{game}/rooms/{room}/leave",roomPresence:"/play/v1/games/{game}/rooms/{room}/presence",roomPlay:"/play/v1/games/{game}/rooms/{room}/play",roomBoard:"/play/v1/games/{game}/rooms/{room}/board"};var Qo="penalty_v1";var Ka="balanced_v1",Jo={aimX:{min:-1200,max:1200},aimY:{min:-200,max:1200},power:{min:0,max:1e3}},Xo={postX:1e3,barY:1e3,postWidth:60,barHeight:60,ballRadius:40,keeperStart:{x:0,y:420}},Wa="shoot";function bt(e){return{op:Wa,model:Qo,shotIndex:e.shotIndex,aimX:e.aimX,aimY:e.aimY,power:e.power}}function _n(e){let t=e?.progress;if(!t||t.kind!=="shoot")return;let n=Array.isArray(t.shots)?t.shots:[];return{kind:"shoot",model:t.model??Qo,profile:t.profile??Ka,goals:typeof t.goals=="number"?t.goals:0,shots:n}}function vn(e){return e?.shots.at(-1)}function Ya(e){return{...e.picks?{picks:e.picks}:{},...e.answers?{answers:e.answers}:{},...e.op?{op:e.op}:{},...e.centre!==void 0?{centre:e.centre}:{},...e.board!==void 0?{board:e.board}:{},...e.operation??{}}}var Sn=e=>`gamestage-session:${e}`;function rs(e,t=typeof localStorage>"u"?void 0:localStorage){return t?.getItem(Sn(e))??void 0}var F=(e,t,n,s)=>e.replace("{game}",encodeURIComponent(t)).replace("{round}",encodeURIComponent(n??"")).replace("{room}",encodeURIComponent(s??""));function is(){let e=new Uint8Array(12);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}var _t=class extends Error{status;code;retryable;detail;constructor(t,n,s,o,r={}){super(s),this.status=t,this.code=n,this.retryable=o,this.detail=r,this.name="PlayerApiError"}},Qa=6e4;function Ja(e){let t=e.split(".")[1];if(t)try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),s=n+"=".repeat((4-n.length%4)%4),o=JSON.parse(atob(s));return typeof o.exp=="number"&&Number.isFinite(o.exp)?o.exp*1e3:void 0}catch{return}}function Zo(e){let t=e.fetch??globalThis.fetch.bind(globalThis),n=e.baseUrl.replace(/\\/+$/,""),s=e.storage??(typeof localStorage>"u"?void 0:localStorage),o=e.session??s?.getItem(Sn(e.game))??void 0,r;async function i(){return o||(r??=(async()=>{let p=await t(`${n}${F(W.session,e.game)}`,{method:"POST"});if(!p.ok)return;let C=await p.json();if(C.token)return o=C.token,s?.setItem(Sn(e.game),o),o})().finally(()=>{r=void 0}),r)}let a=e.now??Date.now,d,u;async function c(p=!1){return p&&(d=void 0),d&&a()<d.renewAt?d.token:(d=void 0,u??=(async()=>{let C=await l(F(W.guestToken,e.game),{method:"POST"});if(!C.token)throw new _t(200,"unknown","The Engine did not issue a guest token.",!1);let S=Ja(C.token);return d=S===void 0?void 0:{token:C.token,renewAt:S-Qa},C.token})().finally(()=>{u=void 0}),u)}async function g(){let p=await l(F(W.commentsToken,e.game),{method:"POST"});if(!p.token)throw new _t(200,"unknown","The Engine did not issue a comments token.",!1);return p.token}let y,b;async function T(){return y&&a()<y.renewAt?y.token:(b??=(async()=>{let p=await c(),C=await t(e.spaceAuthUrl??`${n}/api/auth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"jwt_bearer",assertion:p}).toString()}),S=await C.json().catch(()=>({}));if(!C.ok||!S.access_token)throw C.status<500&&(d=void 0),new _t(C.status,"space_sign_in_refused",S.message??"The Space did not accept the guest token.",C.status>=500);let _=(S.expires_in??3600)*1e3;return y={token:S.access_token,renewAt:a()+Math.max(_-6e4,0)},S.access_token})().finally(()=>{b=void 0}),b)}let f=()=>typeof e.identity=="function"?e.identity():e.identity;async function l(p,C,S=!0){let _=await i(),x=await f(),w=await t(`${n}${p}`,{...C,headers:{"content-type":"application/json",..._?{"x-gamestage-player":_}:{},...x?{authorization:`Bearer ${x}`}:{},...C?.headers??{}}}),h=await w.json().catch(()=>({}));if(!w.ok){let N=h.error;if(S&&w.status===401&&N?.code==="session_required")return o===_&&(o=void 0),l(p,C,!1);throw new _t(w.status,N?.code??"unknown",N?.message??w.statusText,N?.retryable??!1,N??{})}return h}return{guestToken:c,commentsToken:g,spaceToken:T,subscribeNotify:p=>l(F(W.notify,e.game),{method:"POST",body:JSON.stringify(p)}),confirmNotify:p=>l(F(W.notifyConfirm,e.game),{method:"POST",body:JSON.stringify(p)}),resendNotify:p=>l(F(W.notifyResend,e.game),{method:"POST",body:JSON.stringify(p)}),getRuntime:()=>l(F(W.runtime,e.game)),getCurrentRound:()=>l(F(W.currentRound,e.game)),getRound:p=>l(F(W.round,e.game,p)),getNextRound:()=>l(F(W.nextRound,e.game)),getRounds:()=>l(F(W.rounds,e.game)),getPlayedRounds:()=>l(F(W.roundsMine,e.game)),getRoundState:p=>l(F(W.roundState,e.game,p)),getRoundStats:p=>l(F(W.roundStats,e.game,p)),getProfile:()=>l(F(W.profile,e.game)),getIdentityOptions:()=>l(F(W.identityOptions,e.game)),createRoom:p=>l(F(Be.rooms,e.game),{method:"POST",body:JSON.stringify({name:p})}),joinRoom:(p,C)=>l(F(Be.roomJoin,e.game),{method:"POST",body:JSON.stringify({code:p,name:C})}),getRoom:p=>l(F(Be.room,e.game,void 0,p)),startRoom:p=>l(F(Be.roomStart,e.game,void 0,p),{method:"POST"}),leaveRoom:p=>l(F(Be.roomLeave,e.game,void 0,p),{method:"POST"}),roomPresence:p=>l(F(Be.roomPresence,e.game,void 0,p),{method:"POST"}),getRoomPlay:p=>l(F(Be.roomPlay,e.game,void 0,p)),getRoomBoard:p=>l(F(Be.roomBoard,e.game,void 0,p)),setIdentity:p=>l(F(W.identity,e.game),{method:"POST",body:JSON.stringify(p)}),getNameTicket:()=>l(F(W.nameTicket,e.game),{method:"POST"}),declare:p=>l(F(W.declaration,e.game),{method:"POST",body:JSON.stringify({gate:p,qualified:!0})}),getLeaderboard:()=>l(F(W.leaderboard,e.game)),getEditionLeaderboard:()=>l(F(W.editionLeaderboard,e.game)),getRecoveryStatus:()=>l(F(W.recoveryCode,e.game)),issueRecoveryCode:()=>l(F(W.recoveryCode,e.game),{method:"POST"}),restoreFromRecoveryCode:async p=>{let C=await l(F(W.restoreSession,e.game),{method:"POST",body:JSON.stringify({code:p})});return o=C.token,r=void 0,s?.setItem(Sn(e.game),o),C},play:v,shoot:(p,C,S)=>v(p,{operation:bt(C),roundVersion:C.roundVersion,challengeInstanceId:C.challengeInstanceId},S)};function v(p,C,S){return l(F(W.plays,e.game,p),{method:"POST",body:JSON.stringify({idempotency_key:S,round_version:C.roundVersion,challenge_instance_id:C.challengeInstanceId??null,payload:Ya(C),...C.room?{room:C.room}:{}})})}}var vt=class extends Error{constructor(n,s,o){super(s);this.status=n;this.code=s;this.retryAfterSeconds=o;this.name="ArcadeError"}status;code;retryAfterSeconds;get retryable(){return this.code==="rate_limited"||this.code==="engine_busy"||this.status===0}get needsSignIn(){return this.code==="sign_in_required"}get runDidNotCount(){return/^(score_|duration_|run_)/.test(this.code)}},Xa="/game-token";function as(e){let t=e.api.replace(/\\/$/,"")+(e.basePath??"/api/arcade"),n=e.fetch??fetch,s=e.newKey??(()=>crypto.randomUUID()),o=encodeURIComponent(e.game);async function r(){let a=await e.gameToken?.().catch(()=>{});return a?{token:a,prefix:Xa}:{token:await e.token(),prefix:""}}async function i(a,d,u,c={}){let g=async()=>{let y;try{let{token:T,prefix:f}=await r();y=await n(t+f+d,{method:a,headers:{authorization:`Bearer ${T}`,...u===void 0?{}:{"content-type":"application/json"},...c},...u===void 0?{}:{body:JSON.stringify(u)}})}catch{throw new vt(0,"network_error")}let b=await y.json().catch(()=>({}));if(!y.ok)throw new vt(y.status,b.message??"unknown",b.retryAfterSeconds);return b.data};try{return await g()}catch(y){if(y instanceof vt&&y.status===0)return g();throw y}}return{start:a=>i("POST",`/games/${o}/runs`,{build:a.build},{"idempotency-key":s()}),finish:(a,d)=>i("POST",`/runs/${encodeURIComponent(a)}/result`,{score:d.score,playedMs:d.playedMs,metrics:d.metrics??{}}),board:(a="all-time",d={})=>{let u=new URLSearchParams;d.limit!==void 0&&u.set("limit",String(d.limit)),d.offset!==void 0&&u.set("offset",String(d.offset));let c=u.toString();return i("GET",`/boards/${o}/${encodeURIComponent(a)}${c?`?${c}`:""}`)},me:()=>i("GET",`/games/${o}/me`),setName:a=>i("PUT",`/games/${o}/me/name`,{ticket:a})}}var Za=e=>`edition-${e}`;function ec(e){let n=(e??"").trim().toLowerCase().replace(/[^a-z0-9_.]/g,"").replace(/\\.{2,}/g,"."),s=/[a-z]/.test(n),r=(s?n:`fan${n?`_${n}`:""}`).slice(0,30);return(r.length>=3?r:s?r.padEnd(3,"0"):r.padEnd(3,"a"))||"fan"}function cs(e){let t=e.fetch??((...a)=>fetch(...a)),n,s,o=async(a=!1)=>{try{let d=await e.fanToken(a),u=await t(`${e.api}/api/auth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"jwt_bearer",assertion:d}).toString()}),c=await u.json().catch(()=>({}));return!u.ok||!c.access_token?!a&&u.status<500?o(!0):null:(n=c.access_token,c.access_token)}catch{return null}},r=async()=>n||(s??=o().finally(()=>{s=void 0}),s);async function i(a,d,u=!1,c=!0){let g=c?await r():void 0;if(c&&!g)return null;try{let y=await t(`${e.api}${a}`,{...d,headers:{...d?.body!==void 0?{"content-type":"application/json"}:{},...g?{authorization:`Bearer ${g}`}:{},...d?.headers??{}}});return c&&y.status===401&&!u?(n=void 0,s=void 0,i(a,d,!0)):y.ok?await y.json().catch(()=>null):null}catch{return null}}return{suggestName:ec,async list(){return((await i(`/api/v1/comments/topics/${encodeURIComponent(e.topicId)}/messages?sort=oldest&top_level=true`,void 0,!1,!1))?.data??[]).sort((u,c)=>u.received_at-c.received_at)},async canPost(){return await r()!==null},async post(a){let u=(await i(`/api/v1/comments/topics/${encodeURIComponent(e.topicId)}`,{method:"POST",body:JSON.stringify({text:a})}))?.data?.message_id;return u?{message_id:u}:null},async me(){let d=(await i(`/api/v1/comments/me?topic_id=${encodeURIComponent(e.topicId)}`,void 0))?.data;return d&&typeof d.user_id=="string"?d:null},async setName(a){let u=(await i("/api/v1/comments/me/display-name",{method:"PUT",body:JSON.stringify({display_name:a})}))?.data;return u?.allowed!==!1&&u?.display_name?{display_name:u.display_name}:null}}}St();var wt=class extends Error{constructor(n,s,o){super(s);this.status=n;this.code=s;this.retryAfterSeconds=o;this.name="QuizError"}status;code;retryAfterSeconds;get retryable(){return lc.has(this.code)||this.status===0}get needsSignIn(){return this.code==="sign_in_required"}get questionClosed(){return this.code==="question_closed"}get needsNickname(){return this.code==="nickname_required"||this.code==="nickname_refused"||this.code==="nickname_taken"}},lc=new Set(["rate_limited","engine_busy","nickname_check_unavailable","question_not_open"]),Ar=5,uc="/game-token",gc=30;function ys(e){let t=e.api.replace(/\\/$/,"")+(e.basePath??"/api/quiz"),n=e.fetch??fetch,s=e.sleep??(c=>new Promise(g=>setTimeout(g,c))),o=e.retries??3,r=encodeURIComponent(e.game),i=c=>encodeURIComponent(c);async function a(){let c=await e.gameToken?.().catch(()=>{});return c?{token:c,prefix:uc}:{token:await e.token(),prefix:""}}async function d(c,g,y){let b=async()=>{let f;try{let{token:v,prefix:p}=await a();f=await n(t+p+g,{method:c,headers:{authorization:`Bearer ${v}`,...y===void 0?{}:{"content-type":"application/json"}},...y===void 0?{}:{body:JSON.stringify(y)}})}catch{throw new wt(0,"network_error")}let l=await f.json().catch(()=>({}));if(!f.ok){let v=l.message&&/^[a-z_]+$/.test(l.message)?l.message:f.status===429?"rate_limited":"unknown";throw new wt(f.status,v,l.retryAfterSeconds)}return l.data},T=0;for(let f=0;;f++)try{return await b()}catch(l){if(!(l instanceof wt)||!l.retryable||f>=o)throw l;let v=l.status===0?0:Math.min(l.retryAfterSeconds??1,gc);if(l.code==="question_not_open"){if(T>=Ar)throw l;v=Math.min(v,Ar-T),T+=v}await s(v*1e3)}}let u=(c={})=>{let g=new URLSearchParams;c.limit!==void 0&&g.set("limit",String(c.limit)),c.cursor!==void 0&&g.set("cursor",c.cursor);let y=g.toString();return y?`?${y}`:""};return{nickname:c=>d("POST",`/games/${r}/nickname`,{nickname:c}),me:()=>d("GET",`/games/${r}/me`),get:c=>d("GET",`/quizzes/${i(c)}`),questions:async c=>e.words?e.words(c):[],outcomes:async c=>e.outcomeWords?e.outcomeWords(c):[],outcomeShares:async c=>{try{let g=await d("GET",`/quizzes/${i(c)}/outcomes`),y=Array.isArray(g?.outcomes)?g.outcomes:[],b=typeof g?.total=="number"?g.total:0;return b<=0?[]:y.flatMap(T=>typeof T?.outcomeId=="string"&&typeof T?.count=="number"?[{outcomeId:T.outcomeId,share:Math.min(1,Math.max(0,T.count/b))}]:[])}catch{return[]}},start:c=>d("POST",`/quizzes/${i(c)}/plays`,{}),answer:(c,g)=>d("POST",`/quizzes/${i(c)}/answers`,{answers:g.map(y=>({question:y.question,option:y.option}))}),result:c=>d("GET",`/quizzes/${i(c)}/result`),board:(c,g)=>d("GET",`/quizzes/${i(c)}/board${u(g)}`),gameBoard:c=>d("GET",`/games/${r}/board${u(c)}`)}}function bs(e,t){let n=a=>typeof a=="string"&&a.trim()?a.trim():void 0,s=n(t[hr]);if(!s)return;let o=pr.flatMap(a=>{let d=n(t[mr(a)]),u=xn(t[vr(a)]);return d?[{id:a,text:d,...u?{image:u}:{}}]:[]}),r=xn(t[yr]),i=xn(t[_r]);return{id:e,question:s,options:o,...r?{image:{url:r,alt:n(t[br])??""}}:{},...i?{media:{url:i}}:{}}}function _s(e,t){let n=a=>typeof a=="string"&&a.trim()?a.trim():void 0,s=n(t[Sr]);if(!s)return;let o=n(t[wr]),r=n(t[Er]),i=xn(t[Cr]);return{id:e,name:s,...o?{verdict:o}:{},...r?{why:r}:{},...i?{image:{url:i,alt:n(t[Tr])??""}}:{}}}function xn(e){let t=typeof e=="string"?e:e&&typeof e=="object"&&typeof e.url=="string"?e.url:void 0;if(!(!t||!t.trim()))try{let n=new URL(t.trim());return n.protocol==="https:"?n.href:void 0}catch{return}}var Ir=["moment"];function Nr(e,t){let n=t?.id;return e==="side"&&(typeof n=="string"||typeof n=="number")?`side:${n}`:e}async function Pr(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new Error("liveChannel needs WebCrypto (a browser, or Node 18+)");let s=new Uint8Array(await n.digest("SHA-1",new TextEncoder().encode(`gamestage/live/${e}/${t}`)));s[6]=s[6]&15|80,s[8]=s[8]&63|128;let o=[...s.subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`l-${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Rr(e){return e.rows.map(t=>{let n={elapsed:0,sides:[]};return e.columns.forEach((s,o)=>{if(s==="elapsed")return void(n.elapsed=t[o]);let r=s.indexOf("."),i=Number(s.slice(0,r));(n.sides[i]??={})[s.slice(r+1)]=t[o]}),n})}function kn(e,t={}){let n=t.provider??"sportmonks",s=t.contest!==void 0?String(t.contest):null,o=new Map,r=new Map,i=new Set,a={state:"idle",contest:null,last:null},d=null,u=null,c=0,g=p=>{a={...a,...p};for(let C of[...i])C(a)},y=()=>o.get("state")?.sides.map(p=>p.id)??[],b=(p,C)=>p==="timeline"&&C&&typeof C=="object"&&"columns"in C?Rr(C):C;function T(p,C,S){let _=b(p,C);o.set(Nr(p,_),_),a={...a,last:Date.now()};for(let x of r.get(p)??[])if(!(x.news&&S))try{x.fn(_)}catch(w){console.error(w)}}async function f(p){if(p===d)return;let C=++c;if(u?.(),u=null,o.clear(),d=p,!p)return g({state:"idle",contest:null,attempt:void 0,retryAt:void 0});if(!e.subscribeLive)return g({state:"unavailable",contest:p});g({state:"connecting",contest:p,attempt:void 0,retryAt:void 0});let S=await Pr(n,p);C===c&&(u=e.subscribeLive(S,{message:(_,x,w)=>T(_,x,w),synced:()=>g({last:a.last}),status:_=>g({..._,contest:p})}))}let l=()=>s??e.presentation.liveContest?.trim()??null;f(l()||null);let v=s?()=>{}:e.onPresentationChanged(()=>{f(l()||null)});return{get contest(){return d},get status(){return a},state:()=>o.get("state"),clock:()=>o.get("clock"),sides:()=>y().map(p=>o.get(`side:${p}`)).filter(p=>!!p),moments:()=>o.get("moments")??[],timeline:()=>o.get("timeline")??[],health:()=>o.get("health"),on(p,C,S={}){let _=S.news??Ir.includes(p),x={fn:C,news:_};if(r.set(p,[...r.get(p)??[],x]),!_)for(let[w,h]of o)(w===p||w.startsWith(`${p}:`))&&x.fn(h);return()=>r.set(p,(r.get(p)??[]).filter(w=>w!==x))},onStatus(p){return i.add(p),p(a),()=>i.delete(p)},stop(){c++,v(),u?.(),u=null,g({state:"idle"})}}}St();ls();vs();Vt();Vt();var Dr=new Map,$r=e=>{let t=Dr.get(e);if(t)return t;let n=new Promise((s,o)=>{if(typeof document>"u"){o(new Error("no document"));return}let r=document.createElement("script");r.src=e,r.async=!0,r.crossOrigin="anonymous",r.addEventListener("load",()=>s()),r.addEventListener("error",()=>o(new Error(`could not load ${e}`))),document.head.appendChild(r)});return Dr.set(e,n),n};var pc="https://fantenna.com/signal/v1.js";async function Gr(e){if(!e.serviceUrl||!e.projectId)return null;await(e.load??$r)(pc);let n=globalThis.FantennaSignal;if(!n)throw new Error("the Signal tag loaded without defining itself");let s=n.init({applicationId:e.game,endpoint:"",writeKey:"",fantenna:!1,consent:!0,monterosa:{enabled:!0,serviceUrl:e.serviceUrl,projectId:e.projectId},onObservation:e.onObservation?o=>{e.onObservation?.({name:`signal_${o.type}`,at:(e.now??(()=>Date.now()))(),properties:{...o.properties,signal_event_id:o.id,observed_at:o.occurredAt}})}:void 0});return s.start?.(),{track(o,r){s.track(o,{gamestage_game:e.game,...r??{}})},stop(){s.setConsent(!1),s.stop()}}}var Ss={atCapacity:{title:"Kitchen\'s at capacity",body:"This game is taking more players than it can serve right now. Nothing you did. Try again in a few minutes."},rateLimited:{title:"Too many requests from here",body:"This device is sending more requests than the game will take. Wait a moment and carry on."},cappedToday:{title:"That\'s all the plays for today",body:"This game has taken all the plays it can today. Nothing you did. Come back tomorrow."}};function ws(e){return e==="capped_today"?"cappedToday":"atCapacity"}var lt="gamestage-busy";function Es(e,t=Ss){let n=s=>{let o=e?.[s];return typeof o=="string"&&o.trim()?o:void 0};return{atCapacity:{title:n("busyTitle")??t.atCapacity.title,body:n("busyMessage")??t.atCapacity.body},rateLimited:{title:n("rateLimitedTitle")??t.rateLimited.title,body:n("rateLimitedMessage")??t.rateLimited.body},cappedToday:{title:t.cappedToday.title,body:n("cappedTodayNote")??t.cappedToday.body}}}function Cs(e,t={}){let n=t.document??globalThis.document??void 0,s=t.container??n?.body??null;if(!n||!s)return{close:()=>{}};let o=(t.copy??Ss)[e];n.getElementById(lt)?.remove();let r=n.createElement("div");r.id=lt,r.setAttribute("role","alertdialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-labelledby",`${lt}-title`),r.setAttribute("aria-describedby",`${lt}-body`),r.setAttribute("data-kind",e),t.retryAfterSeconds!==void 0&&r.setAttribute("data-retry-after",String(t.retryAfterSeconds)),r.style.cssText=["position:fixed","inset:0","z-index:2147483000","display:flex","align-items:flex-end","justify-content:center","padding:0","background:rgba(0,0,0,0.6)","font-family:inherit"].join(";");let i=n.createElement("div");i.style.cssText=["max-width:480px","width:100%","box-sizing:border-box","padding:20px 24px calc(24px + env(safe-area-inset-bottom, 0px))","border-radius:16px 16px 0 0","background:#fff","color:#111","text-align:center","box-shadow:0 -18px 40px -20px rgba(0,0,0,0.45)"].join(";");let a=n.createElement("div");a.setAttribute("aria-hidden","true"),a.style.cssText=["width:36px","height:4px","margin:0 auto 16px","border-radius:999px","background:rgba(17,17,17,0.18)"].join(";");let d=n.createElement("h2");d.id=`${lt}-title`,d.textContent=o.title,d.style.cssText="margin:0 0 8px;font-size:1.25rem;line-height:1.2";let u=n.createElement("p");u.id=`${lt}-body`,u.textContent=o.body,u.style.cssText="margin:0 0 20px;font-size:1rem;line-height:1.45";let c=n.createElement("button");c.type="button",c.textContent="Close",c.style.cssText=["appearance:none","border:0","cursor:pointer","padding:10px 20px","border-radius:999px","font:inherit","color:#fff","background:var(--gamestage-primary, #111)"].join(";");let g=()=>{n.removeEventListener("keydown",y),r.remove()},y=b=>{b.key==="Escape"&&g()};return c.addEventListener("click",g),r.addEventListener("click",b=>{b.target===r&&g()}),n.addEventListener("keydown",y),i.append(a,d,u,c),r.append(i),s.append(r),c.focus?.(),{close:g}}Wt();Ht();function Ts(e){return`gamestage:sign-in:v1:${e}`}function Ur(e,t){let n=t.toLowerCase(),s=`${e.toLowerCase()}.apps.`;if(!n.startsWith(s))return;let o=n.slice(s.length);return/^[a-z0-9.-]+\\.[a-z]{2,}$/.test(o)?`https://${o}`:void 0}function mc(e){try{let t=e.split(".")[1],n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),s=JSON.parse(n).exp;return typeof s=="number"?s:void 0}catch{return}}var hc="anon:test.";function yc(e){try{let t=e?.();return t?.startsWith(hc)?t:void 0}catch{return}}function Fr(e){let t=e.site??Ur(e.game,e.hostname),n=e.fetch??(typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0),s=()=>e.messages??e.document?.defaultView??void 0,o=e.now??(()=>Date.now()),r=new Set,i=t&&n?"checking":"off",a,d,u,c=f=>{if(f!==i){i=f;for(let l of r)try{l(f)}catch{}}},g=f=>{try{if(!e.store||!e.mayRemember?.())return;e.store.setItem(Ts(e.game),f)}catch{}},y=()=>{try{return e.store?.getItem(Ts(e.game))??null}catch{return null}},b=()=>!t||!n?Promise.resolve(i):(d??=(async()=>{try{let f=yc(e.session),l=await n(`${t}/hub/game-token`,{credentials:"include",cache:"no-store",...f?{headers:{"x-gamestage-player":f}}:{}}),v=l.ok?await l.json().catch(()=>({})):{};v.state==="granted"&&v.token?(a=v.token,c("granted"),g("granted")):v.state==="signed_out"?(a=void 0,c("signed-out")):v.state==="not_granted"?(a=void 0,c(y()==="dismissed"?"dismissed":"not-granted")):(a=void 0,c("not-available"))}catch{a=void 0,c("not-available")}return i})().finally(()=>{d=void 0}),d),T=()=>{u&&(s()?.removeEventListener("message",u.listener),u.host.remove(),u=void 0)};return{get state(){return i},begin:b,rememberedGranted:()=>y()==="granted",async token(){if(i!=="granted")return;let f=a?mc(a):void 0;return a&&f!==void 0&&f-60>o()/1e3?a:(await b(),i==="granted"?a:void 0)},offer(f,l={}){let v=e.document,p=f.playAs?.trim();if(i!=="not-granted"||!v||!t||!p||u)return;let C=new URL(`${t}/hub/play-as`);C.searchParams.set("game",e.game),C.searchParams.set("label",p),f.detail?.trim()&&C.searchParams.set("detail",f.detail.trim()),f.dismiss?.trim()&&C.searchParams.set("dismiss",f.dismiss.trim()),l.accent&&C.searchParams.set("accent",l.accent),l.onAccent&&C.searchParams.set("on",l.onAccent),l.text&&C.searchParams.set("text",l.text);let S=v.createElement("div");S.setAttribute("data-gamestage-sign-in",""),S.style.cssText=["position:fixed","left:16px","right:16px","bottom:16px","z-index:2147483000","max-width:480px","margin:0 auto","padding:12px 16px","border-radius:16px","box-shadow:0 8px 28px rgba(0,0,0,.18)",`background:${l.surface??"Canvas"}`,"visibility:hidden"].join(";");let _=v.createElement("iframe");_.src=C.toString(),_.title=p.replaceAll("{name}","").trim(),_.style.cssText="display:block;width:100%;height:56px;border:0;background:transparent;color-scheme:normal",_.setAttribute("allowtransparency","true"),S.appendChild(_);let x=w=>{if(w.origin!==t||w.source!==_.contentWindow)return;let h=w.data;if(!(!h||h.type!=="gamestage-sign-in"))switch(h.state){case"ready":typeof h.height=="number"&&h.height>0&&h.height<400&&(_.style.height=`${Math.ceil(h.height)}px`),S.style.visibility="visible",c("offered");return;case"granted":T(),c("checking"),b();return;case"dismissed":T(),g("dismissed"),c("dismissed");return;default:T(),c("not-available")}};s()?.addEventListener("message",x),u={host:S,iframe:_,listener:x},v.body.appendChild(S)},async streak(){if(!(i!=="granted"||!t||!n))try{let f=await n(`${t}/hub/game-streak`,{credentials:"include",cache:"no-store"}),l=f.ok?await f.json().catch(()=>({})):{};return l.state==="granted"?l.streak:void 0}catch{return}},async request(f,l={},v){if(i==="granted"||i==="off"||i==="not-available")return i;if(i==="dismissed"&&c("not-granted"),i==="not-granted")return this.offer(f,l),i;if(i==="signed-out"&&t){let p=e.document,C=`${t}/hub/signin?return_to=${encodeURIComponent("/hub")}`,S=()=>{p?.visibilityState!=="hidden"&&(p?.removeEventListener("visibilitychange",S),b().then(()=>this.offer(f,l)))};p?.addEventListener("visibilitychange",S),(v??(_=>p?.defaultView?.open?.(_,"_blank")))(C)}return i},onChange(f){return r.add(f),()=>r.delete(f)},stop(){T(),r.clear()}}}Tn();function jr(e){return`${ir}:${e}`}function qr(e){return Object.entries(e).filter(t=>typeof t[1]=="boolean").sort(([t],[n])=>t.localeCompare(n))}function xs(e,t,n){return n===!0?!0:!t||!e?!1:e.querySelector(\'script[src*="user-consent"], script[src*="onetrust"], script[src*="cookielaw"]\')!=null}function bc(e){return{declared:!0,categories:{...e.categories}}}function ks(e){let t=e.window??globalThis,n=e.policyVersion?.trim()||us,s=e.now??(()=>new Date),o=new Set,r=e.hostManagesConsent===!0||e.hostOwnsConsent===!0,i=null,a=new Set(Cn([...e.embedOrigins??[]])),d=()=>{try{return t?.localStorage}catch{return}},c=(()=>{try{let S=d()?.getItem(jr(e.scope?.trim()||e.game));if(!S)return null;let _=cr(JSON.parse(S));return!_||_.source!=="fan"||_.policyVersion!==n?null:_}catch{return null}})(),g=null,y=S=>g!==null&&JSON.stringify(qr(S))===g,b=()=>{let S=e.platform.consent();return!S.declared||y(S.categories)?null:S},T=(()=>{try{return!!(t&&t.parent&&t.parent!==t)}catch{return!0}})(),f=()=>{let S=b();return S?qt(S.categories,"host",{policyVersion:n,at:s()}):e.hostOwnsConsent?i:c??i},l=()=>{let S=C.reading();for(let _ of[...o])_(S)},v=S=>{if(!T||S.source!==t?.parent||typeof S.origin!="string"||!a.has(S.origin))return;let _=S.data;!_||_.type!==ar||!_.categories||typeof _.categories!="object"||typeof _.policyVersion!="string"||_.policyVersion.trim()!==n||(i=qt(_.categories,"host",{policyVersion:n,at:s()}),l())};t?.addEventListener?.("message",v);let p=e.platform.onConsentChanged(()=>l()),C={reading(){let S=f();return S?bc(S):e.hostOwnsConsent?{declared:!0,categories:{necessary:!0,functional:!0}}:{declared:!1,categories:{necessary:!0}}},record:()=>f(),needed:()=>!r&&e.policy.analyticsRequiresConsent&&f()===null,hostDecides:()=>r||b()!==null,decide(S){if(C.hostDecides())return!1;let _=qt(S,"fan",{policyVersion:n,at:s()});c=_;try{d()?.setItem(jr(e.scope?.trim()||e.game),JSON.stringify(_))}catch{}try{g=JSON.stringify(qr(_.categories)),e.platform.declareConsent({..._.categories})}catch{}return l(),!0},onChange(S){return o.add(S),()=>o.delete(S)},stop(){t?.removeEventListener?.("message",v),p(),o.clear()}};return C}Tn();var Br="gs-consent-style",_c=`\n.gs-consent{position:fixed;left:0;right:0;bottom:var(--gs-consent-clear,0px);z-index:2147483000;display:flex;justify-content:center;padding:12px 12px calc(12px + env(safe-area-inset-bottom));pointer-events:none;box-sizing:border-box}\n.gs-consent[hidden]{display:none}\n.gs-consent--top{bottom:auto;top:0;padding:calc(12px + env(safe-area-inset-top)) 12px 12px}\n.gs-consent__card{pointer-events:auto;position:relative;width:100%;max-width:26rem;box-sizing:border-box;display:grid;gap:12px;padding:16px 44px 16px 18px;border-radius:20px;border:1px solid rgba(0,0,0,.08);background:var(--gs-consent-surface,#fff);color:var(--gs-consent-ink,#1b1c1f);box-shadow:0 10px 30px rgba(0,0,0,.18);font-family:inherit;font-size:15px;line-height:1.45}\n.gs-consent__title{position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}\n.gs-consent p{margin:0}\n.gs-consent a{color:var(--gs-consent-accent-ink,inherit);text-decoration:underline;text-decoration-color:var(--gs-consent-accent,currentColor);text-decoration-thickness:2px;text-underline-offset:4px}\n.gs-consent__row{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px}\n.gs-consent button{font:inherit;cursor:pointer;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;touch-action:manipulation}\n.gs-consent__pill{font-weight:600!important;font-size:15px;min-height:44px;min-width:6.5rem;padding:0 20px;border-radius:999px;box-sizing:border-box}\n.gs-consent__pill:active{transform:translateY(1px)}\n.gs-consent__accept{border:2px solid var(--gs-consent-accent,#1b1c1f);background:var(--gs-consent-accent,#1b1c1f);color:var(--gs-consent-on-accent,#fff)}\n.gs-consent__reject{border:2px solid currentColor;background:transparent;color:inherit}\n.gs-consent__close{position:absolute;top:6px;right:6px;width:40px;height:40px;border:0;border-radius:999px;background:transparent;color:inherit;font-size:22px!important;line-height:1;opacity:.7;display:grid;place-items:center;padding:0}\n.gs-consent__choose{border:0;background:none;color:inherit;text-decoration:underline;text-underline-offset:3px;font-size:14px;padding:4px 2px;min-height:44px}\n.gs-consent button:focus{outline:none}\n.gs-consent button:focus-visible,.gs-consent input:focus-visible,.gs-consent a:focus-visible,.gs-consent__card:focus-visible{outline:3px solid currentColor;outline-offset:2px}\n.gs-consent fieldset{border:0;margin:0;padding:0;display:grid;gap:8px}\n.gs-consent label{display:flex;gap:10px;align-items:flex-start;cursor:pointer}\n.gs-consent input[type=checkbox]{width:22px;height:22px;margin:1px 0 0;flex:none;accent-color:var(--gs-consent-accent,currentColor)}\n.gs-consent__note{font-size:14px}\n@media (min-width:720px){.gs-consent:not(.gs-consent--top) .gs-consent__card--bar{max-width:60rem;grid-template-columns:minmax(0,1fr) auto;align-items:center;column-gap:20px;padding:12px 52px 12px 20px}.gs-consent__card--bar .gs-consent__row{flex-wrap:nowrap}}\n.gs-consent-settings{font:inherit;font-size:inherit;background:none;border:0;color:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;padding:0 .25em;margin:0 0 0 .75em;min-height:0;line-height:inherit;display:inline;vertical-align:baseline}\n.gs-consent-footer{display:block;text-align:center;padding:12px 16px calc(12px + env(safe-area-inset-bottom));font-size:14px}\n.gs-consent-footer .gs-consent-settings{margin:0}\n.gs-copyright-link{display:inline-block;white-space:nowrap;text-decoration:underline}\n.gs-consent-settings:focus{outline:none}\n.gs-consent-settings:focus-visible{outline:3px solid currentColor;outline-offset:2px}\n.gs-consent-room [data-gs-page]::after{content:"";display:block;block-size:var(--gs-consent-room,0px);pointer-events:none}\n`;function vc(e){return e.footCoversMain&&!e.topCoversKept?"top":"foot"}function Os(e,t){let n=e.presentation??{},s={brand:n.consentBrandName,title:n.consentTitle,detail:n.consentDetail,accept:n.consentAcceptLabel,reject:n.consentRejectLabel,choose:n.consentChooseLabel,save:n.consentSaveLabel,analytics:n.consentAnalyticsLabel,marketing:n.consentMarketingLabel,functional:n.consentFunctionalLabel,settings:n.consentSettingsLabel},o={...lr,...t};for(let[r,i]of Object.entries(s))i&&i.trim()&&(o[r]=i);return o}var zr=["analytics","marketing","functional"],Sc=Object.freeze({analytics:!0,marketing:!1,functional:!1});function Is(e,t={}){let n=globalThis.document;if(!n.getElementById(Br)){let P=n.createElement("style");P.id=Br,P.textContent=_c,n.head.append(P)}let s=n.createElement("div");s.className="gs-consent",As(s),s.hidden=!0,s.dataset.gsComponent="consent",s.setAttribute("aria-live","polite"),n.body.append(s);let o=null,r=null,i=P=>{e.consent.decide(P),s.hidden=!0,T(),t.onDecided?.(P)},a=(P,I,G,j="")=>{let D=n.createElement("button");return D.type="button",D.textContent=P,D.dataset.gsPart=I,j&&(D.className=j),D.addEventListener("click",G),D};function d(P){let I=Os(e,t.words),G=e.consent.record()?.categories??{},j=n.createElement("div");j.className=P?"gs-consent__card":"gs-consent__card gs-consent__card--bar",j.setAttribute("role","dialog"),j.setAttribute("aria-modal","false"),j.setAttribute("aria-labelledby","gs-consent-title"),j.tabIndex=-1;let D=n.createElement("h2");D.id="gs-consent-title",D.className="gs-consent__title",D.textContent=I.title;let V=n.createElement("p");V.textContent=ur(I.detail,I.brand);let M=e.presentation?.privacyPolicyUrl;if(M&&/^https?:\\/\\//.test(M)){let K=n.createElement("a");K.href=M,K.target="_blank",K.rel="noopener",K.textContent=I.policy,V.append(" ",K,".")}let oe=a("\\xD7","dismiss",()=>{s.hidden=!0,T()},"gs-consent__close");oe.setAttribute("aria-label",I.dismiss),j.append(D,oe,V);let q=(K,Oe,re,Le)=>a(K,Oe,Le,`gs-consent__pill gs-consent__${re}`);if(P){let K=n.createElement("fieldset"),Oe=n.createElement("legend");Oe.className="gs-consent__note",Oe.textContent=I.necessary,K.append(Oe);let re={};for(let Ee of zr){let De=n.createElement("label"),ve=n.createElement("input");ve.type="checkbox",ve.checked=G[Ee]===!0,ve.dataset.gsPart=Ee,re[Ee]=ve,De.append(ve,n.createTextNode(I[Ee])),K.append(De)}let Le=n.createElement("div");Le.className="gs-consent__row",Le.append(q(I.save,"save","accept",()=>i(Object.fromEntries(zr.map(Ee=>[Ee,re[Ee].checked])))),q(I.reject,"reject","reject",()=>i({analytics:!1,marketing:!1,functional:!1}))),j.append(K,Le)}else{let K=n.createElement("div");K.className="gs-consent__row",K.append(q(I.accept,"accept","accept",()=>i({...Sc})),q(I.reject,"reject","reject",()=>i({analytics:!1,marketing:!1,functional:!1})),a(I.choose,"choose",()=>N(!0,!0),"gs-consent__choose")),j.append(K)}return s.replaceChildren(j),j}let u=n.body,c=n.documentElement,g=u.style.paddingBottom,y=c.style.scrollPaddingBottom,b=()=>n.defaultView,T=()=>{s.hidden&&S();let P=s.querySelector(".gs-consent__card"),I=s.hidden||!P||s.classList.contains("gs-consent--top"),G=I?0:Math.ceil(b().innerHeight-P.getBoundingClientRect().top);u.style.paddingBottom=I?g:`calc(${g||"0px"} + ${G}px)`;let j=I?y:`${G}px`;c.style.scrollPaddingBottom!==j&&(c.style.scrollPaddingBottom=j);let D=I?"":`${G}px`;c.style.getPropertyValue("--gs-consent-room")!==D&&(D?c.style.setProperty("--gs-consent-room",D):c.style.removeProperty("--gs-consent-room")),c.classList.contains("gs-consent-room")===I&&c.classList.toggle("gs-consent-room",!I)},f=32,l=(P,I)=>{let G=Math.min(Math.max(I.left+I.width/2,0),n.documentElement.clientWidth-1),j=Math.min(Math.max(I.top+I.height/2,0),(n.defaultView?.innerHeight??1)-1),V=(typeof n.elementsFromPoint=="function"?n.elementsFromPoint(G,j):[]).find(M=>!s.contains(M));return!V||V===P||P.contains(V)||V.contains(P)},v=()=>{let P=n.defaultView;if(!P)return 0;let I=P.innerHeight,G=[];for(let D of Array.from(n.body.querySelectorAll("body *"))){if(s.contains(D))continue;let V=P.getComputedStyle(D).position;if(V!=="fixed"&&V!=="sticky")continue;let M=D.getBoundingClientRect();M.width===0||M.height===0||M.height>=I*.4||M.bottom<=0||l(D,M)&&G.push(M)}G.sort((D,V)=>V.bottom-D.bottom);let j=0;for(let D of G)I-D.bottom<=j+f&&(j=Math.max(j,I-D.top));return j},p=null,C="",S=()=>{p&&(p.style.paddingBottom=C),p=null},_=P=>{let I=n.querySelector(".gs-boot:not([data-done])");if(!I||!P||s.hidden||s.classList.contains("gs-consent--top"))return S();p!==I&&(S(),p=I,C=I.style.paddingBottom);let G=Math.ceil(b().innerHeight-P.getBoundingClientRect().top);I.style.paddingBottom=`calc(env(safe-area-inset-bottom, 0px) + ${G}px)`},x=()=>{if(!n.defaultView)return;s.style.setProperty("--gs-consent-clear",`${Math.ceil(v())}px`),s.classList.remove("gs-consent--top");let P=s.querySelector(".gs-consent__card");if(_(P),P&&!s.hidden){let I=P.getBoundingClientRect(),G=Array.from(n.querySelectorAll(\'.gs-boot__play, [data-gamestage-start], [data-gs-main], [data-gs-part="commit"]\')),j=(D,V)=>D.some(M=>{let oe=M.getBoundingClientRect();return oe.width===0||oe.height===0||V.right<=oe.left||oe.right<=V.left||V.bottom<=oe.top||oe.bottom<=V.top?!1:l(M,oe)});if(j(G,I)){s.classList.add("gs-consent--top"),S();let D=Array.from(n.querySelectorAll("[data-gs-keep-clear]")),V=D.length>0&&j(D,P.getBoundingClientRect());vc({footCoversMain:!0,topCoversKept:V})==="foot"&&(s.classList.remove("gs-consent--top"),_(P))}}T()},w=typeof ResizeObserver=="function"?new ResizeObserver(()=>{T()}):null;b()?.addEventListener("resize",x),w?.observe(s);let h=!1;function N(P=!1,I=!1){As(s);let G=d(P);h=I||!s.hidden&&h,s.hidden=!1,T(),I&&G.focus({preventScroll:!0}),x()}let R=null,k=()=>{if(t.settingsIn!==void 0)return t.settingsIn;let P=n.querySelector(\'[data-gs-slot="privacy-settings"]\');if(P)return P;let I=n.querySelector(\'[data-gs-part="recovery"]\');if(I?.parentElement&&I.parentElement!==n.body)return I.parentElement;let G=n.querySelectorAll("footer");return G.length?G[G.length-1]:(R||(R=n.createElement("div"),R.className="gs-consent-footer",R.dataset.gsPart="settings-footer",n.body.append(R)),R)},H=()=>{let P=e.consent.hostDecides()?null:k();if(!P){o?.remove(),o=null,r?.remove(),r=null;return}o||(o=a(Os(e,t.words).settings,"settings",()=>N(!0,!0),"gs-consent-settings")),o.parentElement!==P&&P.append(o),r||(r=n.createElement("a"),r.className="gs-consent-settings gs-copyright-link",r.dataset.gsPart="copyright",r.href=dr,r.target="_blank",r.rel="noopener",r.textContent=Os(e,t.words).copyright),r.previousElementSibling!==o&&o.after(r),R&&P!==R&&(R.remove(),R=null)},ue=!1,be=typeof MutationObserver=="function"&&t.settingsIn===void 0?new MutationObserver(P=>{ue||P.every(I=>s.contains(I.target)||(o?.contains(I.target)??!1))||(ue=!0,queueMicrotask(()=>{ue=!1,H()}))}):null;be?.observe(n.body,{childList:!0,subtree:!0});let $=e.consent.onChange(()=>{H(),(e.consent.hostDecides()||!h&&!e.consent.needed())&&(s.hidden=!0,T())});H();let ge=!1,_e=typeof MutationObserver=="function"?new MutationObserver(P=>{s.hidden||ge||P.every(I=>I.target===n.body||s.contains(I.target)||I.target===p&&I.attributeName==="style")||(ge=!0,(b()?.requestAnimationFrame??setTimeout)(()=>{ge=!1,As(s),x()}))}):null;return _e?.observe(n.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","data-done","data-state"]}),e.consent.needed()&&!e.consent.hostDecides()&&N(!1),{open:()=>{e.consent.hostDecides()||N(!0,!0)},close:()=>{s.hidden=!0,T()},stop:()=>{$(),be?.disconnect(),_e?.disconnect(),b()?.removeEventListener("resize",x),w?.disconnect(),S(),s.remove(),o?.remove(),R?.remove(),u.style.paddingBottom=g,c.style.scrollPaddingBottom=y,c.style.removeProperty("--gs-consent-room"),c.classList.remove("gs-consent-room")}}}function Hr(e){let t=e.match(/rgba?\\(\\s*(\\d+)[ ,]+(\\d+)[ ,]+(\\d+)/);if(!t)return null;let[n,s,o]=[t[1],t[2],t[3]].map(r=>{let i=Number(r)/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*n+.7152*s+.0722*o}function Vr(e,t){let n=Hr(e),s=Hr(t);return n===null||s===null?null:(Math.max(n,s)+.05)/(Math.min(n,s)+.05)}function As(e){let t=e.ownerDocument.defaultView;if(!t)return;let n=t.getComputedStyle(e.ownerDocument.documentElement),s=e.ownerDocument.createElement("span");e.append(s);let o=a=>(s.style.color="",s.style.color=a,t.getComputedStyle(s).color),r=[["--gs-backgroundContainerColour","--gs-onBackgroundContainerColour"],["--gs-backgroundMainColour","--gs-onBackgroundColour"]];for(let[a,d]of r){let u=n.getPropertyValue(a).trim(),c=n.getPropertyValue(d).trim();if(!u||!c)continue;let g=Vr(o(u),o(c));if(g!==null&&g>=4.5){e.style.setProperty("--gs-consent-surface",u),e.style.setProperty("--gs-consent-ink",c);break}}let i=[["--gs-highlightMainColour","--gs-onHighlightColour"],["--gamestage-primary",""],["--gs-primaryMainColour","--gs-onPrimaryColour"]];for(let[a,d]of i){let u=n.getPropertyValue(a).trim();if(!u)continue;let c=o(u),g=n.getPropertyValue(d||"--none").trim(),b=(g?[g,"#ffffff","#111111"]:["#ffffff","#111111"]).find(T=>(Vr(c,o(T))??0)>=4.5);if(b){e.style.setProperty("--gs-consent-accent",u),e.style.setProperty("--gs-consent-on-accent",b);break}}s.remove()}var An={heading:"Can\'t load the game right now",body:"Check your connection, then try again.",retry:"Try again"},Yt=class extends Error{code="unavailable";handled=!0;constructor(){super("Interaction Cloud did not answer and this device has no remembered settings, so the game has no words to show. The library has drawn its retry screen."),this.name="GamestageUnavailableError"}},Kr="gamestage-unavailable";function Wr(e){let t=e.document;if(!t?.body||typeof t.createElement!="function"||t.getElementById?.(Kr))return;let n=t.createElement("div");n.setAttribute("id",Kr),n.setAttribute("role","alert"),Object.assign(n.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"16px",padding:"24px",background:"#111",color:"#fff",fontFamily:"system-ui, -apple-system, sans-serif",textAlign:"center"});let s=t.createElement("h1");s.textContent=An.heading,Object.assign(s.style,{fontSize:"22px",margin:"0",fontWeight:"700"});let o=t.createElement("p");o.textContent=An.body,Object.assign(o.style,{fontSize:"17px",margin:"0",opacity:"0.8"});let r=t.createElement("button");r.setAttribute("type","button"),r.textContent=An.retry,Object.assign(r.style,{fontSize:"17px",fontWeight:"700",minHeight:"48px",padding:"0 28px",borderRadius:"999px",border:"0",background:"#fff",color:"#111",cursor:"pointer",touchAction:"manipulation",userSelect:"none"}),r.addEventListener("click",()=>e.location?.reload()),n.appendChild(s),n.appendChild(o),n.appendChild(r),t.body.appendChild(n)}async function ae(e){if(e===void 0)return{kind:"anonymous"};try{let t=typeof e=="function"?await e():e;return typeof t=="string"&&t.length>0?{kind:"identified",token:t}:{kind:"anonymous"}}catch{return{kind:"anonymous"}}}function pe(e){return e.kind==="identified"?e.token:void 0}var Yr=e=>e.replace(/\\/+$/,"");async function wc(e){let t=pe(await ae(e.identity));if(!t)return{kind:"anonymous"};let n=e.fetchImpl??globalThis.fetch,s=`${Yr(e.baseUrl)}/api/loyalty/v1/me`,o={Authorization:`Bearer ${t}`},r=await n(`${s}/points`,{headers:o});if(r.status===401||r.status===403)return{kind:"anonymous"};if(!r.ok)throw new Error(`Loyalty points read failed: ${r.status}`);let a=((await r.json()).items??[]).find(T=>T.programmeId===e.programmeId),{unlocked:d,stillToUnlock:u,catalogue:c}=await Ec(n,s,o);if(!a)return{kind:"standing",standing:{programmeId:e.programmeId,balance:0,enrolled:!1,statement:[],catalogue:c,unlocked:d,stillToUnlock:u}};let g=e.statementLimit??20,y=await n(`${s}/points/${encodeURIComponent(e.programmeId)}/statement?limit=${g}`,{headers:o}),b=y.ok?(await y.json()).lines??[]:[];return{kind:"standing",standing:{programmeId:a.programmeId,balance:a.balance,tier:a.tier,tiers:a.tiers,enrolled:!0,statement:b,catalogue:c,unlocked:d,stillToUnlock:u}}}async function Ns(e){if(!e.baseUrl)return null;let t=pe(await ae(e.identity));if(!t)return null;let n=e.fetchImpl??globalThis.fetch;try{let s=await n(`${Yr(e.baseUrl)}/api/loyalty/v1/me/streak`,{headers:{Authorization:`Bearer ${t}`}});return s.ok?Ps(await s.json()):null}catch{return null}}function Ps(e){let t=e??{};return typeof t.current!="number"||typeof t.best!="number"?null:{current:t.current,best:t.best,lastDay:t.lastDay??"",proved:t.proved===!0,nextMilestone:t.nextMilestone}}async function Ec(e,t,n){let[s,o]=await Promise.all([e(`${t}/rewards`,{headers:n}).catch(()=>{}),e(`${t}/products`,{headers:n}).catch(()=>{})]),r=s?.ok?((await s.json()).items??[]).map(c=>({instanceId:c.instance.instanceId,product:{productId:c.instance.product.productId,name:c.instance.product.name,description:c.instance.product.description,type:c.instance.product.type},campaignName:c.campaign?.name,awardedAt:c.awardedAt})):[],i=o?.ok?(await o.json()).items??[]:[],a=new Set(r.map(c=>c.product.productId)),d=i.map(c=>({productId:c.productId,name:c.name,description:c.description,type:c.type})),u=d.filter(c=>!a.has(c.productId));return{unlocked:r,stillToUnlock:u,catalogue:d}}function Cc(e){let t=e.round;if(!t)return"No round has been read yet.";let n=t.origin;return n?n.source==="studio"?`This round came from Studio: element ${n.element_id??"unknown"}`+(n.edition_id?` on edition ${n.edition_id}`:"")+`, as round ${t.id} version ${t.version}.`:`This round came from the game\'s manifest, as ${t.id} version ${t.version}.`:`This round is ${t.id}, and this Engine does not say where it came from. That is older than the field, not a manifest round.`}function Tc(e){return(e.performance?.getEntriesByType?.("resource")??[]).slice(-40).map(n=>{let s=n;return{name:s.name,status:s.responseStatus?String(s.responseStatus):"unknown",ms:Math.round(s.duration)}})}function xc(e,t){let n=[Cc(e),"",`game ${e.game}`,`platform ${e.platform}`];e.offPlatformReason&&n.push(`not on ic ${e.offPlatformReason}`),e.ids?.project&&n.push(`project ${e.ids.project}`),e.ids?.event&&n.push(`edition ${e.ids.event}`),e.ids?.element&&n.push(`element ${e.ids.element}`),e.ids?.host&&n.push(`studio host ${e.ids.host}`),e.endpoints.playerApi&&n.push(`player api ${e.endpoints.playerApi}`),e.endpoints.mesh&&n.push(`mesh ${e.endpoints.mesh}`),n.push(`identity ${e.identity.signedIn?`${e.identity.kind}, signed in`:e.identity.kind}`),n.push(`consent ${e.consent.allowed?"granted":"not granted"}`);let s=Object.entries(e.presentation).filter(([,o])=>o);n.push(`producer ${s.length?s.map(([o])=>o).join(", "):"nothing set"}`),n.push("","requests");for(let o of Tc(t))n.push(` ${o.status.padEnd(7)} ${o.ms.toString().padStart(5)}ms ${o.name}`);return n.push("",`page ${t.location?.href??"unknown"}`),n.push(`when ${new Date().toISOString()}`),n.join(`\n`)}var Qr="gsdebug",kc="gamestage-debug";function Oc(e,t){let n=e.document,s=n.createElement("div");s.id="gamestage-debug",s.setAttribute("role","dialog"),s.setAttribute("aria-label","Gamestage diagnostics"),s.style.cssText=["position:fixed","inset:auto 0 0 0","max-height:70vh","overflow:auto","z-index:2147483647","background:#0b0f1c","color:#e8eaf2","font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace","padding:12px 14px","border-top:2px solid #e5484d","white-space:pre-wrap"].join(";");let o=n.createElement("div");o.style.cssText="display:flex;gap:8px;margin-bottom:10px";let r=n.createElement("button");r.textContent="Copy",r.style.cssText="font:inherit;padding:4px 10px;cursor:pointer",r.onclick=()=>{e.navigator.clipboard?.writeText(t).then(()=>r.textContent="Copied",()=>r.textContent="Select and copy")};let i=n.createElement("button");i.textContent="Close",i.style.cssText=r.style.cssText,i.onclick=()=>s.remove(),o.append(r,i);let a=n.createElement("div");return a.textContent=t,s.append(o,a),s}function Jr(e,t){let n=t.document;if(!n)return()=>{};let s=()=>{n.getElementById("gamestage-debug")?.remove(),n.body?.append(Oc(t,xc(e(),t)))},o="",r=i=>{let a=i.target;a?.isContentEditable||a?.tagName==="INPUT"||a?.tagName==="TEXTAREA"||i.key.length!==1||(o=(o+i.key.toLowerCase()).slice(-Qr.length),o===Qr&&s())};return n.addEventListener("keydown",r),t.location&&new URLSearchParams(t.location.search).has(kc)&&t.setTimeout(s,0),()=>n.removeEventListener("keydown",r)}Wt();function Rs(e={}){let t=Kt(),n=new Map,s=[],o=new Set,r=new Set,i=new Set,a={...e.presentation??{}},d={declared:!1,categories:{}},u,c=!1,g=()=>{for(let f of[...o])f()},y=e.setInterval??((f,l)=>setInterval(f,l)),b=e.clearInterval??(f=>clearInterval(f)),T=e.pollMilliseconds??0;return T>0&&(u=y(g,T)),{kind:"local",offPlatformReason:e.offPlatformReason,clock:t,emitted:s,presentation:a,signInSettings:e.signInSettings??{enabled:!1},consent:()=>d,onConsentChanged(f){return r.add(f),()=>r.delete(f)},onPresentationChanged(f){return i.add(f),()=>i.delete(f)},setPresentation(f){for(let l of Object.keys(a))delete a[l];Object.assign(a,f);for(let l of[...i])l(a)},declareConsent(f){d={declared:!0,categories:{...f}};for(let l of[...r])l(d);return!0},onRoundAnnounced(f){return o.add(f),()=>o.delete(f)},subscribeLive(f,l){let v=e.liveSource;if(!v||typeof EventSource>"u")return l.status({state:"unavailable"}),()=>{};let p=!1;l.status({state:"connecting"});let C=`${v}${v.includes("?")?"&":"?"}channel=${encodeURIComponent(f)}`,S=new EventSource(C);return S.onmessage=_=>{try{let x=JSON.parse(_.data);l.message(x.class,x.body,!p)}catch{}},S.addEventListener("synced",()=>{p=!0,l.synced(),l.status({state:"live"})}),S.onerror=()=>{p=!1,l.status({state:typeof navigator<"u"&&navigator.onLine===!1?"offline":"reconnecting"})},()=>S.close()},announce:g,emit(f){s.push(f)},storage:{read:async f=>n.get(f)??null,write:async(f,l)=>{n.set(f,l)},remove:async f=>{n.delete(f)}},stop(){c||(c=!0,u!==void 0&&b(u),o.clear(),r.clear())}}}Ht();Ls();function ni(e,t){let n=new Date(e);if(!Number.isNaN(n.getTime()))try{return n.toLocaleDateString("en-CA",{timeZone:t})}catch{return}}function si(e){let t=new Date(`${e}T12:00:00Z`);return t.setUTCDate(t.getUTCDate()-1),t.toISOString().slice(0,10)}function Ic(e,t={}){let n=t.timeZone??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",s=t.now??new Date,o=new Set;for(let g of e){if(g.amount<=0)continue;let y=ni(g.occurredAt,n);y&&o.add(y)}if(o.size===0)return{days:0,capped:!1,today:!1};let r=ni(s.toISOString(),n)??"",i=o.has(r),a=i?r:si(r);if(!o.has(a))return{days:0,capped:!1,today:i};let d=0;for(;o.has(a);)d+=1,a=si(a);let u=[...o].sort()[0],c=a<u;return{days:d,capped:c,today:i}}Vt();$s();Wt();St();function oi(e,t,n=Date.now(),s){if(!e?.can.results_available||!e.finalAt||n>=Date.parse(e.finalAt))return"";let o=new Date(e.finalAt).toLocaleString(s,{day:"numeric",month:"short",hour:"numeric",minute:"2-digit"});return t.replaceAll("{finalAt}",o)}function Nc(e,t,n="label_provisional_result"){let s,o=()=>{clearTimeout(s),t.textContent=oi(e.round,e.presentation?.labels?.[n.replace(/^label_/,"")]??fr,e.now()),t.hidden=!t.textContent;let a=Date.parse(e.round?.finalAt??"")-e.now();a>0&&(s=setTimeout(o,Math.min(a,2147483647)))},r=e.onRoundChanged(o),i=e.onPresentationChanged(o);return o(),()=>{clearTimeout(s),r(),i()}}var ri={open:"Your progress",showTitle:"Keep your progress",showDetail:"Save this code. It brings your name, scores and achievements back on another phone or browser. You only see it once.",private:"Keep it private. Anyone with this code can play as you.",replace:"Getting a new code stops the old one working.",get:"Get a recovery code",issueFailed:"That didn\'t work. Check your connection and try again.",copy:"Copy",copied:"Copied",share:"Share",enterTitle:"I\'ve played before",enterDetail:"Type the recovery code you saved to get your progress back.",submit:"Get my progress back",notRecognised:"That code isn\'t one we know. Check it against the one you saved.",restored:"Welcome back. Your progress is on this device now.",close:"Close"};var ii="gs-recovery-style",Pc=`\n.gs-recovery-open{font:inherit;background:none;border:0;color:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;padding:.5rem 0;min-height:44px}\n.gs-recovery{border:0;border-radius:16px;padding:0;max-width:min(26rem,calc(100vw - 32px));width:100%;color:#1b1c1f;background:#fff;box-shadow:0 18px 48px rgba(0,0,0,.35)}\n.gs-recovery::backdrop{background:rgba(0,0,0,.55)}\n.gs-recovery__body{display:grid;gap:12px;padding:20px;font:17px/1.45 system-ui,sans-serif}\n.gs-recovery h2{margin:0;font-size:1.2rem}\n.gs-recovery p{margin:0}\n.gs-recovery__code{font:700 1.25rem/1.3 ui-monospace,Menlo,monospace;letter-spacing:.02em;text-align:center;padding:12px;border:1.5px solid #c9ccd3;border-radius:10px;background:#f4f5f7;user-select:all;overflow-wrap:anywhere}\n.gs-recovery__row{display:flex;gap:8px;flex-wrap:wrap}\n.gs-recovery button{font:inherit;font-weight:600;min-height:44px;padding:0 16px;border-radius:10px;border:1.5px solid #1b1c1f;background:#fff;color:#1b1c1f;cursor:pointer}\n.gs-recovery button.gs-recovery__primary{background:#1b1c1f;color:#fff}\n.gs-recovery button:disabled{opacity:.5;cursor:default}\n.gs-recovery input{font:16px/1.3 system-ui,sans-serif;min-height:44px;padding:0 12px;border:1.5px solid #c9ccd3;border-radius:10px}\n.gs-recovery input[aria-invalid=true]{border-color:#c62828;border-style:dashed}\n.gs-recovery__note{color:#50535c;font-size:.95rem}\n.gs-recovery__error{color:#c62828}\n.gs-recovery hr{border:0;border-top:1px solid #e3e5e9;margin:4px 0}\n`;function Rc(e,t){let n=e.presentation??{},s={open:n.recoveryOpenLabel,showTitle:n.recoveryShowTitle,showDetail:n.recoveryShowDetail,private:n.recoveryPrivateNote,replace:n.recoveryReplaceNote,enterTitle:n.recoveryEnterTitle,enterDetail:n.recoveryEnterDetail,submit:n.recoverySubmitLabel,notRecognised:n.recoveryNotRecognised,restored:n.recoveryRestored,get:n.recoveryGetLabel,issueFailed:n.recoveryIssueFailed,copy:n.recoveryCopyLabel,copied:n.recoveryCopiedLabel,share:n.recoveryShareLabel,close:n.recoveryCloseLabel},o={...ri,...t};for(let[r,i]of Object.entries(s))i&&i.trim()&&(o[r]=i);return o}function Y(e,t,n={},...s){let o=e.createElement(t),{dataset:r,...i}=n;return Object.assign(o,i),r&&Object.assign(o.dataset,r),o.append(...s),o}function Mc(e,t,n={}){let s=t.ownerDocument;s.getElementById(ii)||s.head.append(Y(s,"style",{id:ii,textContent:Pc}));let o=()=>Rc(e,n.words),r=Y(s,"button",{type:"button",className:"gs-recovery-open",textContent:o().open});r.dataset.gsPart="recovery";let i=Y(s,"dialog",{className:"gs-recovery"});i.setAttribute("aria-labelledby","gs-recovery-title"),t.append(r),s.body.append(i);function a(){let c=o(),g=Y(s,"div",{className:"gs-recovery__body"}),y=Y(s,"h2",{id:"gs-recovery-title",textContent:c.showTitle}),b=Y(s,"p",{className:"gs-recovery__code",hidden:!0});b.setAttribute("aria-label",c.showTitle);let T=Y(s,"button",{type:"button",textContent:c.copy,hidden:!0}),f=Y(s,"button",{type:"button",textContent:c.share,hidden:!0}),l=Y(s,"span",{className:"gs-recovery__note"});l.setAttribute("aria-live","polite");let v=Y(s,"button",{type:"button",className:"gs-recovery__primary",textContent:c.get}),p=Y(s,"p",{className:"gs-recovery__error",hidden:!0});p.setAttribute("role","alert"),v.addEventListener("click",async()=>{v.disabled=!0,p.hidden=!0;try{let R=await e.client.issueRecoveryCode();b.textContent=R.code,b.hidden=!1,T.hidden=!1,f.hidden=typeof navigator.share!="function",v.hidden=!0}catch{p.textContent=c.issueFailed,p.hidden=!1,v.disabled=!1}}),T.addEventListener("click",async()=>{try{await navigator.clipboard.writeText(b.textContent??""),l.textContent=c.copied}catch{l.textContent=""}}),f.addEventListener("click",async()=>{try{await navigator.share({text:b.textContent??""})}catch{}});let C=Y(s,"h2",{textContent:c.enterTitle}),S=Y(s,"form");S.noValidate=!0;let _=Y(s,"label",{htmlFor:"gs-recovery-input",textContent:c.enterTitle});_.hidden=!0;let x=Y(s,"input",{id:"gs-recovery-input",type:"text",placeholder:"four words and two numbers"});x.setAttribute("inputmode","text"),x.setAttribute("autocomplete","off"),x.setAttribute("autocorrect","off"),x.setAttribute("autocapitalize","none"),x.setAttribute("spellcheck","false"),x.setAttribute("enterkeyhint","go");let w=Y(s,"p",{className:"gs-recovery__error",id:"gs-recovery-error",hidden:!0});w.setAttribute("role","alert");let h=Y(s,"button",{type:"submit",className:"gs-recovery__primary",textContent:c.submit});S.addEventListener("submit",async R=>{R.preventDefault();let k=x.value.trim();if(!k)return;let H=k;h.disabled=!0,w.hidden=!0,x.removeAttribute("aria-invalid");try{await e.client.restoreFromRecoveryCode(H),l.textContent=c.restored,w.hidden=!0,S.replaceChildren(Y(s,"p",{textContent:c.restored})),await n.onRestored?.()}catch{w.textContent=c.notRecognised,w.hidden=!1,x.setAttribute("aria-invalid","true"),x.setAttribute("aria-describedby","gs-recovery-error"),h.disabled=!1}}),S.append(_,x,w,h);let N=Y(s,"button",{type:"button",textContent:c.close});N.addEventListener("click",()=>i.close()),g.append(y,Y(s,"p",{textContent:c.showDetail}),v,b,Y(s,"div",{className:"gs-recovery__row"},T,f),l,Y(s,"p",{className:"gs-recovery__note",textContent:`${c.private} ${c.replace}`}),p,Y(s,"hr"),C,Y(s,"p",{textContent:c.enterDetail}),S,Y(s,"div",{className:"gs-recovery__row"},N)),i.replaceChildren(g)}let d=()=>{a(),i.showModal()};r.addEventListener("click",d);let u=e.onPresentationChanged?.(()=>{r.textContent=o().open});return()=>{r.removeEventListener("click",d),u?.(),r.remove(),i.remove()}}St();function In(e){let t=[],n=/\\[([^\\]]*)\\]/g,s=0;for(let o of e.matchAll(n))o.index>s&&t.push({text:e.slice(s,o.index),accent:!1}),o[1]&&t.push({text:o[1],accent:!0}),s=o.index+o[0].length;return s<e.length&&t.push({text:e.slice(s),accent:!1}),t.filter(o=>o.text.length>0)}function Gs(e){return In(e).map(t=>t.text).join("")}var Lc=["displayName","strapline","howToPlay","playButtonLabel","playAgainLabel","resultButtonLabel","shareButtonLabel","editionName","editionStrapline"];function Dc(e,t={},n={}){let s=t.document??globalThis.document??void 0,o=e.displayName||n.displayName||void 0;for(let c of Lc){let g=c==="displayName"?o:e[c],y=t[c];if(y){if(!g){$c(y);continue}Jt.has(y)?Jt.get(y).wrote=g:Jt.set(y,{text:y.textContent??"",hidden:y.hasAttribute?.("hidden")??!1,wrote:g}),y.textContent=g,y.removeAttribute("hidden")}}if(s)if(o)Qt.has(s)?Qt.get(s).wrote=o:Qt.set(s,{before:s.title,wrote:o}),s.title=o;else{let c=Qt.get(s);c&&s.title===c.wrote&&(s.title=c.before),Qt.delete(s)}let r=t.root??s?.documentElement??null;if(!r)return;let i={};if(e.primaryColour&&(i["--gamestage-primary"]=e.primaryColour,Object.assign(i,ci(e.primaryColour))),e.cssVariables){for(let[g,y]of Object.entries(e.cssVariables))y&&(i[`--gs-${g}`]=y);let c=e.cssVariables.highlightMainColour;c&&Object.assign(i,ci(c)),Object.assign(i,yi(e.cssVariables));for(let g of jc){let y=Bt(e.cssVariables[g],e.uploadedFonts??[]);y&&(i[`--gs-${g}`]=y.family)}}let a=_i(e);Object.assign(i,a.vars),Fc(s,a);let d=Bt(e.defaultFontFamily,e.uploadedFonts??[]);d&&(i["--gs-font-default"]=`"${d.family}", system-ui, sans-serif`),s&&Yc(s,e.uploadedFonts),s&&Bc(s,e),e.logoAccentColour&&(i["--gs-title-accent"]=e.logoAccentColour),s&&Zc(s,e.logoText,o),s&&ed(s,e,o),s&&Fs(s,e.logoText,o);let u=ai.get(r)??new Set;for(let c of u)c in i||r.style.removeProperty(c);for(let[c,g]of Object.entries(i))r.style.setProperty(c,g);ai.set(r,new Set(Object.keys(i)))}var ai=new WeakMap,Jt=new WeakMap,Qt=new WeakMap;function $c(e){let t=Jt.get(e);t&&(Jt.delete(e),e.textContent===t.wrote&&(e.textContent=t.text,t.hidden&&e.setAttribute?.("hidden","")))}var Gc={backgroundMainColour:["background"],onBackgroundColour:["ink"],backgroundContainerColour:["surface"],highlightMainColour:["interactive"],highlightVariantColour:["interactive-base"],onHighlightColour:["on-accent"],positiveMainColour:["positive"],positiveVariantColour:["positive-base"],negativeMainColour:["negative"],negativeVariantColour:["negative-base"],secondaryMainColour:["selected"],tertiaryMainColour:["reward"]};function yi(e){let t={};for(let[n,s]of Object.entries(Gc)){let o=e[n];if(o)for(let r of s)t[`--gs-color-${r}`]=o,t[`--gs-color-${r}-solid`]=o}return t}function ci(e){let t={},n=(o,r)=>{t[`--gs-color-${o}`]=r,t[`--gs-color-${o}-solid`]=r};n("interactive",e),n("interactive-hover",`color-mix(in oklab, ${e} 82%, white)`),n("interactive-base",`color-mix(in oklab, ${e} 68%, black)`);let s=Uc(e);return s!==void 0&&n("on-accent",s>.4?"#111111":"#ffffff"),t}function Uc(e){let t=e.trim(),n,s=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(s){let a=s[1].length===3?s[1].split("").map(d=>d+d).join(""):s[1];n=[0,2,4].map(d=>parseInt(a.slice(d,d+2),16))}else{let a=/^rgba?\\(\\s*(\\d+)[\\s,]+(\\d+)[\\s,]+(\\d+)/i.exec(t);a&&(n=a.slice(1,4).map(Number))}if(!n)return;let[o,r,i]=n.map(a=>{let d=a/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*i}var bi="[data-gamestage-title], :root:not(:has([data-gamestage-title])) h1";function _i(e){let t={},n=[],s,o=e.cssVariables??{},r=o.fontTitleFamily??e.titleFont,i=o.fontTitleWeight??e.titleFontWeight,a=o.fontTitleTracking??e.titleLetterSpacing,d=o.fontTitleCase??e.titleCase,u=Bt(r,e.uploadedFonts??[]);if(u){t["--gs-title-font"]=`"${u.family}", var(--gs-font-display, system-ui), sans-serif`,n.push("font-family: var(--gs-title-font)");let b=u.stylesheetHref?xr(r,i)?.weight:i;b!==void 0&&b!==""&&(t["--gs-title-weight"]=String(b),n.push("font-weight: var(--gs-title-weight)")),s=u.stylesheetHref}let c=kr(a);c&&(t["--gs-title-tracking"]=c,n.push("letter-spacing: var(--gs-title-tracking)"));let g=Or(d);g&&(t["--gs-title-case"]=g,n.push("text-transform: var(--gs-title-case)")),e.titleColour&&(t["--gs-title-colour"]=e.titleColour,n.push("color: var(--gs-title-colour)"));let y=n.length?`${bi} { ${n.join("; ")}; }`:"";return e.logoText&&(y+=`${y?" ":""}.gamestage-title-accent { color: var(--gs-title-accent, inherit); }`),{vars:t,css:y,fontHref:s}}var di="gamestage-title-style",li="gamestage-title-font";function Fc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=e.getElementById(di);if(t.css?(n||(n=e.createElement("style"),n.id=di,e.head.appendChild(n)),n.textContent!==t.css&&(n.textContent=t.css)):n?.remove(),!t.fontHref){e.getElementById(li)?.remove();return}Si(e,li,t.fontHref)}var ui="gamestage-font-preconnect",gi="gamestage-role-font-",vi=["fontBodyFamily","fontNumberFamily","fontCTAFamily","fontLabelFamily","fontHighlightFamily"],jc=["fontTitleFamily",...vi];function qc(e){if(e.getElementById(ui))return;let t=e.createElement("link");t.id=ui,t.rel="preconnect",t.href=ms,t.crossOrigin="anonymous",e.head.appendChild(t)}function Si(e,t,n){qc(e);let s=e.getElementById(t);s&&s.href===n||(s||(s=e.createElement("link"),s.id=t,s.rel="stylesheet",e.head.appendChild(s)),s.media="print",s.onload=()=>{s&&(s.media="all")},s.href=n)}function Bc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=t.cssVariables??{},s=t.uploadedFonts??[],o=new Map,r=[t.defaultFontFamily,...vi.map(i=>n[i])];for(let i of r){let a=Bt(i,s);if(!a?.stylesheetHref)continue;let d=a.family.toLowerCase().replace(/[^a-z0-9]+/g,"-");o.set(`${gi}${d}`,a.stylesheetHref)}for(let i of Array.from(e.head.children)){let a=i.id;i.tagName==="LINK"&&a.startsWith(gi)&&!o.has(a)&&i.remove()}for(let[i,a]of o)Si(e,i,a)}var fi="gamestage-font-faces",pi="gamestage-font-preload-",zc={woff2:"woff2",woff:"woff",ttf:"truetype",otf:"opentype"};function Hc(e){let t=e.trim();return!/^(https:)?\\/\\//i.test(t)||/["\'()\\\\\\s<>{}]/.test(t)?null:t}function Vc(e){let t=e.split(/[?#]/)[0]?.split(".").pop()?.toLowerCase();return t?zc[t]:void 0}function Kc(e){let t=[],n=new Set;for(let s of e??[]){let o=hs(s.name??""),r=Hc(s.url??"");if(!o||!r)continue;let i=o.toLowerCase().replace(/[^a-z0-9]+/g,"-");if(n.has(i))continue;n.add(i);let a=String(s.weight??"").trim();t.push({family:o,url:r,weight:/^\\d{2,4}$/.test(a)?a:"400",slug:i})}return t}function Wc(e){let t=Vc(e.url),n=t?`url("${e.url}") format("${t}")`:`url("${e.url}")`;return`@font-face { font-family: "${e.family}"; src: ${n}; font-weight: ${e.weight}; font-display: swap; }`}function Yc(e,t){if(!e?.head||typeof e.createElement!="function")return;let n=Kc(t),s=e.getElementById(fi);if(!n.length)s?.remove();else{let r=n.map(Wc).join(" ");s||(s=e.createElement("style"),s.id=fi,e.head.appendChild(s)),s.textContent!==r&&(s.textContent=r)}let o=new Map(n.map(r=>[`${pi}${r.slug}`,r]));for(let r of Array.from(e.head.children)){let i=r.id;r.tagName==="LINK"&&i.startsWith(pi)&&!o.has(i)&&r.remove()}for(let[r,i]of o){if(e.getElementById(r))continue;let a=e.createElement("link");a.id=r,a.rel="preload",a.as="font",a.href=i.url,a.crossOrigin="anonymous",e.head.appendChild(a)}}var Xt=new WeakMap,ze="data-gamestage-logo",Qc="gamestage-title-accent";function wi(e,t,n){let s=Array.from(e.querySelectorAll("[data-gamestage-title]"));if(s.length)return s;let o=new Set([t,Gs(n)].filter(Boolean).map(r=>r.trim().toLowerCase()));return Array.from(e.querySelectorAll("h1")).filter(r=>r.hasAttribute(ze)||o.has((r.textContent??"").trim().toLowerCase()))}function mi(e){let t=Xt.get(e);if(t?.text){for(let n of wi(e,t.name,t.text)){if(n.getAttribute(ze)===t.text&&n.textContent===Gs(t.text))continue;let s=In(t.text).map(o=>{if(!o.accent)return e.createTextNode(o.text);let r=e.createElement("span");return r.className=Qc,r.textContent=o.text,r});n.replaceChildren(...s),n.setAttribute(ze,t.text),t.name&&n.setAttribute("aria-label",t.name)}Fs(e,t.text,t.name)}}var Jc=20,Us="data-gamestage-fit",hi=new WeakSet;function Fs(e,t,n){if(typeof e.querySelectorAll!="function")return;let s=e.defaultView;if(!s||typeof s.getComputedStyle!="function")return;let o=t?.trim()||n;if(o){for(let r of wi(e,n,o))Xc(r,s);if(!hi.has(e)){hi.add(e);let r=()=>{let i=Xt.get(e);Fs(e,i?.text,i?.name??n)};s.addEventListener?.("resize",r),e.fonts?.addEventListener?.("loadingdone",r),e.fonts?.ready?.then(r)}}}function Xc(e,t){if(!e.style)return;e.hasAttribute(Us)&&(e.style.removeProperty("font-size"),e.style.removeProperty("white-space"),e.style.removeProperty("overflow-wrap"),e.removeAttribute(Us));let n=e.clientWidth;if(!n)return;let s=e.style.whiteSpace;e.style.whiteSpace="nowrap";let o=e.scrollWidth;if(o<=n){e.style.whiteSpace=s;return}let r=parseFloat(t.getComputedStyle(e).fontSize);e.style.fontSize=`${Math.max(Jc,Math.floor(r*n/o*.97))}px`,e.setAttribute(Us,""),e.scrollWidth>n?(e.style.whiteSpace="normal",e.style.overflowWrap="anywhere"):e.style.whiteSpace=s}function Zc(e,t,n){if(typeof e.querySelectorAll!="function")return;let s=Xt.get(e)??{},o=t?.trim()||void 0;if(!o){if(s.text)for(let i of Array.from(e.querySelectorAll(`[${ze}]`)))i.removeAttribute(ze),i.removeAttribute("aria-label"),n&&(i.textContent=n);s.observer?.disconnect(),Xt.set(e,{name:n});return}if(s.text!==o)for(let i of Array.from(e.querySelectorAll(`[${ze}]`)))i.removeAttribute(ze);s.text=o,s.name=n,Xt.set(e,s),mi(e);let r=e.defaultView;if(!s.observer&&r?.MutationObserver&&e.body){let i=!1;s.observer=new r.MutationObserver(()=>{i||(i=!0,queueMicrotask(()=>{i=!1,mi(e)}))}),s.observer.observe(e.body,{childList:!0,subtree:!0,characterData:!0})}}function ed(e,t,n){let s=e.defaultView,o=s?.gamestageSplash;if(!o?.update)return;let r=t.cssVariables??{};o.update({start:t.splashGradientStart||r.backgroundMainColour,end:t.splashGradientEnd||r.backgroundContainerColour,ink:t.titleColour,accent:t.logoAccentColour,play:t.splashPlayLabel,resume:t.splashContinueLabel,error:t.splashErrorText,retry:t.splashRetryLabel});let i=e.querySelector(".gs-boot__logo"),a=()=>s?.gamestageSplash?.fit?.(),d=t.logoText?.trim()||n;i&&d&&i.getAttribute(ze)!==d&&(i.replaceChildren(...In(d).map(u=>{if(!u.accent)return e.createTextNode(u.text);let c=e.createElement("span");return c.className="gs-boot__accent",c.textContent=u.text,c})),i.setAttribute(ze,d),n&&i.setAttribute("aria-label",n),a())}ds();var td="US1 1 10;AG1 1 10;AI1 1 10;AS1 1 10;BB1 1 10;BM1 1 10;BS1 1 10;CA1 1 10;DM1 1 10;DO1 1 10;GD1 1 10;GU1 1 10;JM1 1 10;KN1 1 10;KY1 1 10;LC1 1 10;MP1 1 10;MS1 1 10;PR1 1 10;SX1 1 10;TC1 1 10;TT1 1 10;VC1 1 10;VG1 1 10;VI1 1 10;RU7 8 10;KZ7 8 10;EG20 0 10;ZA27 0 5.6.7.8.9;GR30 0 10;NL31 0 9.11;BE32 0 9;FR33 0 9;ES34 0 9;HU36 06 9;IT39 0 9.10;VA39 0 9.10;RO40 0 9;CH41 0 9;AT43 0 7.8.9.10.11.12.13;GB44 0 10;GG44 0 10;IM44 0 10;JE44 0 10;DK45 0 8;SE46 0 9;NO47 0 8;SJ47 0 8;PL48 0 9;DE49 0 10.11;PE51 0 9;MX52 0 10;CU53 0 8;AR54 0 10.11;BR55 0 10.11;CL56 0 9;CO57 0 10;VE58 0 10;MY60 0 9.10;AU61 0 9;CC61 0 9;CX61 0 9;ID62 0 9.10.11.12;PH63 0 10;NZ64 0 8.9.10;SG65 0 8;TH66 0 9;JP81 0 10;KR82 0 9.10;VN84 0 9;CN86 0 11;TR90 0 10;IN91 0 10;PK92 0 10;AF93 0 9;LK94 0 9;MM95 0 7.8.9.10;IR98 0 10;SS211 0 9;MA212 0 9;EH212 0 9;DZ213 0 9;TN216 0 8;LY218 0 9;GM220 0 7.9;SN221 0 9;MR222 0 8;ML223 0 8;GN224 0 9;CI225 10;BF226 0 8;NE227 0 8;TG228 0 8;BJ229 10;MU230 0 8;LR231 0 7.9;SL232 0 8;GH233 0 9;NG234 0 10;TD235 0 8;CF236 0 8;CM237 0 9;CV238 0 7;ST239 0 7;GQ240 0 9;GA241 7.8;CG242 9;CD243 0 7.9;AO244 0 9;GW245 0 9;IO246 0 7;AC247 0 5;SC248 0 7;SD249 0 9;RW250 0 9;ET251 0 9;SO252 0 7.8.9;DJ253 0 8;KE254 0 9;TZ255 0 9;UG256 0 9;BI257 0 8;MZ258 0 9;ZM260 0 9;MG261 0 9;RE262 0 9;YT262 0 9;ZW263 0 9;NA264 0 9;MW265 0 9;LS266 0 8;BW267 0 8;SZ268 0 8;KM269 0 7;SH290 0 5;TA290 0 4;ER291 0 7;AW297 0 7;FO298 0 6;GL299 0 6;GI350 0 8;PT351 0 9;LU352 0 9;IE353 0 9;IS354 0 7.9;AL355 0 9;MT356 0 8;CY357 0 8;FI358 0 6.7.8.9.10;AX358 0 6.7.8.9.10;BG359 0 8.9;LT370 0 8;LV371 0 8;EE372 0 7.8;MD373 0 8;AM374 0 8;BY375 8 9;AD376 0 6.9;MC377 0 8.9;SM378 0 8;UA380 0 9;RS381 0 8.9.10;ME382 0 8;XK383 0 8;HR385 0 8.9;SI386 0 8;BA387 0 8.9;MK389 0 8;CZ420 0 9;SK421 0 9;LI423 0 7.9;FK500 0 5;BZ501 0 7;GT502 0 8;SV503 0 8;HN504 0 8;NI505 0 8;CR506 0 8;PA507 0 7.8;PM508 0 6.9;HT509 0 8;GP590 0 9;BL590 0 9;MF590 0 9;BO591 0 8;GY592 0 7;EC593 0 9;GF594 0 9;PY595 0 9;MQ596 0 9;SR597 0 7;UY598 0 8;CW599 0 7.8;BQ599 0 7;TL670 0 8;NF672 0 6;BN673 0 7;NR674 0 7;PG675 0 8;TO676 0 7;SB677 0 5.7;VU678 0 7;FJ679 0 7;PW680 0 7;WF681 0 6;CK682 0 5;NU683 0 4.7;WS685 0 7.10;KI686 0 8;NC687 0 6;TV688 0 6.7;PF689 0 8;TK690 0 4.5.6.7;FM691 0 7;MH692 1 7;KP850 0 10;HK852 0 8;MO853 0 8;KH855 0 8.9;LA856 0 9.10;BD880 0 10;TW886 0 9;MV960 0 7;LB961 0 7.8;JO962 0 9;SY963 0 9;IQ964 0 10;KW965 0 8;SA966 0 9;YE967 0 9;OM968 0 8;PS970 0 9;AE971 0 9;IL972 0 9;BH973 0 8;QA974 0 8;BT975 0 8;MN976 0 8;NP977 0 10;TJ992 0 9;TM993 8 8;AZ994 0 9;GE995 0 9;KG996 0 9;UZ998 0 9",Nn=td.split(";").map(e=>{let[t,n,s]=e.split(" ");return[t.slice(0,2),t.slice(2),n,s.split(".").map(Number)]});var Zt=new Map(Nn.map(e=>[e[0],e])),nd="GB",sd=`\n.gs-notify-form [hidden]{display:none!important}\n:where(.gs-notify-field){display:grid;gap:12px}\n:where(.gs-notify-via){display:flex;gap:4px;margin:0;padding:4px;border:0;border-radius:10px;background:var(--bg,#fff)}\n:where(.gs-notify-via legend){position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}\n:where(.gs-notify-via label){flex:1;display:block;position:relative;cursor:pointer}\n:where(.gs-notify-via input){position:absolute;inset:0;margin:0;opacity:0;cursor:pointer}\n:where(.gs-notify-via span){display:block;padding:10px 12px;border-radius:8px;text-align:center;font-weight:600}\n:where(.gs-notify-via input:checked+span){background:var(--text,#222);color:var(--bg,#fff)}\n:where(.gs-notify-via input:focus-visible+span){outline:3px solid var(--text,#222);outline-offset:2px}\n:where(.gs-notify-phone){display:flex;gap:8px}\n:where(.gs-notify-country){position:relative;flex:none;display:flex;align-items:center;gap:6px;min-height:48px;padding:0 12px;border-radius:10px;background:var(--bg,#fff);white-space:nowrap}\n:where(.gs-notify-country)::after{content:"";width:7px;height:7px;margin:-4px 0 0 2px;border:solid currentColor;border-width:0 2px 2px 0;transform:rotate(45deg)}\n:where(.gs-notify-country select){position:absolute;inset:0;width:100%;opacity:0;cursor:pointer;font:inherit}\n:where(.gs-notify-country:focus-within){outline:3px solid var(--text,#222);outline-offset:3px}\n:where(.gs-notify-phone input){flex:1}\n.gs-notify-form .gs-notify-secondary{min-height:48px;padding:12px 20px;border:1.5px solid currentColor;border-radius:10px;background:transparent;color:inherit;font:inherit;font-weight:600;cursor:pointer}\n.gs-notify-form .gs-notify-secondary:disabled{opacity:.55;cursor:default}\n.gs-notify-form .gs-notify-link{min-height:0;padding:4px 0;border:0;background:none;color:inherit;font:inherit;text-decoration:underline;text-underline-offset:3px;cursor:pointer;justify-self:start}\n:where(.gs-notify-confirm){margin-top:16px}\n:where(.gs-notify-confirm input[name=code]){letter-spacing:.3em;font-variant-numeric:tabular-nums;max-width:12ch}\n:where(.gs-notify-error){margin:0;color:var(--gs-errorColour,#b3261e);font-weight:600}\n`;function od(e){let t;try{t=new Intl.DisplayNames([e],{type:"region"})}catch{}return Nn.map(([n,s])=>({code:n,name:t?.of(n)??n,dial:`+${s}`})).sort((n,s)=>n.name.localeCompare(s.name,e))}function rd(e){return String.fromCodePoint(...[...e].map(t=>127397+t.charCodeAt(0)))}function id(){let e=typeof navigator>"u"?[]:[...navigator.languages??[],navigator.language];for(let t of e){let n=t?.split("-").slice(1).find(s=>/^[A-Za-z]{2}$/.test(s))?.toUpperCase();if(n&&Zt.has(n))return n}return nd}function Ei(e,t){let n=Zt.get(t);return n&&e.startsWith(n[1])?t:Nn.find(([,s])=>e.startsWith(s))?.[0]}function js(e,t){let n=e.trim().replace(/^00/,"+"),s=n.replace(/\\D/g,""),o=Zt.get(t);if(n.startsWith("+")){let c=Ei(s,t);if(o=c?Zt.get(c):void 0,!o)return;s=s.slice(o[1].length)}else if(!o)return;let[,r,i,a]=o,d=c=>a.includes(c.length);i&&s.startsWith(i)?s=s.slice(i.length):!n.startsWith("+")&&s.startsWith(r)&&!d(s)&&d(s.slice(r.length))&&(s=s.slice(r.length));let u=`+${r}${s}`;return d(s)&&wn(u,"sms")?u:void 0}function ad(e,t){let n=!1,s=!1,o="",r=typeof navigator>"u"?"en-GB":navigator.language||"en-GB",i,a=new Map,d,u=()=>{d!==void 0&&clearInterval(d),d=void 0},c=(f,l)=>{let v=f?.status??0,p=f?.message;return v>=400&&v<500&&p?p:l};if(typeof document<"u"&&document.head&&!document.head.querySelector?.("style[data-gs-notify]")){let f=document.createElement("style");f.setAttribute("data-gs-notify",""),f.textContent=sd,document.head.append(f)}let g=()=>{if(s)return;let f=e.round?.id??"",l=a.get(f)??{email:"",phone:"",country:id(),message:"",pending:!1,saved:!1};a.set(f,l);let v=e.presentation.notify,p=JSON.stringify([f,n,v,l.message,l.pending,l.saved,l.awaiting]);if(p===o)return;o=p;let C=t.contains?.(document.activeElement),S=C?document.activeElement?.name:void 0;if(t.hidden=!n||!v?.enabled||!v.ownerName||!/^https:\\/\\//.test(v.privacyUrl)||!v.channels.length,t.replaceChildren(),t.hidden||!v)return;let _=v.labels,x=v.channels.includes("sms")?"sms":v.channels.includes("rcs")?"rcs":void 0,w=v.channels.includes("email");(!l.channel||(l.channel==="email"?!w:!x))&&(l.channel=x?"phone":"email");let h=(A,U)=>{let X=document.createElement(A);return U&&(X.textContent=U),X},N=t.id||"gs-notify",R=h("h2",_.title);R.id=`${N}-title`,t.setAttribute("aria-labelledby",R.id);let k=h("p");if(k.setAttribute("role","status"),k.hidden=!0,t.append(R,k),u(),l.saved){k.textContent=_.success,k.hidden=!1,C&&(k.tabIndex=-1,k.focus());return}if(l.awaiting){let A=l.awaiting,U=A.channel!=="email";k.textContent=A.note||A.sent,k.hidden=!1;let X=h("form");X.className="gs-notify-form gs-notify-confirm",X.noValidate=!0;let Z=h("input"),te=h("p");if(U){Z.name="code",Z.id=`${N}-code`,Z.autocomplete="one-time-code",Z.inputMode="numeric",Z.maxLength=6,Z.value=A.code,te.id=`${N}-code-error`,te.className="gs-notify-error",te.textContent=A.error,te.hidden=!A.error,Z.setAttribute("aria-describedby",te.id),A.error&&Z.setAttribute("aria-invalid","true");let se=h("label",_.code);se.append(Z);let m=h("div");m.className="gs-notify-field",m.append(se,te);let O=h("button",A.busy?_.pending:_.confirm);O.type="submit",O.disabled=A.busy,X.append(m,O),Z.oninput=()=>{A.code=Z.value.replace(/\\D/g,"").slice(0,6),Z.value!==A.code&&(Z.value=A.code),A.code.length===6&&!A.busy&&yn()}}let ne=h("button");ne.type="button",ne.className="gs-notify-secondary";let Ft=()=>{let se=Math.ceil((A.resendAt-Date.now())/1e3);ne.disabled=se>0||A.busy,ne.textContent=se>0?_.resend_wait.replaceAll("{seconds}",String(se)):U?_.resend_code:_.resend_email,se<=0&&u()};Ft(),A.resendAt>Date.now()&&(d=setInterval(Ft,1e3),d.unref?.());let yt=h("button",_.change_address);yt.type="button",yt.className="gs-notify-link",yt.onclick=()=>{l.awaiting=void 0,l.message="",g()},X.append(ne,yt),t.append(X),U&&C&&Z.focus();let yn=async()=>{if(A.busy||A.code.length!==6){A.code.length!==6&&(A.error=_.code_incomplete,g());return}A.busy=!0,A.error="",g();try{if(await e.client.confirmNotify({roundId:f,channel:A.channel,address:A.address,code:A.code}),s)return;l.awaiting=void 0,l.saved=!0}catch(se){A.error=c(se,_.error),A.code=""}finally{A.busy=!1,!s&&e.round?.id===f&&g()}};X.onsubmit=se=>{se.preventDefault(),yn()},ne.onclick=async()=>{A.busy=!0,g();try{let se=await e.client.resendNotify({roundId:f,channel:A.channel,address:A.address});if(se.status==="confirmed"){l.awaiting=void 0,l.saved=!0;return}A.resendAt=Date.now()+(se.resendAfterSeconds??60)*1e3,A.note=_.resent,A.error=""}catch(se){let m=Number(se.detail?.retryAfterSeconds);Number.isFinite(m)&&m>0&&(A.resendAt=Date.now()+m*1e3),A.note=c(se,_.error)}finally{A.busy=!1,!s&&e.round?.id===f&&g()}};return}let H=h("form");H.className="gs-notify-form",H.noValidate=!0;let ue=new Map,be=A=>{let U=ue.get(A);U&&(U.hidden=!0,U.textContent=""),A.removeAttribute("aria-invalid")},$=h("input");$.type="email",$.name="email",$.autocomplete="email",$.inputMode="email",$.maxLength=254,$.value=l.email,$.oninput=()=>{l.email=$.value,wn($.value.trim(),"email")&&be($)};let ge=(A,U)=>{let X=h("p");return X.id=`${N}-${U}-error`,X.className="gs-notify-error",X.hidden=!0,A.setAttribute("aria-describedby",X.id),ue.set(A,X),X},_e=ge($,"email"),P=h("label",_.email_address);P.append($);let I=h("div");I.className="gs-notify-field",I.append(P,_e),i??=od(r);let G=h("select");G.name="country",G.setAttribute("aria-label",_.country);for(let A of i){let U=h("option",`${A.name} (${A.dial})`);U.value=A.code,U.selected=A.code===l.country,G.append(U)}G.value=l.country;let j=h("span");j.setAttribute("aria-hidden","true");let D=()=>{j.textContent=`${rd(l.country)} +${Zt.get(l.country)?.[1]??""}`};D();let V=h("span");V.className="gs-notify-country",V.append(j,G);let M=h("input");M.type="tel",M.name="phone",M.id=`${N}-phone`,M.autocomplete="tel",M.inputMode="tel",M.maxLength=24,M.value=l.phone,M.oninput=()=>{let A=M.value.trim().replace(/^00/,"+"),U=A.startsWith("+")?Ei(A.replace(/\\D/g,""),l.country):void 0;U&&U!==l.country&&(l.country=U,G.value=U,D()),l.phone=M.value,js(M.value,l.country)&&be(M)},G.onchange=()=>{l.country=G.value,D(),js(M.value,l.country)&&be(M),M.focus?.()};let oe=h("label",_.mobile_number);oe.htmlFor=M.id;let q=h("div");q.className="gs-notify-phone",q.append(V,M);let K=h("div");K.className="gs-notify-field";let Oe=ge(M,"phone");K.append(oe,q,Oe);let re=()=>{be($),be(M)},Le=()=>{I.hidden=l.channel!=="email",K.hidden=l.channel!=="phone"};if(w&&x){let A=h("fieldset");A.className="gs-notify-via",A.append(h("legend",_.via));for(let[U,X]of[["phone",_.sms],["email",_.email]]){let Z=h("label"),te=h("input");te.type="radio",te.name=`${N}-via`,te.value=U,te.checked=l.channel===U,te.onchange=()=>{l.channel=U,l.message="",k.hidden=!0,re(),Le()},Z.append(te,h("span",X)),A.append(Z)}H.append(A)}Le();let Ee=h("p",_.consent.replaceAll("{brand}",v.ownerName)+" "),De=h("a",_.privacy);De.href=v.privacyUrl,De.target="_blank",De.rel="noopener noreferrer",Ee.append(De);let ve=h("button",l.pending?_.pending:_.button);ve.disabled=l.pending,ve.type="submit",H.append(I,K,Ee,ve),t.append(H),k.textContent=l.message,k.hidden=!l.message,(S==="email"||S==="phone")&&(S==="email"?$:M).focus(),H.onsubmit=async A=>{if(A.preventDefault(),l.pending||!e.round||e.round.id!==f)return;l.email=$.value,l.phone=M.value;let U=l.channel==="email",X=U?$:M,Z=U?$.value.trim():js(M.value,l.country),te=U?"email":x;if(re(),!te||!Z||!wn(Z,te)){let ne=U?_e:Oe;ne.textContent=U?_.invalid_email:_.invalid_mobile,ne.hidden=!1,X.setAttribute("aria-invalid","true"),X.focus?.();return}k.hidden=!1,l.pending=!0,o="",ve.disabled=!0,ve.textContent=_.pending,k.textContent="",l.message="";try{let ne=await e.client.subscribeNotify({roundId:f,channel:te,address:Z,consent:{wording:v.wording,termsVersion:v.termsVersion}});if(s)return;["subscribed","already_subscribed"].includes(ne.status)?l.saved=!0:ne.status==="pending_confirmation"?l.awaiting={channel:te,address:Z,sent:ne.fanMessage,code:"",error:"",note:"",busy:!1,resendAt:Date.now()+(ne.resendAfterSeconds??60)*1e3}:l.message=ne.fanMessage}catch(ne){l.message=c(ne,_.error)}finally{l.pending=!1,!s&&e.round?.id===f&&g()}}},y=async()=>{if(s||typeof document>"u"||document.visibilityState!=="visible")return;let f=e.round?.id??"",l=a.get(f),v=l?.awaiting,p=e.presentation.notify;if(!(!l||!v||v.channel!=="email"||v.busy||!p))try{let C=await e.client.subscribeNotify({roundId:f,channel:v.channel,address:v.address,consent:{wording:p.wording,termsVersion:p.termsVersion}});!s&&["subscribed","already_subscribed"].includes(C.status)&&l.awaiting===v&&(l.awaiting=void 0,l.saved=!0,g())}catch{}};typeof document<"u"&&document.addEventListener?.("visibilitychange",y);let b=e.onRoundChanged(()=>{n=!1,g()}),T=e.onPresentationChanged(g);return g(),{update(f){n=f?.finished===!0&&f.outcome==="pending",g()},destroy(){s=!0,u(),b(),T(),typeof document<"u"&&document.removeEventListener?.("visibilitychange",y),t.replaceChildren(),t.hidden=!0}}}var $l=new Set(["comment"]);function $a(e){let n=e.outcome==="accepted"||e.outcome==="duplicate"?e.round_state?.progress?.guesses?.at(-1):void 0;return n?{...e,guessed:n}:e}function Ef(e,t){if(!t?.finished||t.outcome!=="won"||!e||e.plays<2)return null;let n=t.progress?.guesses;if(!Array.isArray(n)||n.length===0)return null;let s=n.length,o=0;for(let[r,i]of Object.entries(e.pick_shares??{}))typeof i!="number"||!(i>0)||(r==="X"||/^\\d+$/.test(r)&&Number(r)>s)&&(o+=i);return Math.max(0,Math.min(100,Math.round(o*100)))}function Gl(e){let t=e.GAMESTAGE_API,n=e.GAMESTAGE_GAME;if(!t||!n)throw new Error("This game has no Gamestage configuration. `window.GAMESTAGE_API` and `window.GAMESTAGE_GAME` are written by `gamestage deploy` and printed by `gamestage dev`.");return{api:t,game:n}}function hn(e,t){let n=new URLSearchParams(t??""),s=o=>{let r=n.get(o);return r&&r.trim()?r.trim():void 0};return{host:s("h")??e.GAMESTAGE_IC_HOST,projectId:s("p")??e.GAMESTAGE_IC_PROJECT,eventId:s("e")??e.GAMESTAGE_IC_EVENT,locale:s("locale")??e.GAMESTAGE_LOCALE,theme:s("theme")??e.GAMESTAGE_THEME}}function Ho(e,t=globalThis.navigator){let n=e.locale??t?.languages?.[0]??t?.language;return n&&n.trim().split(/[-_]/)[0].toLowerCase()||void 0}var Ga=3e4;async function Ul(e,t,n){let s=`${e.replace(/\\/+$/,"")}/public/v1/platform/${encodeURIComponent(t)}`;try{let o=AbortSignal.timeout?AbortSignal.timeout(Ga):void 0,r=await n(s,o?{signal:o}:void 0);if(!r.ok)return{because:r.status===404?`${t} is not on Interaction Cloud: the control plane answered 404.`:`asking for this game\'s platform ids answered ${r.status}.`};let i=await r.json(),a=typeof i.project=="string"?i.project:void 0,d=typeof i.host=="string"?i.host:void 0,u=typeof i.name=="string"&&i.name.trim()?i.name:void 0;if(!a||!d)return{because:"the control plane answered without both a project and a host, so there is nothing connectable to use."};let c=typeof i.analytics_url=="string"&&/^https:\\/\\//.test(i.analytics_url)?i.analytics_url:void 0,g=i.services?.comments,y=typeof g?.topic_id=="string"&&typeof g.api=="string"&&/^https:\\/\\//.test(g.api)?{topicId:g.topic_id,api:g.api}:void 0;return{host:d,projectId:a,name:u,analyticsUrl:c,comments:y}}catch(o){return{because:o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?`the control plane did not answer within ${Ga/1e3}s, so this page is playing the round without a Studio connection. A producer\'s words and live updates will reach the next load.`:`asking for this game\'s platform ids failed: ${o instanceof Error?o.message:String(o)}`}}}async function Fl(e,t,n){let s=hn(e,t),o=s.host,r=s.projectId,i=s.eventId,a,d,u,c;if((!o||!r)&&e.GAMESTAGE_IC_LOOKUP&&n?.api&&n?.game){n?.step?.("looking-up");let g=await Ul(n.api,n.game,n.fetch??fetch);o??=g.host,r??=g.projectId,d=g.name,u=g.analyticsUrl,c=g.comments,a=g.because}else(!o||!r)&&e.GAMESTAGE_IC_LOOKUP&&(a="this page carries no Interaction Cloud ids and no API to ask for them.");if((!o||!r)&&e.GAMESTAGE_IC_LOOKUP)throw new Error(a??"this game could not reach Interaction Cloud and there is no reason recorded.");return!o||!r?{deployedName:d,projectId:r,platform:Rs({pollMilliseconds:5e3,offPlatformReason:a,...typeof e.GAMESTAGE_LIVE_SOURCE=="string"?{liveSource:e.GAMESTAGE_LIVE_SOURCE}:{},presentation:at(e.GAMESTAGE_PRESENTATION,Ho(s)),signInSettings:zt(e.GAMESTAGE_PRESENTATION,Ho(s))})}:{deployedName:d,projectId:r,analyticsUrl:u,comments:c,platform:await jl({host:o,projectId:r,eventId:i,locale:Ho(s),settingsConsent:n?.settingsConsent},n?.step)}}async function jl(e,t){t?.("loading-kits");let n=await Promise.resolve().then(()=>(Da(),La));return t?.("opening"),n.createMonterosaPlatform(e)}async function Cf(e={}){let t=e.globals??globalThis.window??globalThis,{api:n,game:s}=Gl(t),o=e.search??globalThis.location?.search,r=m=>{try{e.onStep?.(m)}catch{}},i=()=>({declared:!1,categories:{}}),a=e.platform!==void 0?Promise.resolve({platform:e.platform,deployedName:void 0}):Fl(t,o,{api:n,game:s,fetch:e.fetch,step:r,settingsConsent:()=>i()});a.catch(()=>{});let d=t.location??globalThis.location,u=e.signIn!==!0||typeof document>"u"||!d?.hostname?void 0:Fr({game:s,hostname:d.hostname,fetch:e.fetch,document,store:globalThis.localStorage,mayRemember:()=>Et(i(),"functional"),session:()=>rs(s)});u?.state==="off"&&u.stop();let c=u&&u.state!=="off"?u:void 0,y=!pe(await ae(e.identity))&&c?c.begin():void 0;y&&c?.rememberedGranted()&&await Promise.race([y,new Promise(m=>setTimeout(m,1500))]);let b=async()=>pe(await ae(e.identity))??await c?.token()??void 0,T=await ae(b),f=t.GAMESTAGE_HOST_OWNS_CONSENT===!0,l={analyticsRequiresConsent:f||(e.consent?.analyticsRequiresConsent??!0)},v,p=()=>v?.reading()??{declared:!1,categories:{necessary:!0}},C=Lr({policy:l,destinations:e.destinations??[],consent:p}),S=null,_=!1,x=()=>{if(S||_)return;let m=k.presentation?.analyticsUrl?.trim()||be;!m||!ue||ct(l,p())&&(_=!0,Gr({game:s,projectId:ue,serviceUrl:m,now:()=>k.clock.now(),onObservation:O=>{C.track(O)}}).then(O=>{S=O}).catch(()=>{}).finally(()=>{_=!1}))},w=()=>{S?.stop(),S=null},h=Zo({baseUrl:n,game:s,fetch:e.fetch,identity:async()=>(T=await ae(b),pe(T))}),N=t.GAMESTAGE_FORMAT==="arcade"||t.GAMESTAGE_FORMAT==="mystery"||t.GAMESTAGE_FORMAT==="quiz";N||r("fetching-round");let R=N?Promise.resolve({ok:"none"}):h.getCurrentRound().then(m=>({ok:!0,value:m}),m=>({ok:!1,cause:m})),{platform:k,deployedName:H,projectId:ue,analyticsUrl:be,comments:$}=await a;if(k.settingsSource?.()==="none"){let m=t,O=globalThis;throw Wr({document:m.document??O.document,location:m.location??O.location}),new Yt}let ge=ts(t),_e=()=>or(sr(k.presentation?.gate,ge),f),P=_e(),I=bn(P,s),G=async(m=P)=>{if(!m)return!1;try{return await h.declare(jt(m)),!0}catch{return!1}},j=I.then(()=>G()),D,V=()=>{if(D)return D;let m=_e()??P;return m?(P=m,D=(async()=>(os(s),await bn(m,s),G(m)))().finally(()=>{D=void 0}),D):Promise.resolve(!1)};v=ks({platform:k,policy:l,game:s,scope:e.consentScope,policyVersion:k.presentation?.consentPolicyVersion,embedOrigins:k.presentation?.embedOrigins,hostManagesConsent:xs(typeof document>"u"?void 0:document,k.presentation?.oneTrustId,f),hostOwnsConsent:f}),i=p,v.onChange(m=>{ct(l,m)?x():w(),k.rememberSettings?.()}),k.rememberSettings?.(),x();let M,oe={reading:p,allowed:()=>dt(l,p()),record:()=>v?.record()??null,needed:()=>v?.needed()??l.analyticsRequiresConsent,hostDecides:()=>v?.hostDecides()??!1,decide:m=>v?.decide(m)??!1,declare:m=>v?.decide(m)??!1,onChange:m=>v?.onChange(m)??(()=>{}),openSettings:()=>M?.open()};if(await I,typeof document<"u"&&e.consentBanner!==!1&&!f&&(M=Is({presentation:k.presentation,consent:oe},e.consentBanner??{})),c&&y){let m=()=>{if(oe.needed())return;let O=k.presentation??{},fe=O.cssVariables??{};c.offer({playAs:O.signInPlayAsLabel,detail:O.signInDetail,dismiss:O.signInDismissLabel},{accent:fe.highlightMainColour??O.primaryColour,onAccent:fe.onHighlightMainColour,surface:fe.backgroundMainColour,text:fe.onBackgroundMainColour})};y.then(m),oe.onChange(()=>m()),c.onChange(O=>{O==="granted"&&ae(b).then(fe=>{T=fe})})}let q,K=new Set,Oe=async(m=!1)=>{if(!N)try{let O=await h.getCurrentRound();return Ct(k.clock,O.server_time),q=O,O}catch(O){if(m)throw O;return}},re=await R,Le=re.ok==="none"||re.ok===!1&&re.cause instanceof Error&&re.cause.status===404&&["not_found","no_round"].includes(re.cause.code??"");if(re.ok===!1&&!Le)throw re.cause;re.ok===!0&&(Ct(k.clock,re.value.server_time),q=re.value);let Ee=(m,O)=>m!==void 0&&m.id===O.id&&m.version===O.version&&(m.settled_revision??0)===(O.settled_revision??0)&&m.provisional===O.provisional&&m.challenge_instance_id===O.challenge_instance_id,De,ve=k.onRoundAnnounced(()=>{(async()=>{let m=q,O=await Oe();if(O&&!Ee(m,O))for(let fe of[...K])fe(O)})()},()=>!!(q&&(q.provisional===!0||q.awaits_settlement===!0&&!q.can.results_available&&(q.can.closed||(q.locks_at?k.clock.now()>=Date.parse(q.locks_at):De===q.id))))),A=!1,U=(()=>{let m=Es(k.presentation),O=e.busy?.copy;return{atCapacity:{...m.atCapacity,...O?.atCapacity??{}},rateLimited:{...m.rateLimited,...O?.rateLimited??{}},cappedToday:{...m.cappedToday,...O?.cappedToday??{}}}})();function X(m,O){if(e.busy?.enabled!==!1)try{Cs(m,{copy:U,...e.busy?.container===void 0?{}:{container:e.busy.container},...e.busy?.document?{document:e.busy.document}:{},...O===void 0?{}:{retryAfterSeconds:O}})}catch{}}let Z=typeof globalThis.document>"u"?()=>{}:Jr(()=>({game:s,platform:k.kind,offPlatformReason:k.offPlatformReason,ids:{project:k.projectId??hn(t,o).projectId,event:hn(t,o).eventId,host:hn(t,o).host},round:q?{id:q.id,version:q.version,number:q.number,origin:q.origin}:void 0,endpoints:{playerApi:n,mesh:hn(t,o).host},identity:{kind:T.kind,signedIn:T.kind!=="anonymous"},consent:{allowed:dt(l,p())},presentation:k.presentation}),globalThis),te=!!e?.optimistic&&q?.can.optimistic_play===!0,ne,Ft=as({api:n,game:s,fetch:e.fetch,token:async()=>pe(await ae(e.identity))??h.spaceToken(),gameToken:async()=>pe(await ae(e.identity))?void 0:await c?.token()}),yt=ys({api:n,game:s,fetch:e.fetch,token:async()=>pe(await ae(e.identity))??h.spaceToken(),gameToken:async()=>pe(await ae(e.identity))?void 0:await c?.token(),words:async m=>(await k.elementFields?.(m)??[]).flatMap(O=>bs(O.id,O.fields)??[]),outcomeWords:async m=>(await k.elementFields?.(m)??[]).flatMap(O=>_s(O.id,O.fields)??[])}),yn=t.GAMESTAGE_FORMAT==="arcade"?Bl(h,Ft,{returning:rs(s)!==void 0||!!pe(T)}):h,se=$?cs({api:$.api,topicId:$.topicId,fanToken:()=>h.commentsToken(),fetch:e.fetch}):null;return await j,{platform:k.kind,optimistic:te,id:s,get eventId(){return k.eventId},client:yn,arcade:Ft,quiz:yt,comments:se,streak:async()=>!pe(await ae(e.identity))&&c?.state==="granted"?Ps(await c.streak()):Ns({baseUrl:e.loyalty?.baseUrl,identity:b,fetchImpl:e.fetch}),presentation:k.presentation,get signInSettings(){return k.signInSettings},get needsSignIn(){return!!k.signInSettings?.enabled&&!pe(T)},settingsSource:()=>k.settingsSource?.()??"studio",analytics:C,now:()=>k.clock.now(),deployedName:H,offPlatformReason:k.offPlatformReason,get identity(){return T},async refreshIdentity(){return T=await ae(b),T},signIn:{get state(){return c?.state??"off"},onChange(m){return c?.onChange(m)??(()=>{})},requiredFor(m){return $l.has(m)},async request(){if(!c)return"off";let m=k.presentation??{},O=m.cssVariables??{};return c.request({playAs:m.signInPlayAsLabel,detail:m.signInDetail,dismiss:m.signInDismissLabel},{accent:O.highlightMainColour??m.primaryColour,onAccent:O.onHighlightMainColour,surface:O.backgroundMainColour,text:O.onBackgroundMainColour})}},get round(){return q},onRoundChanged(m){return K.add(m),()=>K.delete(m)},async playNext(){let m=await h.getNextRound();if(m.status!=="ready"||!m.round)return"exhausted";Ct(k.clock,m.server_time),q=m.round;for(let O of K)O(m.round);return"ready"},onPresentationChanged(m){return k.onPresentationChanged(m)},live(m){return m?kn(k,m):ne??=kn(k)},async play(m){let O=q??await Oe();if(!O)throw new Error("There is no round to play. The Engine did not return one.");let fe=m.idempotencyKey??is(),Ae=async()=>{try{return await h.play(O.id,{...m.picks?{picks:m.picks}:{},...m.answers?{answers:m.answers}:{},...m.op?{op:m.op}:{},...m.centre!==void 0?{centre:m.centre}:{},...m.board!==void 0?{board:m.board}:{},...m.operation?{operation:m.operation}:{},...m.room?{room:m.room}:{},roundVersion:O.version},fe)}catch(Ie){throw Ie?.status===429&&X("rateLimited"),Ie&&typeof Ie=="object"&&(Ie.idempotency_key=fe),Ie}},$e=await Ae();if($e.outcome==="rejected"&&$e.reason==="declaration_required"&&await V()&&($e=await Ae()),$e.outcome==="busy"){let Ie=$e;X(ws(Ie.reason),Ie.retry_after_seconds)}return Ct(k.clock,$e.server_time),($e.outcome==="accepted"||$e.outcome==="duplicate")&&(De=O.id),{...$e,idempotency_key:fe}},async shoot(m){let{idempotencyKey:O,...fe}=m,Ae=await this.play({operation:bt(fe),idempotencyKey:O}),Ie=Ae.outcome==="accepted"||Ae.outcome==="duplicate"?vn(_n(Ae.round_state)):void 0;return Ie?{...Ae,shot:Ie}:Ae},async draw(m={}){let O=await this.play({operation:{op:"draw"},idempotencyKey:m.idempotencyKey}),Ae=O.outcome==="accepted"||O.outcome==="duplicate"?O.round_state?.progress?.drawn?.at(-1):void 0;return Ae?{...O,drawn:Ae}:O},async solve(m,O={}){return this.play({operation:{op:"solve",text:m},idempotencyKey:O.idempotencyKey})},async guess(m,O={}){return $a(await this.play({operation:{op:"guess",value:m},idempotencyKey:O.idempotencyKey}))},async skip(m={}){return $a(await this.play({operation:{op:"skip"},idempotencyKey:m.idempotencyKey}))},track(m,O={}){return S?.track(m,O),C.track({name:m,properties:O,at:k.clock.now()})},consent:oe,storage:{read:m=>dt(l,p())?k.storage.read(m):Promise.resolve(null),write:async(m,O)=>dt(l,p())?(await k.storage.write(m,O),!0):!1,remove:async m=>dt(l,p())?(await k.storage.remove(m),!0):!1},stop(){Z(),!A&&(A=!0,ve(),K.clear(),w(),M?.stop(),v?.stop(),c?.stop(),k.stop())}}}var ql=5e3;function Bl(e,t,{returning:n}){let s=async()=>{try{let{ticket:r}=await e.getNameTicket();await t.setName(r)}catch(r){let i=r?.code??"unknown";console.warn(`gamestage: the chosen name did not reach the board (${i}). Play carries on.`)}},o=async()=>{let r;try{await Promise.race([s(),new Promise(i=>r=setTimeout(i,ql))])}finally{clearTimeout(r)}};return n&&e.getProfile().then(r=>r.name_chosen?s():void 0).catch(()=>{}),{...e,async setIdentity(r){let i=await e.setIdentity(r);return r.name&&await o(),i}}}export{Mr as ANALYTICS_CATEGORY,vt as ArcadeError,lt as BUSY_MODAL_ID,Ss as DEFAULT_BUSY_COPY,Xo as GOAL_GEOMETRY,Yt as GamestageUnavailableError,wt as QuizError,Zr as SETTINGS_CACHE_CATEGORY,Jo as SHOOT_INPUT,bi as TITLE_SELECTOR,An as UNAVAILABLE_COPY,ct as analyticsAllowed,Dc as applyPresentation,ws as busyKindFor,as as createArcadeClient,Kt as createClock,cs as createCommentsClient,ks as createConsentState,kn as createLiveContest,Rs as createLocalPlatform,jl as createMonterosaPlatform,ys as createQuizClient,Za as editionBoard,On as flatten,os as forgetGate,yi as gamestageUiTokens,ts as gateFrom,jt as gateKey,Et as granted,Ef as guessBetterThan,Yo as hasDeclared,xs as hostRunsConsentManager,Ds as hostname,vn as latestShot,Ho as localeFor,Is as mountConsent,ad as mountNotify,Nc as mountProvisionalResult,Mc as mountRecovery,is as newIdempotencyKey,bn as passGate,ns as placeNames,hn as platformIds,oi as provisionalResultText,_s as quizOutcomeFromFields,bs as quizWordsFromFields,wc as readLoyalty,Ns as readStreak,Es as resolveBusyCopy,ae as resolveIdentity,Ct as sampleIso,ei as settingsCacheAllowed,bt as shootOperation,_n as shootProgressOf,Cs as showBusyModal,Ts as signInMemoryKey,Ur as siteForGame,Cf as start,dt as storageAllowed,Ic as streakFrom,_i as titleTreatment,pe as tokenOf};\n/*! Bundled license information:\n\n@monterosa/sdk-util/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @preserve\n * Global object polyfill.\n * Based on MDN article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\n *\n * @internal\n *\n * @returns typeof globalThis\n *)\n (**\n * @license\n * fromentries.ts\n * util\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * checksum.ts\n * util\n *\n * Copyright \xA9 2025 Monterosa. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-util\n *\n * Copyright \xA9 2022-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-core/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2023-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2021-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-core\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-bridge-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2022-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-bridge-kit\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-storage-kit/dist/index.js:\n (**\n * @license\n * types.ts\n * storage-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * storage_impl.ts\n * storage-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-storage-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * api.ts\n * storage-kit\n *\n * Copyright \xA9 2025-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-enmasse-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-enmasse-kit\n *\n * Copyright \xA9 2023-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-connect-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-connect-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-connect-kit\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-consent-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-consent-kit\n *\n * Copyright \xA9 2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-analytics-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-analytics-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-analytics-kit\n *\n * Copyright \xA9 2025-2026 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-interact-interop/dist/index.js:\n (**\n * @license\n * api.ts\n * interact-interop\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n\n@monterosa/sdk-interact-kit/dist/index.js:\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2022 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2022-2024 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2023 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n (**\n * @license\n * @monterosa/sdk-interact-kit\n *\n * Copyright \xA9 2025 Monterosa Productions Limited. All rights reserved.\n *\n * More details on the license can be found at https://www.monterosa.co/sdk/license\n *)\n*/\n//# sourceMappingURL=https://gamestage.ai/client/0.112.0/gamestage.js.map\n',cs="47cc43f4ac4efd06",Tn="gamestage.js",us="0.112.0",Ice=`<!doctype html>
900
900
  <html lang="en">
901
901
  <head>
902
902
  <meta charset="utf-8" />
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gamestage",
3
- "version": "0.76.0",
3
+ "version": "0.77.0",
4
4
  "description": "Take a browser game to production: answers, scoring, locks and settlement behind a server the player cannot edit.",
5
5
  "bin": {
6
6
  "gamestage": "./cli.mjs"