@caisual/cli 0.17.0 → 0.20.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Damiano Rodriguez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @caisual/cli
2
+
3
+ Create, test and publish browser games on [Caisual](https://caisual.com), a free home for small browser games with multiplayer built in.
4
+
5
+ ```sh
6
+ npx @caisual/cli init my-game
7
+ cd my-game
8
+ npx @caisual/cli dev
9
+ export CAISUAL_KEY='ck_...'
10
+ npx @caisual/cli publish
11
+ ```
12
+
13
+ A game is a folder with `caisual.json`, `client/index.html` and, for rooms, `server.js`. Every publish creates a new immutable version behind one permanent address, `caisual.com/g/<id>`.
14
+
15
+ ## Commands
16
+
17
+ ```text
18
+ caisual init [--multiplayer | --arcade] [folder]
19
+ caisual dev [folder] [--port 8790] [--day YYYY-MM-DD] [--latency ms [--jitter ms] [--loss percent]]
20
+ caisual check [folder] [--json]
21
+ caisual publish [folder]
22
+ caisual versions [folder|id]
23
+ caisual rollback [folder|id] --to <n>
24
+ caisual unlist [folder|id]
25
+ caisual relist [folder|id]
26
+ caisual delete [folder|id] --yes
27
+ caisual skill
28
+ ```
29
+
30
+ `dev` runs the game locally with the production handshake, several guests and network simulation. `check` runs every local validation used by publish without a key. `skill` writes the publishing guide, the kit reference and the index of the guides into `.claude/skills/caisual/SKILL.md`, so a coding agent reads the rules before it starts; `init` does the same in the new folder.
31
+
32
+ ## Documentation
33
+
34
+ - [Publishing guide](https://caisual.com/publish.md): the folder, the manifest, the limits and every command.
35
+ - [Kit reference](https://caisual.com/kit.md): the API the game calls, from [`@caisual/kit`](https://www.npmjs.com/package/@caisual/kit).
36
+ - [Guides](https://caisual.com/docs) and [llms.txt](https://caisual.com/llms.txt) for coding agents.
37
+
38
+ Requires Node.js 20 or newer. Publishing is free; games run on caisual.com.
package/dist/caisual.mjs CHANGED
@@ -5268,7 +5268,7 @@ var DevService = class {
5268
5268
  response.setHeader("Content-Type", "text/javascript; charset=utf-8");
5269
5269
  response.setHeader("Cache-Control", "no-store");
5270
5270
  response.setHeader("X-Content-Type-Options", "nosniff");
5271
- response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.16.0\nvar kt=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],xt=new Set(kt),Mt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function ge(n){return n.length>=3&&n.length<=32&&Mt.test(n)||Ct.test(n)}function Ne(n){return xt.has(n)}function G(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function Ce(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function Pt(n,e="en"){let t=[],i=G(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(G(e)??e),[...new Set(t)]}function je(n,e=[]){let t=e.map(G).filter(r=>r!==null),i=n.map(G).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let s of Pt(r,r))if(t.includes(s))return s;return t[0]}function Ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function Ue(n,e){let t=e===null?void 0:n.modes.find(i=>i.id===e);if(e!==null&&t===void 0)throw new Error("The selected game mode does not exist.");return{players:{...t?.players??n.players},lobby:t?.lobby??n.lobby}}function ve(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var P=24;var Tt=3e3,Je=32,At=new Set(["overlay","manifest","id","name","description","cover","card","icon","screenshots","tags","languages","language","platform","orientation","input","visibility","network","isolated","requires","players","lobby","persistent","replays","spectators","boards","roles","teams","voice","modes"]),It=new Set(["keyboard","mouse","touch","gamepad"]),Ot=new Set(["desktop","mobile","both"]),Et=new Set(["landscape","portrait"]),_t=new Set(["public","unlisted"]),zt=new Set(["none","room","team","proximity"]),Vt=new Set(["light","medium","heavy"]),Lt=/^[a-z0-9-]+$/,qe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,$t=/^[a-z0-9][a-z0-9-]{0,31}$/,Dt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Be(n){if(n===""||n.startsWith("/")||n.includes("\\\\")||n.includes("\\0")||n.includes("?")||n.includes("#"))return!1;let e=n.split("/");if(e.some(t=>t===""||t==="."||t===".."))return!1;try{return!e.map(i=>decodeURIComponent(i)).some(i=>i===""||i==="."||i===".."||i.includes("/"))}catch{return!1}}function Nt(n){return n.length===0||n.length>253||n.includes("://")||/[/:?#@]/.test(n)?!1:n.split(".").every(t=>t.length>=1&&t.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(t))}function V(n,e,t){return typeof n=="number"&&Number.isInteger(n)&&n>=e&&n<=t}function Pe(n,e,t,i){let r=n[e];return r===void 0?t:typeof r!="string"?(i.push(`${e}: must be a string.`),t):r}function ye(n,e,t,i,r){if(n[e]===void 0)return;let s=(h,d)=>{if(typeof h!="string"||h.trim().length===0||h.trim().length>t||/[\\r\\n\\u0000-\\u001f]/.test(h)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return h.trim()},o=n[e],a=i?`${i}.${e}`:e;if(typeof o=="string")return s(o,a);let c=J(o);if(!c||Object.keys(c).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[h,d]of Object.entries(c)){let u=G(h);if(!u){r.push(`${a}.${h}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,u)&&r.push(`${a}.${h}: duplicate language.`);let v=s(d,`${a}.${h}`);v!==void 0&&(m[u]=v)}return m}function Te(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let g of Object.keys(t))At.has(g)||e.push(`${g}: unknown field.`);t.manifest===void 0?e.push("manifest: is required and must be 1."):t.manifest!==1&&e.push("manifest: must be exactly 1.");let i=Pe(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(ge(i)?Ne(i)&&e.push("id: this slug is reserved."):e.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters."));let r=Pe(t,"name","",e);t.name===void 0?e.push("name: is required."):typeof t.name=="string"&&(r.trim()===""||r.length>60)&&e.push("name: must contain 1-60 characters.");let s=t.description===""?"":ye(t,"description",500,"",e)??"",o={cover:"",card:"",icon:""},a=new Set;for(let g of["cover","card","icon"]){let f=t[g];if(f==null)e.push(`${g}: is required.`);else if(typeof f!="string"||!Be(f))e.push(`${g}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\\.(png|jpe?g|webp)$/i.test(f)||e.push(`${g}: must be a PNG, JPEG or WebP file.`);let L=decodeURIComponent(f);a.has(L)&&e.push(`${g}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(L),o[g]=f}}let{cover:c,card:m,icon:h}=o,d=[];if(t.screenshots!==void 0)if(!Array.isArray(t.screenshots))e.push("screenshots: must be an array of relative file paths.");else{t.screenshots.length>8&&e.push("screenshots: must contain at most 8 paths.");for(let[g,f]of t.screenshots.entries())typeof f!="string"||!Be(f)?e.push(`screenshots[${g}]: must be a relative file path without query, fragment, or parent segments.`):d.push(f)}let u=[];if(t.tags!==void 0)if(!Array.isArray(t.tags))e.push("tags: must be an array.");else{t.tags.length>10&&e.push("tags: must contain at most 10 tags.");for(let[g,f]of t.tags.entries())typeof f!="string"||f.length>24||!Lt.test(f)?e.push(`tags[${g}]: must be 1-24 lowercase letters, digits, or hyphens.`):u.push(f)}let v=Pe(t,"language","en",e);/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(v)||e.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");let x=[];if(!Array.isArray(t.languages)||t.languages.length===0)e.push("languages: must be a non-empty array of BCP 47 language tags.");else for(let[g,f]of t.languages.entries()){let L=G(f);L?x.includes(L)?e.push(`languages[${g}]: duplicate language ${L}.`):x.push(L):e.push(`languages[${g}]: must be a BCP 47 language tag.`)}x.includes("en")||e.push("languages: English is always required alongside the game\'s own languages.");let w=x[0]??v;if(typeof s=="object")for(let g of Object.keys(s))x.includes(g)||e.push(`description.${g}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&v.toLowerCase()!==w.toLowerCase()&&e.push("language: must match the first entry in languages when both are present.");let N="both";t.platform===void 0?e.push("platform: is required."):typeof t.platform!="string"||!Ot.has(t.platform)?e.push("platform: must be desktop, mobile, or both."):N=t.platform;let _="landscape";t.orientation!==void 0&&(typeof t.orientation!="string"||!Et.has(t.orientation)?e.push("orientation: must be landscape or portrait."):_=t.orientation);let j=[];if(t.input!==void 0)if(!Array.isArray(t.input))e.push("input: must be an array.");else for(let[g,f]of t.input.entries())typeof f!="string"||!It.has(f)?e.push(`input[${g}]: must be keyboard, mouse, touch, or gamepad.`):j.includes(f)?e.push(`input[${g}]: duplicate value ${f}.`):j.push(f);let z="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!_t.has(t.visibility)?e.push("visibility: must be public or unlisted."):z=t.visibility);let B=[];if(t.network!==void 0)if(!Array.isArray(t.network))e.push("network: must be an array of host names.");else for(let[g,f]of t.network.entries())typeof f!="string"||!Nt(f)?e.push(`network[${g}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(f)?e.push(`network[${g}]: duplicate host ${f}.`):B.push(f);t.isolated!==void 0&&typeof t.isolated!="boolean"&&e.push("isolated: must be a boolean.");let U={webgl2:!1,webgpu:!1,wasm:!1,threads:!1,memoryMb:null,performance:"light"};if(t.requires!==void 0){let g=J(t.requires);if(g===null)e.push("requires: must be an object.");else{for(let f of Object.keys(g))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(f)||e.push(`requires.${f}: unknown field.`);for(let f of["webgl2","webgpu","wasm","threads"])g[f]!==void 0&&(typeof g[f]!="boolean"?e.push(`requires.${f}: must be a boolean.`):U[f]=g[f]);g.memoryMb!==void 0&&(g.memoryMb!==null&&(!V(g.memoryMb,512,32768)||g.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):U.memoryMb=g.memoryMb),g.performance!==void 0&&(typeof g.performance!="string"||!Vt.has(g.performance)?e.push("requires.performance: must be light, medium, or heavy."):U.performance=g.performance)}}let F={min:1,max:1};if(t.players!==void 0){let g=J(t.players);if(g===null)e.push("players: must be an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`players.${f}: unknown field.`);V(g.min,1,P)||e.push(`players.min: must be an integer from 1 to ${P}.`),V(g.max,1,P)||e.push(`players.max: must be an integer from 1 to ${P} in manifest version 1.`),V(g.min,1,P)&&V(g.max,1,P)&&(g.min>g.max?e.push("players.max: must be greater than or equal to players.min."):F={min:g.min,max:g.max})}}let W=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):W=t.lobby);let A=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):A=t.persistent);let M=t.replays===!0;t.replays!==void 0&&typeof t.replays!="boolean"&&e.push("replays: must be a boolean.");let ue={delayMs:Tt};if(t.spectators===!1||t.spectators===null)ue=null;else if(t.spectators!==void 0&&t.spectators!==!0){let g=J(t.spectators);if(g===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let f of Object.keys(g))f!=="delayMs"&&e.push(`spectators.${f}: unknown field.`);V(g.delayMs,0,3e4)?ue={delayMs:g.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let ee=null;if(t.overlay!==void 0&&t.overlay!==null){let g=J(t.overlay);if(g===null)e.push("overlay: must be an object or null.");else{for(let f of Object.keys(g))["version","accent"].includes(f)||e.push(`overlay.${f}: unknown field.`);g.version!==1&&e.push("overlay.version: must be exactly 1."),g.accent!==void 0&&(typeof g.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(g.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),ee={version:1,...typeof g.accent=="string"?{accent:g.accent}:{}}}}let I={};if(t.boards!==void 0){let g=J(t.boards);if(g===null)e.push("boards: must be an object of board ids.");else{Object.keys(g).length>Je&&e.push(`boards: at most ${Je} boards.`);for(let[f,L]of Object.entries(g)){let S=!0;Dt.test(f)||(e.push(`boards.${f}: invalid board id.`),S=!1);let b=J(L);if(b===null){e.push(`boards.${f}.source: must be "client" or "server".`);continue}for(let E of Object.keys(b))["source","label","periods","day"].includes(E)||e.push(`boards.${f}.${E}: unknown field.`);b.source!=="client"&&b.source!=="server"&&(e.push(`boards.${f}.source: must be "client" or "server".`),S=!1),b.day!==void 0&&b.day!=="submit"&&b.day!=="start"&&e.push(`boards.${f}.day: must be "submit" or "start".`),b.day==="start"&&b.source!=="server"&&e.push(`boards.${f}.day: start requires source "server".`);let O=ye(b,"label",48,`boards.${f}`,e),T=["all-time"];b.periods!==void 0&&(!Array.isArray(b.periods)||b.periods.length<1||b.periods.length>2||b.periods.some(E=>E!=="daily"&&E!=="all-time")||new Set(b.periods).size!==b.periods.length?e.push(`boards.${f}.periods: must contain daily, all-time, or both without duplicates.`):T=[...b.periods]),S&&Object.defineProperty(I,f,{value:{source:b.source,periods:T,...b.day===void 0?{}:{day:b.day},...O===void 0?{}:{label:O}},enumerable:!0,configurable:!0,writable:!0})}}}let te=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let g=new Set;for(let[f,L]of t.roles.entries()){let S=J(L);if(S===null){e.push(`roles[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","min","max","label"].includes(l)||e.push(`roles[${f}].${l}: unknown field.`);let b=S.id,O=S.min,T=S.max,E=!0;typeof b!="string"||b.length>32||!qe.test(b)?(e.push(`roles[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),E=!1):g.has(b)?(e.push(`roles[${f}].id: duplicate role ${b}.`),E=!1):g.add(b),V(O,0,P)||(e.push(`roles[${f}].min: must be an integer from 0 to ${P}.`),E=!1),T!==void 0&&!V(T,0,P)&&(e.push(`roles[${f}].max: must be an integer from 0 to ${P} when present.`),E=!1),typeof O=="number"&&typeof T=="number"&&O>T&&(e.push(`roles[${f}].max: must be greater than or equal to min.`),E=!1);let ie=ye(S,"label",32,`roles[${f}]`,e);E&&te.push({id:b,min:O,...T===void 0?{}:{max:T},...ie===void 0?{}:{label:ie}})}}let Y=null;if(t.teams!==void 0&&t.teams!==null){let g=J(t.teams);if(g===null)e.push("teams: must be null or an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`teams.${f}: unknown field.`);V(g.min,2,P)||e.push(`teams.min: must be an integer from 2 to ${P}.`),V(g.max,2,P)||e.push(`teams.max: must be an integer from 2 to ${P}.`),V(g.min,2,P)&&V(g.max,2,P)&&(g.min>g.max?e.push("teams.max: must be greater than or equal to teams.min."):Y={min:g.min,max:g.max})}}let re="none";t.voice!==void 0&&(typeof t.voice!="string"||!zt.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):re=t.voice);let H=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let g=new Set;for(let[f,L]of t.modes.entries()){let S=J(L);if(S===null){e.push(`modes[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","players","lobby","matchmaking","execution","label","instructions"].includes(l)||e.push(`modes[${f}].${l}: unknown field.`);if(typeof S.id!="string"||S.id.length>32||!qe.test(S.id)){e.push(`modes[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(g.has(S.id)){e.push(`modes[${f}].id: duplicate mode ${S.id}.`);continue}g.add(S.id);let b={id:S.id};for(let[l,y]of[["label",48],["instructions",160]]){let R=ye(S,l,y,`modes[${f}]`,e);R!==void 0&&(b[l]=R)}if(S.execution!==void 0&&(S.execution!=="local"&&S.execution!=="room"?e.push(`modes[${f}].execution: must be local or room.`):b.execution=S.execution),ee!==null&&b.execution===void 0&&e.push(`modes[${f}].execution: is required with the standard overlay.`),S.players!==void 0){let l=`modes[${f}].players`,y=J(S.players);if(y===null)e.push(`${l}: must be an object with min and max.`);else{for(let R of Object.keys(y))R!=="min"&&R!=="max"&&e.push(`${l}.${R}: unknown field.`);V(y.min,1,P)||e.push(`${l}.min: must be an integer from 1 to ${P}.`),V(y.max,1,P)||e.push(`${l}.max: must be an integer from 1 to ${P}.`),V(y.min,1,P)&&V(y.max,1,P)&&(y.min>y.max?e.push(`${l}.max: must be greater than or equal to min.`):b.players={min:y.min,max:y.max})}}if(S.lobby!==void 0&&(typeof S.lobby!="boolean"?e.push(`modes[${f}].lobby: must be a boolean.`):b.lobby=S.lobby),b.execution==="local"){let l=b.players??F;(l.min!==1||l.max!==1)&&e.push(`modes[${f}].players: local execution requires min and max to be 1.`),(b.lobby??W)&&e.push(`modes[${f}].lobby: local execution requires false.`),S.matchmaking!==void 0&&e.push(`modes[${f}].matchmaking: local execution cannot use matchmaking.`)}if(S.matchmaking===void 0){H.push(b);continue}let O=J(S.matchmaking);if(O===null){e.push(`modes[${f}].matchmaking: must be an object.`);continue}for(let l of Object.keys(O))["key","timeoutMs","defaults"].includes(l)||e.push(`modes[${f}].matchmaking.${l}: unknown field.`);let T=!0,E=[];if(!Array.isArray(O.key)||O.key.length<1||O.key.length>8)e.push(`modes[${f}].matchmaking.key: must contain from 1 to 8 fields.`),T=!1;else for(let[l,y]of O.key.entries())typeof y!="string"||!$t.test(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),T=!1):E.includes(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: duplicate field ${y}.`),T=!1):E.push(y);V(O.timeoutMs,1e3,3e5)||(e.push(`modes[${f}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),T=!1);let ie;if(O.defaults!==void 0){let l=J(O.defaults);if(l===null||Object.keys(l).length!==E.length||E.some(y=>!Object.hasOwn(l,y)))e.push(`modes[${f}].matchmaking.defaults: must contain exactly the declared key fields.`);else{ie={};for(let[y,R]of Object.entries(l))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${f}].matchmaking.defaults.${y}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(ie,y,{value:R,enumerable:!0})}}T&&H.push({...b,matchmaking:{...ie===void 0?{}:{defaults:ie},key:E,timeoutMs:O.timeoutMs}})}}return ee!==null&&H.length===0&&e.push("modes: at least one explicit mode is required with the standard overlay."),e.length>0?{ok:!1,errori:e}:{ok:!0,manifest:{manifest:1,overlay:ee,id:i,name:r,description:s,cover:c,card:m,icon:h,screenshots:d,tags:u,languages:x,language:w,platform:N,orientation:_,input:j,visibility:z,network:B,requires:U,players:F,lobby:W,persistent:A,replays:M,spectators:ue,boards:I,roles:te,teams:Y,voice:re,modes:H}}}function jt(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function Fe(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Gt(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let o=e?.deviceMemory,a=typeof o=="number"?o*1024:NaN;Number.isFinite(a)&&(t=a)}catch{t=null}let i=null;try{let o=e?.hardwareConcurrency;typeof o=="number"&&Number.isFinite(o)&&(i=o)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let s=!1;try{s=n.crossOriginIsolated===!0}catch{s=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:s,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function We(n,e=1500){let t=n??globalThis,i=Gt(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let h=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(h!==null){i.webgl2=!0,i.gpu="hardware",Fe(h);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Fe(d))}catch{i.webgl2=!1,i.gpu="none"}}),s=Promise.resolve().then(async()=>{let m;try{let h=t.navigator?.gpu;if(h===void 0)return;let d=await h.requestAdapter();if(d===null)return;m=await d.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),o=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),a=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),c;return await Promise.race([Promise.all([r,s,o,a]),new Promise(m=>{c=setTimeout(m,Math.max(0,e))})]),c!==void 0&&clearTimeout(c),{...i,tier:jt(i)}}function Ae(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var de=/^[A-Za-z0-9_-]{22}$/;function Bt(n,e=null,t=null,i=null){let r=Te(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");return{manifest:r.manifest,coverUrl:e,iconUrl:i,invite:t}}function D(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Ut(n){let e=D(n),t=D(e?.configuration);return e?.v===1&&typeof e.epoch=="string"&&e.epoch.length>0&&e.epoch.length<=128&&t!==null&&(t.coverUrl===null||typeof t.coverUrl=="string")&&(t.iconUrl===null||typeof t.iconUrl=="string")&&(t.invite===null||typeof t.invite=="string"&&/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(t.invite))&&Te(t.manifest).ok}function He(n){return Ut(n)?{v:1,epoch:n.epoch,configuration:Bt(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Ft(n){let e=D(n);return e!==null&&Object.keys(e).length===4&&["top","right","bottom","left"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])&&Number(e[t])>=0&&Number(e[t])<=1e5)}function Oe(n){let e=D(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Ft(e.safeArea))&&(e.shortcutEnabled===void 0||typeof e.shortcutEnabled=="boolean")&&typeof e.inputBlocked=="boolean"&&Array.isArray(e.reservedRects)&&e.reservedRects.length<=8&&e.reservedRects.every(t=>{let i=D(t);return i!==null&&Object.keys(i).length===4&&["x","y","width","height"].every(r=>typeof i[r]=="number"&&Number.isFinite(i[r])&&i[r]>=0&&i[r]<=1e5)})}function Ke(n){let e=D(n),t=D(e?.args);if(e?.type!=="caisual:overlay"||e.v!==1||typeof e.epoch!="string"||e.epoch.length<1||e.epoch.length>128||typeof e.requestId!="string"||!(/^[1-9][0-9]{0,15}$/.test(e.requestId)&&Number.isSafeInteger(Number(e.requestId)))||t===null||Object.keys(e).some(s=>!["type","v","epoch","requestId","sessionId","op","args"].includes(s))||!(e.sessionId===void 0||e.sessionId===null||typeof e.sessionId=="string"&&/^[1-9][0-9]{0,15}$/.test(e.sessionId)))return!1;let i=(...s)=>Object.keys(t).every(o=>s.includes(o)),r=s=>typeof t[s]=="string"&&t[s].length>=1&&t[s].length<=64;switch(e.op){case"replay.play":case"replay.pause":return i()&&typeof e.sessionId=="string";case"replay.seek":return i("positionMs")&&typeof e.sessionId=="string"&&typeof t.positionMs=="number"&&Number.isFinite(t.positionMs)&&t.positionMs>=0&&t.positionMs<=18e5;case"replay.speed":return i("speed")&&typeof e.sessionId=="string"&&[.5,1,2,4].includes(Number(t.speed))&&typeof t.speed=="number";case"local.start":return i("mode")&&r("mode");case"room.create":return i("mode")&&(t.mode===null||r("mode"));case"room.join":return i("code")&&(t.code===void 0||r("code"));case"room.watch":return i("code")&&r("code");case"room.match":{let s=D(t.key);return i("mode","key")&&r("mode")&&(t.key===void 0||s!==null&&Object.keys(s).length<=8&&Object.values(s).every(o=>typeof o=="string"&&o.length>=1&&o.length<=64||typeof o=="number"&&Number.isSafeInteger(o)))}case"room.ready":return i("ready")&&typeof t.ready=="boolean";case"room.role":case"room.requestRole":return i("role")&&r("role");case"room.team":return i("team")&&Number.isInteger(t.team)&&t.team>=1&&t.team<=24;case"room.restart":case"room.start":case"session.cancel":case"session.leave":case"session.disconnect":case"session.resume":return i();case"voice.join":case"voice.leave":return i()&&typeof e.sessionId=="string";case"voice.mute":return i("muted")&&typeof t.muted=="boolean"&&typeof e.sessionId=="string";case"voice.setVolume":return i("playerId","volume")&&typeof e.sessionId=="string"&&typeof t.playerId=="string"&&t.playerId.length>0&&t.playerId.length<=128&&typeof t.volume=="number"&&Number.isFinite(t.volume)&&t.volume>=0&&t.volume<=1;case"overlay.view":return Oe(t);default:return!1}}function me(n){if(typeof n!="string"||!/^\\d{4}-\\d{2}-\\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isFinite(e)&&new Date(e).toISOString().slice(0,10)===n}function Ye(n,e){let t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,i=t(n);if(!i||!Array.isArray(i.standings))return null;let r=new Set(e),s=new Set,o=[];for(let a of i.standings){let c=t(a);!c||typeof c.playerId!="string"||!r.has(c.playerId)||s.has(c.playerId)||(s.add(c.playerId),o.push({playerId:c.playerId,...typeof c.score=="number"&&Number.isFinite(c.score)?{score:c.score}:{},...typeof c.rank=="number"&&Number.isSafeInteger(c.rank)&&c.rank>0?{rank:c.rank}:{}}))}return o.length?{standings:o,...Array.isArray(i.winners)?{winners:[...new Set(i.winners.filter(a=>typeof a=="string"&&s.has(a)))]}:{},...typeof i.draw=="boolean"?{draw:i.draw}:{},...typeof i.unit=="string"?{unit:i.unit}:{}}:null}function p(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function $(){return p("offline","Caisual services are unavailable.")}function pe(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Wt(n){let e={};try{e=await n.json()}catch{}return p(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function be(n,e,t,i){async function r(s,o,a,c){let m=new Headers({Authorization:`Bearer ${a}`}),h;if(c!==void 0){m.set("Content-Type","application/json");try{h=JSON.stringify(c)}catch{throw p("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+s,n),{method:o,headers:m,body:h,credentials:"omit"})}catch{throw $()}}return async function(o,a,c,m=!1){let h;try{h=m?await i.rinnova():await i.ottieni()}catch{throw $()}let d=await r(o,a,h,c);if(d.status===401){try{h=await i.rinnova()}catch{throw $()}d=await r(o,a,h,c)}if(!d.ok)throw await Wt(d);try{return await d.json()}catch{throw p("internal_error","The service returned an invalid response.")}}}var Ee=.02,Ze=300,Ht=200,Qe=3e3,Kt=1e4,Yt=[1e3,2e3,4e3];function Xe(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Zt(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var we=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Zt(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=this.scegliMic(e);this.verificaIngresso(t),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(p("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw p("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=Xe(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(p(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,Xe(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(p("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(p("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}scegliMic(e){return e.mic!==void 0?e.mic:this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role!=="spectator"}verificaIngresso(e=this.micDesiderato){if(!this.contesto.connessa())throw p("offline","The room is not connected.");if(this.modeCorrente==="none")throw p("voice_disabled","Voice is disabled for this room.");if(this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role==="spectator"&&e)throw p("spectator","Spectators cannot publish voice.");if(this.dipendenze===null)throw p("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let s;try{s=await t.getUserMedia({audio:!0})}catch(a){throw this.permessoNegato(a)?p("permission_denied","Microphone permission was denied."):p("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(a){for(let c of s.getTracks())c.stop();throw a}let o=s.getAudioTracks()[0];if(o===void 0)throw p("voice_error","The microphone has no audio track.");this.stream=s,this.tracciaMic=o,o.enabled=!this.mutedCorrente,this.preparaAnalizzatore(s)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw p("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let s of this.gains.keys())this.aggiornaZero(s);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=s=>{let o=s.transceiver.mid,a=o===null?void 0:this.midGiocatori.get(o);a!==void 0&&this.collegaTraccia(a,s.track,s.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let s=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),o=await i.createOffer();await i.setLocalDescription(o),this.controllaGenerazione(t);let a=s.mid,c=i.localDescription?.sdp;if(a===null||c===void 0)throw p("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:c,mid:a})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw p("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw p("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw p("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,s)=>{let o=()=>{e.removeEventListener("connectionstatechange",a),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},a=()=>{t!==this.generazione?(o(),s(p("offline","Voice was stopped."))):e.connectionState==="connected"?(o(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(o(),s(p("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",a),this.cancellaAttesaConnessione=()=>{o(),s(p("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{o(),s(p("voice_error","The voice connection timed out."))},Kt)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(m=>[m.id,m])),r=[];for(let[m,h]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===h.session&&d.track===h.track||(r.push(h),this.riproduzioni.has(m)||h.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(h.mid),this.scollegaTraccia(m))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(m=>m.mid)});let s=[...i.values()].filter(m=>!this.sfuAttive.has(m.id));if(s.length===0)return;let o;try{o=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:s.map(m=>({session:m.session,track:m.track}))})}catch(m){if(pe(m)!=="not_allowed")throw m;for(let h of s)this.negati.add(h.id);return}if(o.op!=="subscribe")throw p("voice_error","The voice service returned an invalid response.");for(let m of o.tracks){let h=s.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&h!==void 0&&this.negati.add(h.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||h===void 0)&&(this.midGiocatori.set(m.mid,h.id),this.sfuAttive.set(h.id,{session:h.session,track:h.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:o.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let c=t.localDescription?.sdp;if(c===void 0)throw p("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:c}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=s=>{s.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:s.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=s=>{r.receiver=s.receiver,this.collegaTraccia(t,s.track,s.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(o=>o.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let s=t;try{if(s.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(s.candidate);return}if(s.kind!=="offer"&&s.kind!=="answer"||typeof s.sdp!="string")return;let o=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),a=s.kind==="offer"&&!o;if(r.ignoreOffer=!r.polite&&a,r.ignoreOffer)return;if(r.settingRemoteAnswer=s.kind==="answer",await r.pc.setRemoteDescription({type:s.kind,sdp:s.sdp}),r.settingRemoteAnswer=!1,s.kind==="offer"){let c=await r.pc.createAnswer();await r.pc.setLocalDescription(c);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(pe(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>{if(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic)return!1;if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return!1}return!0})}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<Qe})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),s=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,Qe-r));this.timerZero.set(e,s)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),s=r.creaMediaStream([t]),o=this.richiediAudioContext().createMediaStreamSource(s),a=this.richiediAudioContext().createGain();o.connect(a),a.connect(this.richiediAudioContext().destination);let c=null;try{c=this.richiediAudioContext().createAnalyser(),c.fftSize=256,o.connect(c)}catch{c=null}let m=r.creaAudioElement();m.srcObject=s,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:o,gain:a,analyser:c,audio:m,track:t,receiver:i});let h=this.sfuAttive.get(e);h!==void 0&&(h.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Ht)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Ee),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=Ze;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let s of this.copiaPeers()){let o=this.riproduzioni.get(s.id);this.livelloAnalizzatore(o?.analyser??null)>Ee?this.ultimoAudio.set(s.id,e.ora()):(o?.analyser===null||o?.analyser===void 0)&&(o?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Ee)&&this.ultimoAudio.set(s.id,e.ora());let a=!s.muted&&e.ora()-(this.ultimoAudio.get(s.id)??0)<=Ze;(this.speakingPeers.get(s.id)??!1)!==a&&(this.speakingPeers.set(s.id,a),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,s)=>r+s*s,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>{if(r.id===e)return[];if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return[]}return[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}]})}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(p("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Yt[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(p("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(s){this.richieste.delete(t),r(s)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw p("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw p("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw p("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw p("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="spectator"||t==="offline"||t==="voice_error"?e:p("voice_error","Voice could not be started.")}return p("voice_error","Voice could not be started.")}};var ne=1,et=[1e3,2e3,4e3,8e3],Qt=6e4,Xt=5e3,ei=2e4,ti=500,ii=2e3,ni=new Set([4003,4004,4005,4006,4008,4009]);function Q(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function tt(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ri(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function oi(n){let e=Q(n),t=Q(e?.players);return e!==null&&typeof e.url=="string"&&Number.isInteger(e.timeoutMs)&&e.timeoutMs>=1e3&&e.timeoutMs<=3e5&&t!==null&&Number.isInteger(t.min)&&Number.isInteger(t.max)&&t.min>=1&&t.max>=t.min}function Z(n){return JSON.parse(JSON.stringify(n))}function _e(n,e){let t=Z(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Z(i.value);continue}let r=t,s=i.path;for(let a=0;a<s.length-1;a++){let c=s[a];if(Array.isArray(r)){if(typeof c!="number"||c>=r.length)return{ok:!1};r=r[c]}else{let m=Q(r);if(m===null||typeof c!="string"||!Object.hasOwn(m,c))return{ok:!1};r=m[c]}}let o=s.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof o!="number"||o>=r.length)return{ok:!1};r[o]=Z(i.value)}else{let a=Q(r);if(a===null||typeof o!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(a,o))return{ok:!1};delete a[o]}else Object.defineProperty(a,o,{configurable:!0,enumerable:!0,value:Z(i.value),writable:!0})}}return{ok:!0,state:t}}function si(n){let e=be(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,c,m)=>{try{return await e(o,a,{...Q(c),n:n.n},m)}catch(h){if(h instanceof Error&&"code"in h&&["version_outdated","version_mismatch"].includes(String(h.code))){let d=Q(c),u=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\\s-]/g,""):void 0,v=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(h,h.code==="version_mismatch"?{code:u,roomId:v,watch:o==="/rooms/watch"}:void 0)}throw h}};async function i(o,a,c=!1){let m=await t(o,"POST",a,c);if(!tt(m))throw p("internal_error","The room service returned an invalid response.");return m}async function r(o){let a=await t("/match","POST",{mode:o.mode,key:o.key});if(!oi(a))throw p("internal_error","The matchmaking service returned an invalid response.");return a}async function s(o,a=!1){let c=await t("/rooms/watch","POST",o,a);if(!ri(c))throw p("internal_error","The room service returned an invalid response.");return c}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),watchCode:o=>s({code:o}),watchRoom:o=>s({roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var Se=class{constructor(e,t,i,r,s,o,a=!1){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=s;this.segnalaStanza=o;this.spettatore=a;this.meta={host:null,mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.scoreListeners=new Set;this.scores=[];this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.hostCorrente=null;this.resultCorrente=null;this.delaySpettatore=0;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.replay=!1;this.promessaPronta=new Promise((c,m)=>{this.risolviPronta=c,this.rifiutaPronta=m}),this.voice=new we({invia:c=>this.invia(c),connessa:()=>this.socket?.readyState===ne&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),a&&(this.rosterRicevuto=!0),this.apri(i)}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}get queuedScores(){return structuredClone(this.scores)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onScoreQueued(e){return this.scoreListeners.add(e),()=>this.scoreListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.metadataChanged({host:e.host,mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(p("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(p("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(p("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let s=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(p("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:s});try{this.invia({t:"request-role",r:t,role:e})}catch(o){this.dipendenze.clearTimeout(s),this.roleRequests.delete(t),r(o)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(p("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(p("cancelled","The room was disconnected.")))}get role(){return this.spettatore?"spectator":this.giocatoriCorrenti.find(e=>e.id===this.youCorrente)?.role??null}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get host(){return this.hostCorrente}get code(){return this.codice}get result(){return this.resultCorrente}get delayMs(){return this.delaySpettatore}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-29),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw p("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(30,this.tickRateCorrente):30);this.inviiGioco=this.inviiGioco.filter(o=>e-o<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,s=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let o=this.dipendenze.ora();if(o<this.ultimoInvioGioco+i||this.inviiGioco.filter(c=>o-c<1e3).length>=30){this.programmaInput();return}let a=this.ultimoInput;try{this.send(JSON.parse(a)),this.inputInviato=a}catch{}},Math.max(0,Math.ceil(Math.max(s,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}start(){this.invia({t:"start"})}restart(){if(this.statusCorrente!=="finished")throw p("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){if(!this.lasciata){if(this.spettatore||this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===ne){let e=this.socket;this.invia({t:"leave"}),this.spettatore&&e.close(1e3)}this.termina(1e3)}}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==ne)throw p("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw p("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Xt:ei;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===ne)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=Q(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="watching")this.riceviWatching(t);else if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="replay-ready"&&/^[A-Za-z0-9_-]{22}$/.test(t.id))this.metadataChanged({replayId:t.id});else if(t.t==="players")this.riceviGiocatori(t.players,t.host);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,Z(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="score-queued"&&!this.spettatore)this.scores.push(structuredClone(t.score)),this.scores=this.scores.slice(-32),this.notifica(this.scoreListeners,structuredClone(t.score));else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(p(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWatching(e){let t=e.room;!this.spettatore||t.id!==this.roomId||(this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.delaySpettatore=e.delayMs,this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},ii)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e,t){this.giocatoriCorrenti=e.map(i=>({...i})),t!==void 0?this.hostCorrente=t:this.giocatoriCorrenti.some(i=>i.id===this.hostCorrente&&i.connected)||(this.hostCorrente=this.giocatoriCorrenti.find(i=>i.connected)?.id??null),this.metadataChanged({host:this.hostCorrente}),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){(e.status==="playing"||e.status==="countdown"||e.status==="lobby")&&this.metadataChanged({replayId:null}),this.statusCorrente=e.status,e.host!==void 0&&(this.hostCorrente=e.host),this.resultCorrente=Z(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,host:this.hostCorrente,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=_e(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=Z(e),this.statoPubblico=Z(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==ne)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(ni.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.spettatore||this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,et.length-1),t=et[e];if(this.tempoRiconnessione+t>Qt){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=this.spettatore?await this.api.watchRoom(this.roomId):await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let o=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(p(o,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.spettatore&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},ti))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function he(n=null){return{replay:!1,invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw $()},async join(){throw $()},async watch(){throw $()},async match(){throw $()}}}function it(n,e){let t,i=new Set,r=si({...n,onVersionError(d,u){t=u;for(let v of i)try{v(d)}catch{}}}),s=!1,o=null,a=d=>{let u=d?.code??null;s&&u===o||(s=!0,o=u,n.segnalaStanza?.(d))},c=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,a);return await u.pronta(),u},m=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,()=>{},!0);return await u.pronta(),{role:"spectator",replay:!1,get mode(){return u.mode},get countdownAt(){return u.countdownAt},get connection(){return u.connection},get metadata(){return u.metadata},onMetadata:v=>u.onMetadata(v),onConnection:v=>u.onConnection(v),disconnect:()=>u.disconnect(),get state(){return u.state},get tick(){return u.tick},get tickRate(){return u.tickRate},get latency(){return u.latency},get seed(){return u.seed},get status(){return u.status},get players(){return u.players},get host(){return u.host},get code(){return u.code},get result(){return u.result},get delayMs(){return u.delayMs},onState:v=>u.onState(v),onPlayers:v=>u.onPlayers(v),onStatus:v=>u.onStatus(v),onMessage:v=>u.onMessage(v),leave:()=>{u.leave()},serverTime:()=>u.serverTime()}},h=(d,u)=>new Promise((v,x)=>{let w,N=!1,_=()=>{w.removeEventListener("message",W),w.removeEventListener("close",U),w.removeEventListener("error",F),u.signal?.removeEventListener("abort",B)},j=()=>{try{w.close(1e3)}catch{}},z=(A,M)=>{N||(N=!0,_(),M&&j(),x(A))};function B(){z(p("cancelled","The matchmaking search was cancelled."),!0)}function U(){z($(),!1)}function F(){z($(),!0)}function W(A){let M=null;try{M=typeof A.data=="string"?Q(JSON.parse(A.data)):null}catch{}if(M===null||typeof M.t!="string"){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}if(M.t==="waiting"){if(!Number.isInteger(M.players)||!Number.isInteger(M.min)||!Number.isInteger(M.max)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}try{u.onWaiting?.({players:M.players,min:M.min,max:M.max})}catch{}return}if(M.t==="matched"){if(!tt(M)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}N=!0,_(),j(),v(M);return}if(M.t==="no_match"){z(p("no_match","No match was found before the timeout."),!0);return}if(M.t==="error"){z(p(typeof M.code=="string"?M.code:"internal_error",typeof M.message=="string"?M.message:"The matchmaking service could not complete the search."),!0);return}M.t!=="pong"&&z(p("internal_error","The matchmaking service sent an invalid message."),!0)}try{w=n.apriSocket(d)}catch{x($());return}w.addEventListener("message",W),w.addEventListener("close",U),w.addEventListener("error",F),u.signal?.addEventListener("abort",B,{once:!0}),u.signal?.aborted===!0&&B()});return{replay:!1,invited:e,reload(){n.reload?.(t)},onError(d){return i.add(d),()=>{i.delete(d)}},async create(d){return c(await r.create(d.mode))},async join(d){let u=d??e;if(u==null||u.length===0)throw p("invalid_request","A room invitation code is required.");return c(await r.joinCode(u))},async watch(d){if(typeof d!="string"||d.length===0)throw p("invalid_request","A room invitation code is required.");return m(await r.watchCode(d))},async match(d){let u=()=>d.signal?.aborted===!0;if(u())throw p("cancelled","The matchmaking search was cancelled.");let v=await r.match(d);if(u())throw p("cancelled","The matchmaking search was cancelled.");return c(await h(v.url,d))}}}var K=()=>p("replay_invalid","The replay is incomplete or invalid.");function q(n,...e){for(let t of n)try{t(...e)}catch{}}function le(n,e){return n.add(e),()=>{n.delete(e)}}var li={now:()=>performance.now(),setInterval:(n,e)=>globalThis.setInterval(n,e),clearInterval:n=>globalThis.clearInterval(n)},ze=class{constructor(e,t,i=li){this.index=e;this.events=t;this.clock=i;this.replay=!0;this.role="spectator";this.delayMs=0;this.code="";this.latency=null;this.countdownAt=null;this.cursor=1;this.position=0;this.paused=!0;this.speedValue=1;this.timer=null;this.last=0;this.lastEmitted=-1/0;this.disconnected=!1;this.checkpoints=[];this.states=new Set;this.playersListeners=new Set;this.statuses=new Set;this.metadataListeners=new Set;this.connections=new Set;this.playbackListeners=new Set;this.step=()=>{let e=this.clock.now();this.position=Math.min(this.index.durationMs,this.position+Math.max(0,e-this.last)*this.speedValue),this.last=e,this.advance(!0),this.position>=this.index.durationMs&&this.pause(),e-this.lastEmitted>=100&&(this.lastEmitted=e,q(this.playbackListeners,this.playback))};if(t[0]?.message.t!=="start"||t[0].at!==0||t[0].message.room.id!==e.roomId)throw K();let r=t[0].message;this.picture=structuredClone({room:r.room,players:r.players,state:r.state,result:null}),this.checkpoints.push({cursor:1,at:0,picture:structuredClone(this.picture)});let s=Math.max(1,Math.ceil(t.length/32)),o=0;for(let a=1;a<t.length;a++){let c=t[a];if(!Number.isFinite(c.at)||c.at<o||c.at>e.durationMs||c.message.t==="start")throw K();this.apply(c.message,!1),a%s===0&&this.checkpoints.push({cursor:a+1,at:c.at,picture:structuredClone(this.picture)}),o=c.at}this.seek(0)}get mode(){return this.picture.room.mode}get connection(){return this.disconnected?"disconnected":"connected"}get metadata(){return{host:this.host,mode:this.mode,countdownAt:null,configuration:null,rematch:null,connection:this.connection,closedCode:null}}get state(){return structuredClone(this.picture.state)}get tick(){return this.picture.room.tick}get tickRate(){return this.picture.room.tickRate}get seed(){return this.picture.room.seed}get status(){return this.picture.room.status}get players(){return structuredClone(this.picture.players)}get host(){return this.picture.room.host}get result(){return structuredClone(this.picture.result)}get playback(){return{positionMs:this.position,durationMs:this.index.durationMs,speed:this.speedValue,paused:this.paused,truncated:this.index.truncated}}serverTime(){return this.index.startedAt+this.position}onState(e){return le(this.states,e)}onStatus(e){return le(this.statuses,e)}onPlayers(e){return le(this.playersListeners,e)}onMetadata(e){return le(this.metadataListeners,e)}onConnection(e){return le(this.connections,e)}onMessage(e){return()=>{}}onPlayback(e){return le(this.playbackListeners,e)}apply(e,t){let i=this.picture;switch(e.t){case"start":throw K();case"snapshot":i.state=structuredClone(e.state);break;case"state":{if(i.room.tick!==e.base)throw K();let r=_e(i.state,e.patch);if(!r.ok)throw K();i.state=r.state;break}case"players":i.players=structuredClone(e.players),e.host!==void 0&&(i.room.host=e.host),t&&q(this.playersListeners,this.players);return;case"status":i.room.status=e.status,i.result=structuredClone(e.result),e.host!==void 0&&(i.room.host=e.host),t&&q(this.statuses,this.status,this.result,e.at);return;default:throw K()}i.room.tick=e.tick,i.room.serverTime=e.serverTime,i.room.tickRate=e.tickRate??i.room.tickRate,t&&q(this.states,this.state,this.tick,e.serverTime)}seek(e){if(!Number.isFinite(e)||this.disconnected)return;this.position=Math.max(0,Math.min(e,this.index.durationMs));let t=[...this.checkpoints].reverse().find(i=>i.at<=this.position);this.picture=structuredClone(t.picture),this.cursor=t.cursor,this.advance(!1),this.last=this.clock.now(),q(this.playersListeners,this.players),q(this.statuses,this.status,this.result,this.serverTime()),q(this.states,this.state,this.tick,this.serverTime()),q(this.metadataListeners,this.metadata),this.position>=this.index.durationMs&&this.pause(),q(this.playbackListeners,this.playback)}advance(e){for(;this.events[this.cursor]&&this.events[this.cursor].at<=this.position;)this.apply(this.events[this.cursor++].message,e)}play(){!this.paused||this.disconnected||this.index.durationMs===0||(this.position>=this.index.durationMs&&this.seek(0),this.paused=!1,this.last=this.clock.now(),this.timer=this.clock.setInterval(this.step,16),q(this.playbackListeners,this.playback))}pause(){this.timer!==null&&this.clock.clearInterval(this.timer),this.timer=null,this.paused=!0,q(this.playbackListeners,this.playback)}speed(e){if(![.5,1,2,4].includes(e))throw K();this.paused||this.step(),this.speedValue=e,q(this.playbackListeners,this.playback)}disconnect(){this.disconnected||(this.pause(),this.disconnected=!0,q(this.connections,this.connection),q(this.metadataListeners,this.metadata))}leave(){this.disconnect()}};async function rt(n,e){let t=await n(e,{credentials:"omit",cache:"no-store"});if(!t.ok)throw p("replay_unavailable","This replay is no longer available.");let i=await t.json();if(i.format!==1||!de.test(i.id)||!Number.isInteger(i.chunks)||i.chunks<1||i.chunks>Math.ceil(10485760/524288)+1||!Number.isInteger(i.bytes)||i.bytes>10485760||i.bytes<1||!Number.isFinite(i.startedAt)||!Number.isFinite(i.durationMs)||i.durationMs<0||i.durationMs>18e5)throw K();let r=[],s=0;for(let o=0;o<i.chunks;o++){let a=await n(`${e}?chunk=${o}`,{credentials:"omit",cache:"no-store"});if(!a.ok)throw K();let c=await a.text();if(s+=new TextEncoder().encode(c).byteLength,s>i.bytes||!c.endsWith(`\n`))throw K();for(let m of c.trimEnd().split(`\n`))r.push(JSON.parse(m))}if(s!==i.bytes)throw K();try{return new ze(i,r)}catch{throw K()}}var ci=["en","it","es","fr","de","pt","ja"];function ot(n){let e=G(n);return e&&ci.includes(e.split("-")[0])?e:"en"}function st(n,e,t="/"){let i,r=t.match(/^\\/rt\\/[^/]+\\/[1-9][0-9]*\\//)?.[0]??"/";return()=>i??(i=(async()=>{let s={};try{let o=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(o.ok){let a=await o.json();Ge(a)&&(s=a)}}catch{}return(o,a={})=>Object.hasOwn(s,o)?s[o].replace(/\\{([^{}]+)\\}/g,(m,h)=>Object.hasOwn(a,h)?String(a[h]):m):o})())}var at="caisual-session-v1";function lt(n){let e=D(n);return!e||typeof e.code!="string"||!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(e.code)||!(e.mode===void 0||e.mode===null||typeof e.mode=="string")?null:{version:1,code:e.code,mode:typeof e.mode=="string"?e.mode:null,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}}function ct(n,e){let t=null,i=!1,r=Promise.resolve(),s=async()=>{let a={version:1,imported:!0,resume:t};return r=r.catch(()=>{}).then(async()=>{try{await n.set(at,a),i=!1}catch(c){throw i=!0,c}finally{e()}}),r},o=(async()=>{try{let a=await n.get(at),c=D(a);if(c?.version===1&&c.imported===!0)t=lt(c.resume);else{let m=await n.get("resume");t=lt(m),(a!==null||m!==null)&&await s()}}catch{i=!0}e()})();return{loaded:o,get value(){return t===null?null:{...t}},get error(){return i},async set(a){await o,t=a,e(),await s()}}}function X(n,e){for(let t of n)try{t(e)}catch{}}function ut(n,e=null,t=n.connected,i=null){let r=i!==null||e?.manifest.overlay?.version===1,s=e?.manifest,o={kind:"idle"},a=!1,c=0,m=0,h=null,d=null,u=null,v=null,x=[],w=!1,N="",_={inputBlocked:r,reservedRects:[],safeArea:{top:0,right:0,bottom:0,left:0}},j=new Set,z=new Set,B=new Set,U=new Set,F=new Set,W=new Set,A=null,M=()=>({local:i===null,rooms:i===null&&t,overlay:r,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function ue(){if(o.kind!=="room"||!s||s.voice==="none")return null;let l=o.room,y=l.voice;return!y||y.mode==="none"||l.players.find(R=>R.id===l.you)?.role==="spectator"?null:{mode:y.mode,state:y.state,mic:y.mic,muted:y.muted,speaking:y.speaking,peers:y.peers.map(({id:R,mic:C,muted:k,speaking:ae,volume:oe})=>({id:R,mic:C,muted:k,speaking:ae,volume:oe}))}}function ee(){let l=o.kind==="room"||o.kind==="watch"?o.room:null,y=l?.metadata.configuration,R=l?Ye(l.result,l.players.map(k=>k.id)):null,C=s&&l&&(l.mode===null||s.modes.some(k=>k.id===l.mode))?Ue(s,l.mode):{players:{min:1,max:1},lobby:!1};return{kind:h??(o.kind==="idle"?a?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:h?d:o.kind==="local"?o.mode:l?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:a,capabilities:M(),room:l?{...l===i?{replay:i.playback}:{},...l.metadata.replayId?{replayId:l.metadata.replayId}:{},...l.metadata.rematch?.keepSetup||l.metadata.rematch?.autoStart?{rematch:l.metadata.rematch}:{},code:l.code,mode:l.mode,status:l.status,host:l.host,you:o.kind==="room"?o.room.you:null,players:l.players.map(k=>({id:k.id,name:k.name,guest:k.guest,role:k.role,team:k.team,ready:k.ready,connected:k.connected})),...R?{result:R}:{},countdownAt:l.countdownAt,connection:l.connection,closedCode:l.metadata.closedCode,limits:{...y?.players??C.players},lobby:y?.lobby??C.lobby,persistent:y?.persistent??s?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:y?.requestRole??!1}:null,voice:h?null:ue(),waiting:u?{...u}:null,resume:A?.value??null,resumeError:A?.error??!1}}function I(){if(w)return;let l=ee(),y=JSON.stringify(l);y!==N&&(N=y,X(B,l))}function te(){X(j,{...o}),I()}function Y(){if(o.kind!=="room")throw p("no_room","There is no active player room.");return o.room}function re(){let l=Y();if(l.players.find(y=>y.id===l.you)?.role==="spectator")throw p("spectator","Spectators cannot use voice controls.");if(!s||s.voice==="none"||l.voice.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");return l.voice}function H(){c++,v?.abort(),v=null,h=null,u=null,I()}function g(l){x.splice(0).forEach(y=>y()),(o.kind==="room"||o.kind==="watch")&&(l?o.room.disconnect():o.room.leave()),o={kind:"idle"},te()}async function f(l){A?.value?.code===l&&await A.set(null).catch(()=>{})}async function L(l,y,R){if(R!==c||w)throw l.leave(),p("cancelled","The operation was cancelled.");g(!1),o=y?{kind:"watch",room:l,id:String(++m)}:{kind:"room",room:l,id:String(++m)};let C=l;if(x=[C.onPlayers(I),C.onMetadata(()=>{C.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===C?(x.splice(0).forEach(k=>k()),!y&&C.metadata.closedCode===1e3&&f(C.code),o={kind:"idle"},te()):I()}),C.onStatus(()=>{I(),!y&&C.connection==="ended"&&f(C.code)})],l===i&&x.push(i.onPlayback(I)),!y){let k=l,ae=o.id;k.voice&&x.push(k.voice.onState(I),k.voice.onPeers(I)),x.push(k.onError(oe=>X(F,{sessionId:ae,error:{...oe}}))),x.push(k.onScoreQueued(oe=>X(W,{...oe})));for(let oe of k.queuedScores)X(W,{...oe})}return h=null,u=null,te(),!y&&A&&C.connection!=="ended"&&await A.set({version:1,code:C.code,mode:C.mode,updatedAt:n.time.now()}).catch(()=>{}),l}async function S(l,y,R,C=!1){H();let k=c;v=new AbortController,h=l,d=y,I();try{let ae=await R(v.signal,k);if(await L(ae,C,k),k!==c||w)throw p("cancelled","The operation was cancelled.");return ae}finally{k===c&&(h=null,u=null,v=null,I())}}let b=n.room,O=b.onError(l=>{!r||w||(l.code==="version_mismatch"?b.reload():l.code==="version_outdated"&&X(F,{sessionId:o.kind==="idle"?null:o.id,error:l}))}),T=i||!r?b:{invited:b.invited,reload:()=>b.reload(),onError:l=>b.onError(l),create(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot create rooms.")):S("attaching",l.mode,()=>b.create(l))},join(l){return S("attaching",null,()=>b.join(l))},watch(l){return S("attaching",null,()=>b.watch(l),!0)},match(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot use matchmaking.")):S("matching",l.mode,(y,R)=>{let C=()=>{c===R&&H()};return l.signal?.addEventListener("abort",C,{once:!0}),l.signal?.aborted&&C(),b.match({...l,signal:y,onWaiting(k){R===c&&(u={...k},I(),l.onWaiting?.(k))}}).finally(()=>l.signal?.removeEventListener("abort",C))})}};return r&&!i&&(A=ct(n.save,I)),i&&(a=!0,L(i,!0,c)),{session:{get current(){return{...o}},get capabilities(){return M()},onChange(l){return j.add(l),X(new Set([l]),{...o}),()=>{j.delete(l)}},ready(){w||a||(a=!0,I())},finish(){if(o.kind==="room"||o.kind==="watch")throw p("not_local","Only a local session can be finished by the client.");o.kind==="local"&&(o={...o,status:"ended"},te())}},overlay:{open(l){if(!["home","room","invite","friends","voice","boards"].includes(l))throw p("invalid_request","Unknown overlay panel.");r&&X(U,l)},onChange(l){return z.add(l),X(new Set([l]),structuredClone(_)),()=>{z.delete(l)}}},rooms:T,snapshot:ee,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(l){return B.add(l),l(ee()),()=>{B.delete(l)}},onOpen(l){return U.add(l),()=>{U.delete(l)}},onError(l){return F.add(l),()=>{F.delete(l)}},onScore(l){return W.add(l),()=>{W.delete(l)}},async execute(l){if(!r)throw p("overlay_disabled","This game uses its own room flow.");if(l.op==="overlay.view"){if(!Oe(l.args))throw p("invalid_request","The overlay geometry is invalid.");if(_={...structuredClone(l.args),safeArea:{top:0,right:0,bottom:0,left:0,...l.args.safeArea}},typeof document<"u")for(let[y,R]of Object.entries(_.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${y}`,`${R}px`);X(z,structuredClone(_));return}if(l.sessionId!==void 0&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(l.op.startsWith("replay.")&&(!i||o.kind!=="watch"||o.room!==i||l.sessionId!==o.id))throw p("session_replaced","The replay is no longer active.");if(i&&!l.op.startsWith("replay.")&&!["session.leave","session.disconnect"].includes(l.op))throw p("replay_readonly","Replays are read only.");if(l.op.startsWith("voice.")&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(!a)throw p("game_not_ready","The game is still loading.");switch(l.op){case"replay.play":i.play();return;case"replay.pause":i.pause();return;case"replay.seek":i.seek(l.args.positionMs);return;case"replay.speed":i.speed(l.args.speed);return;case"local.start":{if(!s||!ve(s,l.args.mode))throw p("invalid_mode","This is not a local mode.");H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1),o={kind:"local",id:String(++m),mode:l.args.mode,status:"playing"},te();return}case"room.create":await T.create(l.args);return;case"room.join":await T.join(l.args.code);return;case"room.watch":await T.watch(l.args.code);return;case"room.match":{let y=s?.modes.find(C=>C.id===l.args.mode),R=l.args.key??y?.matchmaking?.defaults;if(!R)throw p("invalid_request","Matchmaking needs a complete key.");await T.match({mode:l.args.mode,key:R});return}case"voice.join":{let y=Y();if(await re().join(),o.kind!=="room"||o.room!==y)throw p("session_replaced","The active session changed.");I();return}case"voice.mute":re().mute(l.args.muted),I();return;case"voice.leave":re().leave(),I();return;case"voice.setVolume":{let y=re();if(!y.peers.some(R=>R.id===l.args.playerId))throw p("voice_peer_missing","This voice participant is no longer available.");y.setVolume(l.args.playerId,l.args.volume),I();return}case"room.ready":Y().ready(l.args.ready);return;case"room.role":Y().setRole(l.args.role);return;case"room.requestRole":await Y().requestRole(l.args.role);return;case"room.team":Y().setTeam(l.args.team);return;case"room.start":Y().start();return;case"room.restart":Y().restart();return;case"session.cancel":H();return;case"session.resume":{await S("attaching",null,async y=>{if(await A?.loaded,y.aborted)throw p("cancelled","The operation was cancelled.");if(!A?.value)throw p("no_resume","There is no saved room.");return b.join(A.value.code)});return}case"session.disconnect":{H();let y=c;if(o.kind==="room"&&o.room.connection!=="ended"&&A&&await A.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!0);return}case"session.leave":{H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1);return}}},dispose(){O(),H(),g(!0),w=!0,j.clear(),z.clear(),B.clear(),U.clear(),W.clear(),F.clear()}}}function dt(n,e,t){let i=!0,r=!1,s=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),o=a=>{let c=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||c?.closest?.(\'input,textarea,select,[contenteditable="true"]\')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",o,!0),()=>{s(),n.removeEventListener("keydown",o,!0)}}function mt(n,e,t){let i=!1,r=0,s=0,o=0,a=new Map,c=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[dt(window,t.overlay,()=>c({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>c({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>c({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:u})=>c({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:u})),t.onScore(d=>c({type:"caisual:overlay-score",v:1,epoch:e.epoch,score:d}))],h=d=>{let u=D(d.data);if(u?.type!=="caisual:overlay"||u.epoch!==e.epoch||i)return;let v={type:"caisual:overlay-response",v:1,epoch:e.epoch,requestId:typeof u.requestId=="string"?u.requestId:""};if(!Ke(u)){c({...v,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let x=JSON.stringify([u.op,u.args,u.sessionId]),w=a.get(u.requestId);if(w){w.fingerprint!==x?c({...v,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):w.response.then(c);return}if(Number(u.requestId)<=s||o>=32){c({...v,ok:!1,error:{code:"stale_request",message:"The request is stale or too many requests are pending."}});return}s=Number(u.requestId),o++;let N=Promise.resolve().then(()=>t.execute(u)).then(()=>({...v,ok:!0}),_=>({...v,ok:!1,error:{code:typeof D(_)?.code=="string"?D(_).code:"internal_error",message:_ instanceof Error?_.message:"The operation could not be completed."}}));a.set(u.requestId,{fingerprint:x,response:N}),N.then(_=>{if(o--,c(_),a.size>64)for(let j of a.keys())Number(j)<s-64&&a.delete(j)})};return n.addEventListener("message",h),n.start(),()=>{i=!0,n.removeEventListener("message",h),m.forEach(d=>d()),t.dispose(),a.clear()}}function pt(n,e,t){let i=be(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,s)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:s}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(s){if(pe(s)==="not_found")return null;throw s}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves},async boardSubmit(r,s,o){let a=await i("/scores","POST",{board:r,score:s,daily:o});return{accepted:!0,best:a.best,rank:a.rank,day:a.day,verified:a.verified}},async boardTop(r,s){if(s.day!==void 0&&(!me(s.day)||s.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");let o=new URLSearchParams;s.day!==void 0&&o.set("day",s.day),s.daily&&o.set("daily","1"),s.limit!==void 0&&o.set("limit",String(s.limit)),s.guests&&o.set("guests","1");let a=o.size===0?"":`?${o.toString()}`,{day:c,entries:m,me:h}=await i(`/scores/${encodeURIComponent(r)}${a}`,"GET");return{day:c,entries:m,me:h}}}}function ce(n){return(Math.floor(n/864e5)+1)*864e5}function Re(n,e,t){let i=new Set,r={...n},s,o=!1;function a(){!i.size||s!==void 0||o||(s=setTimeout(c,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),s.unref?.())}async function c(){s=void 0,o=!0;try{let m=await t(),h=m.day!==r.day;if(r={...m},h)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{o=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:ft(n.seed),rng:()=>ft(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&s!==void 0&&(clearTimeout(s),s=void 0)}}}}function Ve(n){return new Date(n).toISOString().slice(0,10)}async function Le(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function ft(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function ke(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function ht(n,e){return ke(n)?.type===e}function ui(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function gt(n,e,t=3e3){return new Promise(i=>{let r=!1,s=globalThis.crypto.randomUUID(),o=h=>{r||(r=!0,n.removeEventListener("message",c),n.clearTimeout(m),i(h))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:s,overlayVersion:1},e)},c=h=>{if(h.origin!==e||h.source!==n.parent)return;if(ht(h.data,"caisual:ready?")){a();return}if(!ht(h.data,"caisual:hello"))return;let d=ke(h.data),u=h.ports[0];if(typeof d?.ticket!="string"||!Ae(d.n)||u===void 0)return;u.start();let v=He(d.overlay),x=w=>Array.isArray(w)?w.map(G).filter(N=>N!==null):void 0;o({...v?{overlay:v}:{},...G(d.language)?{language:G(d.language)}:{},uiLanguage:G(d.uiLanguage)??void 0,languagePreferences:x(d.languagePreferences),gameLanguages:x(d.gameLanguages),...typeof d.replay=="string"&&de.test(d.replay)?{replay:d.replay}:{},ticket:d.ticket,n:d.n,live:ui(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:u})};n.addEventListener("message",c);let m=n.setTimeout(()=>o(null),t);a()})}function di(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=ke(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function mi(n,e,t,i){return new Promise((r,s)=>{let o=!1,a=h=>{o||(o=!0,n.removeEventListener("message",c),e.clearTimeout(m),h===null?s(new Error("Ticket refresh timed out.")):r(h))},c=h=>{let d=ke(h.data),u=d?.aud===void 0?"portal":d.aud;d?.type==="caisual:ticket"&&u===i&&typeof d.ticket=="string"&&a(d.ticket)};n.addEventListener("message",c);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function $e(n,e,t,i,r=3e3,s="portal"){let o=n,a=null,c=()=>{if(a!==null)return a;let h=mi(e,t,r,s).then(d=>(o=d,d)).finally(()=>{a===h&&(a=null)});return a=h,h};return{async ottieni(){if(o===null)return c();let m=di(o);return m!==null&&m-i()<3e4?c():o},rinnova:c}}var se="caisual:save:",pi=/^[a-z0-9][a-z0-9_-]{0,31}$/;function De(n){if(!pi.test(n))throw p("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function yt(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function vt(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(se)&&e.push(i.slice(se.length))}return e}function fi(n,e){let t=()=>{if(n===null)throw $();return n};return{async set(i,r){De(i);let s=t(),o=JSON.stringify({value:r}),a=new TextEncoder().encode(o).byteLength;if(a>262144)throw p("payload_too_large","The save is larger than 262144 bytes.");if(s.getItem(se+i)===null&&vt(s).length>=64)throw p("save_limit","A game can store at most 64 save keys.");let c={value:r,bytes:a,updatedAt:e()};return s.setItem(se+i,JSON.stringify(c)),{key:i,bytes:a,updatedAt:c.updatedAt}},async get(i){return De(i),yt(t().getItem(se+i))?.value??null},async remove(i){De(i),t().removeItem(se+i)},async list(){let i=t();return vt(i).flatMap(r=>{let s=yt(i.getItem(se+r));return s===null?[]:[{key:r,bytes:s.bytes,updatedAt:s.updatedAt}]}).sort((r,s)=>r.key.localeCompare(s.key))}}}async function xe(n,e=null){let t=n.ora(),i=Ve(t),r=await Le(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:Re({day:i,seed:r,expiresAt:ce(t)},n.ora,async()=>{let s=n.ora(),o=Ve(s);return{day:o,seed:await Le(n.hostname,o,n.subtle),expiresAt:ce(s)}}),time:{now:n.ora},save:fi(n.archivio,n.ora),board:{async submit(){return{accepted:!1,reason:"offline",verified:!1}},async top(s,o={}){if(o.day!==void 0&&(!me(o.day)||o.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");return{day:o.day??(o.daily?i:null),entries:[],me:null}}},room:he(e)}}function hi(n){let e=n?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function gi(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function yi(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:gi(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>We()}}async function vi(n){let e=hi(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return bt(n);let i=await gt(n.finestra,e,n.timeoutHandshake);if(i===null)return bt(n);if(i.replay){let u=i.overlay?.configuration.manifest.id;if(!u)throw new Error("The replay game is missing.");let v=await rt(n.fetcher,`${e}/api/replays/${encodeURIComponent(u)}/${i.replay}`),x=await xe(n),w=he();return x.connected=!0,x.room=Object.assign(v,{invited:null,reload:()=>w.reload(),onError:w.onError,create:w.create,join:w.join,match:w.match,watch:async()=>v}),Me(x,i,n,v)}let r=$e(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),s=pt(e,n.fetcher,r),o=n.ora(),a;try{a=await s.me()}catch{let u=await xe(n,i.invite);return Me(u,i,n)}let c=n.ora(),m=a.serverTime-(o+c)/2,h=i.live===null?he(i.invite):it({appOrigin:e,n:i.n,reload:u=>i.porta.postMessage({type:"caisual:reload",target:u}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:$e(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(u){if(n.apriSocket!==void 0)return n.apriSocket(u);if(typeof WebSocket>"u")throw $();return new WebSocket(u)},ora:n.ora,setTimeout:(u,v)=>globalThis.setTimeout(u,v),clearTimeout:u=>globalThis.clearTimeout(u),setInterval:(u,v)=>globalThis.setInterval(u,v),clearInterval:u=>globalThis.clearInterval(u),voce:n.voce,segnalaStanza(u){try{i.porta.postMessage({type:"caisual:room",room:u})}catch{}}},i.invite),d={connected:!0,player:a.player,daily:Re({day:a.day,seed:a.seed,expiresAt:a.expiresAt??ce(a.serverTime)},()=>n.ora()+m,async()=>{let u=await s.me();return{day:u.day,seed:u.seed,expiresAt:u.expiresAt??ce(u.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(u,v)=>s.saveSet(u,v),get:u=>s.saveGet(u),remove:u=>s.saveRemove(u),list:()=>s.saveList()},board:{async submit(u,v,x={}){try{return await s.boardSubmit(u,v,x.daily===!0)}catch(w){if(typeof w=="object"&&w!==null&&"code"in w&&w.code==="offline")return{accepted:!1,reason:"offline",verified:!1};throw w}},top:(u,v={})=>s.boardTop(u,v)},room:h};return Me(d,i,n)}function Me(n,e,t,i=null){let r=ut(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null,i);if(e?.overlay){let c=mt(e.porta,e.overlay,r);r.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",c,{once:!0})}let s=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=je(s,e?.gameLanguages??(e?.overlay?Ce(e.overlay.configuration.manifest):void 0)),a=ot(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:a},text:st(t?.fetcher??globalThis.fetch,o,t?.pathname),room:r.rooms,session:r.session,overlay:r.overlay}}async function bt(n){return Me(await xe(n),void 0,n)}function wt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function bi(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>wt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(wt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function St(n=yi()){let e=null;return{connect(){return e??(e=Promise.all([vi(n),bi(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Rt=St();globalThis.caisual=Rt;var xr=Rt;export{Rt as caisual,xr as default};\n');
5271
+ response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.20.0\nvar kt=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],xt=new Set(kt),Mt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function ge(n){return n.length>=3&&n.length<=32&&Mt.test(n)||Ct.test(n)}function Ne(n){return xt.has(n)}function G(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function Ce(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function Pt(n,e="en"){let t=[],i=G(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(G(e)??e),[...new Set(t)]}function je(n,e=[]){let t=e.map(G).filter(r=>r!==null),i=n.map(G).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let s of Pt(r,r))if(t.includes(s))return s;return t[0]}function Ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function Ue(n,e){let t=e===null?void 0:n.modes.find(i=>i.id===e);if(e!==null&&t===void 0)throw new Error("The selected game mode does not exist.");return{players:{...t?.players??n.players},lobby:t?.lobby??n.lobby}}function ve(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var P=24;var Tt=3e3,Je=32,At=new Set(["overlay","manifest","id","name","description","cover","card","icon","screenshots","tags","languages","language","platform","orientation","input","visibility","network","isolated","requires","players","lobby","persistent","replays","spectators","boards","roles","teams","voice","modes"]),It=new Set(["keyboard","mouse","touch","gamepad"]),Ot=new Set(["desktop","mobile","both"]),Et=new Set(["landscape","portrait"]),_t=new Set(["public","unlisted"]),zt=new Set(["none","room","team","proximity"]),Vt=new Set(["light","medium","heavy"]),Lt=/^[a-z0-9-]+$/,qe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,$t=/^[a-z0-9][a-z0-9-]{0,31}$/,Dt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Be(n){if(n===""||n.startsWith("/")||n.includes("\\\\")||n.includes("\\0")||n.includes("?")||n.includes("#"))return!1;let e=n.split("/");if(e.some(t=>t===""||t==="."||t===".."))return!1;try{return!e.map(i=>decodeURIComponent(i)).some(i=>i===""||i==="."||i===".."||i.includes("/"))}catch{return!1}}function Nt(n){return n.length===0||n.length>253||n.includes("://")||/[/:?#@]/.test(n)?!1:n.split(".").every(t=>t.length>=1&&t.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(t))}function V(n,e,t){return typeof n=="number"&&Number.isInteger(n)&&n>=e&&n<=t}function Pe(n,e,t,i){let r=n[e];return r===void 0?t:typeof r!="string"?(i.push(`${e}: must be a string.`),t):r}function ye(n,e,t,i,r){if(n[e]===void 0)return;let s=(h,d)=>{if(typeof h!="string"||h.trim().length===0||h.trim().length>t||/[\\r\\n\\u0000-\\u001f]/.test(h)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return h.trim()},o=n[e],a=i?`${i}.${e}`:e;if(typeof o=="string")return s(o,a);let c=J(o);if(!c||Object.keys(c).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[h,d]of Object.entries(c)){let u=G(h);if(!u){r.push(`${a}.${h}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,u)&&r.push(`${a}.${h}: duplicate language.`);let v=s(d,`${a}.${h}`);v!==void 0&&(m[u]=v)}return m}function Te(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let g of Object.keys(t))At.has(g)||e.push(`${g}: unknown field.`);t.manifest===void 0?e.push("manifest: is required and must be 1."):t.manifest!==1&&e.push("manifest: must be exactly 1.");let i=Pe(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(ge(i)?Ne(i)&&e.push("id: this slug is reserved."):e.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters."));let r=Pe(t,"name","",e);t.name===void 0?e.push("name: is required."):typeof t.name=="string"&&(r.trim()===""||r.length>60)&&e.push("name: must contain 1-60 characters.");let s=t.description===""?"":ye(t,"description",500,"",e)??"",o={cover:"",card:"",icon:""},a=new Set;for(let g of["cover","card","icon"]){let f=t[g];if(f==null)e.push(`${g}: is required.`);else if(typeof f!="string"||!Be(f))e.push(`${g}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\\.(png|jpe?g|webp)$/i.test(f)||e.push(`${g}: must be a PNG, JPEG or WebP file.`);let L=decodeURIComponent(f);a.has(L)&&e.push(`${g}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(L),o[g]=f}}let{cover:c,card:m,icon:h}=o,d=[];if(t.screenshots!==void 0)if(!Array.isArray(t.screenshots))e.push("screenshots: must be an array of relative file paths.");else{t.screenshots.length>8&&e.push("screenshots: must contain at most 8 paths.");for(let[g,f]of t.screenshots.entries())typeof f!="string"||!Be(f)?e.push(`screenshots[${g}]: must be a relative file path without query, fragment, or parent segments.`):d.push(f)}let u=[];if(t.tags!==void 0)if(!Array.isArray(t.tags))e.push("tags: must be an array.");else{t.tags.length>10&&e.push("tags: must contain at most 10 tags.");for(let[g,f]of t.tags.entries())typeof f!="string"||f.length>24||!Lt.test(f)?e.push(`tags[${g}]: must be 1-24 lowercase letters, digits, or hyphens.`):u.push(f)}let v=Pe(t,"language","en",e);/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(v)||e.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");let x=[];if(!Array.isArray(t.languages)||t.languages.length===0)e.push("languages: must be a non-empty array of BCP 47 language tags.");else for(let[g,f]of t.languages.entries()){let L=G(f);L?x.includes(L)?e.push(`languages[${g}]: duplicate language ${L}.`):x.push(L):e.push(`languages[${g}]: must be a BCP 47 language tag.`)}x.includes("en")||e.push("languages: English is always required alongside the game\'s own languages.");let w=x[0]??v;if(typeof s=="object")for(let g of Object.keys(s))x.includes(g)||e.push(`description.${g}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&v.toLowerCase()!==w.toLowerCase()&&e.push("language: must match the first entry in languages when both are present.");let N="both";t.platform===void 0?e.push("platform: is required."):typeof t.platform!="string"||!Ot.has(t.platform)?e.push("platform: must be desktop, mobile, or both."):N=t.platform;let _="landscape";t.orientation!==void 0&&(typeof t.orientation!="string"||!Et.has(t.orientation)?e.push("orientation: must be landscape or portrait."):_=t.orientation);let j=[];if(t.input!==void 0)if(!Array.isArray(t.input))e.push("input: must be an array.");else for(let[g,f]of t.input.entries())typeof f!="string"||!It.has(f)?e.push(`input[${g}]: must be keyboard, mouse, touch, or gamepad.`):j.includes(f)?e.push(`input[${g}]: duplicate value ${f}.`):j.push(f);let z="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!_t.has(t.visibility)?e.push("visibility: must be public or unlisted."):z=t.visibility);let B=[];if(t.network!==void 0)if(!Array.isArray(t.network))e.push("network: must be an array of host names.");else for(let[g,f]of t.network.entries())typeof f!="string"||!Nt(f)?e.push(`network[${g}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(f)?e.push(`network[${g}]: duplicate host ${f}.`):B.push(f);t.isolated!==void 0&&typeof t.isolated!="boolean"&&e.push("isolated: must be a boolean.");let U={webgl2:!1,webgpu:!1,wasm:!1,threads:!1,memoryMb:null,performance:"light"};if(t.requires!==void 0){let g=J(t.requires);if(g===null)e.push("requires: must be an object.");else{for(let f of Object.keys(g))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(f)||e.push(`requires.${f}: unknown field.`);for(let f of["webgl2","webgpu","wasm","threads"])g[f]!==void 0&&(typeof g[f]!="boolean"?e.push(`requires.${f}: must be a boolean.`):U[f]=g[f]);g.memoryMb!==void 0&&(g.memoryMb!==null&&(!V(g.memoryMb,512,32768)||g.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):U.memoryMb=g.memoryMb),g.performance!==void 0&&(typeof g.performance!="string"||!Vt.has(g.performance)?e.push("requires.performance: must be light, medium, or heavy."):U.performance=g.performance)}}let F={min:1,max:1};if(t.players!==void 0){let g=J(t.players);if(g===null)e.push("players: must be an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`players.${f}: unknown field.`);V(g.min,1,P)||e.push(`players.min: must be an integer from 1 to ${P}.`),V(g.max,1,P)||e.push(`players.max: must be an integer from 1 to ${P} in manifest version 1.`),V(g.min,1,P)&&V(g.max,1,P)&&(g.min>g.max?e.push("players.max: must be greater than or equal to players.min."):F={min:g.min,max:g.max})}}let W=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):W=t.lobby);let A=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):A=t.persistent);let M=t.replays===!0;t.replays!==void 0&&typeof t.replays!="boolean"&&e.push("replays: must be a boolean.");let ue={delayMs:Tt};if(t.spectators===!1||t.spectators===null)ue=null;else if(t.spectators!==void 0&&t.spectators!==!0){let g=J(t.spectators);if(g===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let f of Object.keys(g))f!=="delayMs"&&e.push(`spectators.${f}: unknown field.`);V(g.delayMs,0,3e4)?ue={delayMs:g.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let ee=null;if(t.overlay!==void 0&&t.overlay!==null){let g=J(t.overlay);if(g===null)e.push("overlay: must be an object or null.");else{for(let f of Object.keys(g))["version","accent"].includes(f)||e.push(`overlay.${f}: unknown field.`);g.version!==1&&e.push("overlay.version: must be exactly 1."),g.accent!==void 0&&(typeof g.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(g.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),ee={version:1,...typeof g.accent=="string"?{accent:g.accent}:{}}}}let I={};if(t.boards!==void 0){let g=J(t.boards);if(g===null)e.push("boards: must be an object of board ids.");else{Object.keys(g).length>Je&&e.push(`boards: at most ${Je} boards.`);for(let[f,L]of Object.entries(g)){let S=!0;Dt.test(f)||(e.push(`boards.${f}: invalid board id.`),S=!1);let b=J(L);if(b===null){e.push(`boards.${f}.source: must be "client" or "server".`);continue}for(let E of Object.keys(b))["source","label","periods","day"].includes(E)||e.push(`boards.${f}.${E}: unknown field.`);b.source!=="client"&&b.source!=="server"&&(e.push(`boards.${f}.source: must be "client" or "server".`),S=!1),b.day!==void 0&&b.day!=="submit"&&b.day!=="start"&&e.push(`boards.${f}.day: must be "submit" or "start".`),b.day==="start"&&b.source!=="server"&&e.push(`boards.${f}.day: start requires source "server".`);let O=ye(b,"label",48,`boards.${f}`,e),T=["all-time"];b.periods!==void 0&&(!Array.isArray(b.periods)||b.periods.length<1||b.periods.length>2||b.periods.some(E=>E!=="daily"&&E!=="all-time")||new Set(b.periods).size!==b.periods.length?e.push(`boards.${f}.periods: must contain daily, all-time, or both without duplicates.`):T=[...b.periods]),S&&Object.defineProperty(I,f,{value:{source:b.source,periods:T,...b.day===void 0?{}:{day:b.day},...O===void 0?{}:{label:O}},enumerable:!0,configurable:!0,writable:!0})}}}let te=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let g=new Set;for(let[f,L]of t.roles.entries()){let S=J(L);if(S===null){e.push(`roles[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","min","max","label"].includes(l)||e.push(`roles[${f}].${l}: unknown field.`);let b=S.id,O=S.min,T=S.max,E=!0;typeof b!="string"||b.length>32||!qe.test(b)?(e.push(`roles[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),E=!1):g.has(b)?(e.push(`roles[${f}].id: duplicate role ${b}.`),E=!1):g.add(b),V(O,0,P)||(e.push(`roles[${f}].min: must be an integer from 0 to ${P}.`),E=!1),T!==void 0&&!V(T,0,P)&&(e.push(`roles[${f}].max: must be an integer from 0 to ${P} when present.`),E=!1),typeof O=="number"&&typeof T=="number"&&O>T&&(e.push(`roles[${f}].max: must be greater than or equal to min.`),E=!1);let ie=ye(S,"label",32,`roles[${f}]`,e);E&&te.push({id:b,min:O,...T===void 0?{}:{max:T},...ie===void 0?{}:{label:ie}})}}let Y=null;if(t.teams!==void 0&&t.teams!==null){let g=J(t.teams);if(g===null)e.push("teams: must be null or an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`teams.${f}: unknown field.`);V(g.min,2,P)||e.push(`teams.min: must be an integer from 2 to ${P}.`),V(g.max,2,P)||e.push(`teams.max: must be an integer from 2 to ${P}.`),V(g.min,2,P)&&V(g.max,2,P)&&(g.min>g.max?e.push("teams.max: must be greater than or equal to teams.min."):Y={min:g.min,max:g.max})}}let re="none";t.voice!==void 0&&(typeof t.voice!="string"||!zt.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):re=t.voice);let H=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let g=new Set;for(let[f,L]of t.modes.entries()){let S=J(L);if(S===null){e.push(`modes[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","players","lobby","matchmaking","execution","label","instructions"].includes(l)||e.push(`modes[${f}].${l}: unknown field.`);if(typeof S.id!="string"||S.id.length>32||!qe.test(S.id)){e.push(`modes[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(g.has(S.id)){e.push(`modes[${f}].id: duplicate mode ${S.id}.`);continue}g.add(S.id);let b={id:S.id};for(let[l,y]of[["label",48],["instructions",160]]){let R=ye(S,l,y,`modes[${f}]`,e);R!==void 0&&(b[l]=R)}if(S.execution!==void 0&&(S.execution!=="local"&&S.execution!=="room"?e.push(`modes[${f}].execution: must be local or room.`):b.execution=S.execution),ee!==null&&b.execution===void 0&&e.push(`modes[${f}].execution: is required with the standard overlay.`),S.players!==void 0){let l=`modes[${f}].players`,y=J(S.players);if(y===null)e.push(`${l}: must be an object with min and max.`);else{for(let R of Object.keys(y))R!=="min"&&R!=="max"&&e.push(`${l}.${R}: unknown field.`);V(y.min,1,P)||e.push(`${l}.min: must be an integer from 1 to ${P}.`),V(y.max,1,P)||e.push(`${l}.max: must be an integer from 1 to ${P}.`),V(y.min,1,P)&&V(y.max,1,P)&&(y.min>y.max?e.push(`${l}.max: must be greater than or equal to min.`):b.players={min:y.min,max:y.max})}}if(S.lobby!==void 0&&(typeof S.lobby!="boolean"?e.push(`modes[${f}].lobby: must be a boolean.`):b.lobby=S.lobby),b.execution==="local"){let l=b.players??F;(l.min!==1||l.max!==1)&&e.push(`modes[${f}].players: local execution requires min and max to be 1.`),(b.lobby??W)&&e.push(`modes[${f}].lobby: local execution requires false.`),S.matchmaking!==void 0&&e.push(`modes[${f}].matchmaking: local execution cannot use matchmaking.`)}if(S.matchmaking===void 0){H.push(b);continue}let O=J(S.matchmaking);if(O===null){e.push(`modes[${f}].matchmaking: must be an object.`);continue}for(let l of Object.keys(O))["key","timeoutMs","defaults"].includes(l)||e.push(`modes[${f}].matchmaking.${l}: unknown field.`);let T=!0,E=[];if(!Array.isArray(O.key)||O.key.length<1||O.key.length>8)e.push(`modes[${f}].matchmaking.key: must contain from 1 to 8 fields.`),T=!1;else for(let[l,y]of O.key.entries())typeof y!="string"||!$t.test(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),T=!1):E.includes(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: duplicate field ${y}.`),T=!1):E.push(y);V(O.timeoutMs,1e3,3e5)||(e.push(`modes[${f}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),T=!1);let ie;if(O.defaults!==void 0){let l=J(O.defaults);if(l===null||Object.keys(l).length!==E.length||E.some(y=>!Object.hasOwn(l,y)))e.push(`modes[${f}].matchmaking.defaults: must contain exactly the declared key fields.`);else{ie={};for(let[y,R]of Object.entries(l))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${f}].matchmaking.defaults.${y}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(ie,y,{value:R,enumerable:!0})}}T&&H.push({...b,matchmaking:{...ie===void 0?{}:{defaults:ie},key:E,timeoutMs:O.timeoutMs}})}}return ee!==null&&H.length===0&&e.push("modes: at least one explicit mode is required with the standard overlay."),e.length>0?{ok:!1,errori:e}:{ok:!0,manifest:{manifest:1,overlay:ee,id:i,name:r,description:s,cover:c,card:m,icon:h,screenshots:d,tags:u,languages:x,language:w,platform:N,orientation:_,input:j,visibility:z,network:B,requires:U,players:F,lobby:W,persistent:A,replays:M,spectators:ue,boards:I,roles:te,teams:Y,voice:re,modes:H}}}function jt(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function Fe(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Gt(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let o=e?.deviceMemory,a=typeof o=="number"?o*1024:NaN;Number.isFinite(a)&&(t=a)}catch{t=null}let i=null;try{let o=e?.hardwareConcurrency;typeof o=="number"&&Number.isFinite(o)&&(i=o)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let s=!1;try{s=n.crossOriginIsolated===!0}catch{s=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:s,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function We(n,e=1500){let t=n??globalThis,i=Gt(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let h=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(h!==null){i.webgl2=!0,i.gpu="hardware",Fe(h);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Fe(d))}catch{i.webgl2=!1,i.gpu="none"}}),s=Promise.resolve().then(async()=>{let m;try{let h=t.navigator?.gpu;if(h===void 0)return;let d=await h.requestAdapter();if(d===null)return;m=await d.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),o=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),a=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),c;return await Promise.race([Promise.all([r,s,o,a]),new Promise(m=>{c=setTimeout(m,Math.max(0,e))})]),c!==void 0&&clearTimeout(c),{...i,tier:jt(i)}}function Ae(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var de=/^[A-Za-z0-9_-]{22}$/;function Bt(n,e=null,t=null,i=null){let r=Te(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");return{manifest:r.manifest,coverUrl:e,iconUrl:i,invite:t}}function D(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Ut(n){let e=D(n),t=D(e?.configuration);return e?.v===1&&typeof e.epoch=="string"&&e.epoch.length>0&&e.epoch.length<=128&&t!==null&&(t.coverUrl===null||typeof t.coverUrl=="string")&&(t.iconUrl===null||typeof t.iconUrl=="string")&&(t.invite===null||typeof t.invite=="string"&&/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(t.invite))&&Te(t.manifest).ok}function He(n){return Ut(n)?{v:1,epoch:n.epoch,configuration:Bt(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Ft(n){let e=D(n);return e!==null&&Object.keys(e).length===4&&["top","right","bottom","left"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])&&Number(e[t])>=0&&Number(e[t])<=1e5)}function Oe(n){let e=D(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Ft(e.safeArea))&&(e.shortcutEnabled===void 0||typeof e.shortcutEnabled=="boolean")&&typeof e.inputBlocked=="boolean"&&Array.isArray(e.reservedRects)&&e.reservedRects.length<=8&&e.reservedRects.every(t=>{let i=D(t);return i!==null&&Object.keys(i).length===4&&["x","y","width","height"].every(r=>typeof i[r]=="number"&&Number.isFinite(i[r])&&i[r]>=0&&i[r]<=1e5)})}function Ke(n){let e=D(n),t=D(e?.args);if(e?.type!=="caisual:overlay"||e.v!==1||typeof e.epoch!="string"||e.epoch.length<1||e.epoch.length>128||typeof e.requestId!="string"||!(/^[1-9][0-9]{0,15}$/.test(e.requestId)&&Number.isSafeInteger(Number(e.requestId)))||t===null||Object.keys(e).some(s=>!["type","v","epoch","requestId","sessionId","op","args"].includes(s))||!(e.sessionId===void 0||e.sessionId===null||typeof e.sessionId=="string"&&/^[1-9][0-9]{0,15}$/.test(e.sessionId)))return!1;let i=(...s)=>Object.keys(t).every(o=>s.includes(o)),r=s=>typeof t[s]=="string"&&t[s].length>=1&&t[s].length<=64;switch(e.op){case"replay.play":case"replay.pause":return i()&&typeof e.sessionId=="string";case"replay.seek":return i("positionMs")&&typeof e.sessionId=="string"&&typeof t.positionMs=="number"&&Number.isFinite(t.positionMs)&&t.positionMs>=0&&t.positionMs<=18e5;case"replay.speed":return i("speed")&&typeof e.sessionId=="string"&&[.5,1,2,4].includes(Number(t.speed))&&typeof t.speed=="number";case"local.start":return i("mode")&&r("mode");case"room.create":return i("mode")&&(t.mode===null||r("mode"));case"room.join":return i("code")&&(t.code===void 0||r("code"));case"room.watch":return i("code")&&r("code");case"room.match":{let s=D(t.key);return i("mode","key")&&r("mode")&&(t.key===void 0||s!==null&&Object.keys(s).length<=8&&Object.values(s).every(o=>typeof o=="string"&&o.length>=1&&o.length<=64||typeof o=="number"&&Number.isSafeInteger(o)))}case"room.ready":return i("ready")&&typeof t.ready=="boolean";case"room.role":case"room.requestRole":return i("role")&&r("role");case"room.team":return i("team")&&Number.isInteger(t.team)&&t.team>=1&&t.team<=24;case"room.restart":case"room.start":case"session.cancel":case"session.leave":case"session.disconnect":case"session.resume":return i();case"voice.join":case"voice.leave":return i()&&typeof e.sessionId=="string";case"voice.mute":return i("muted")&&typeof t.muted=="boolean"&&typeof e.sessionId=="string";case"voice.setVolume":return i("playerId","volume")&&typeof e.sessionId=="string"&&typeof t.playerId=="string"&&t.playerId.length>0&&t.playerId.length<=128&&typeof t.volume=="number"&&Number.isFinite(t.volume)&&t.volume>=0&&t.volume<=1;case"overlay.view":return Oe(t);default:return!1}}function me(n){if(typeof n!="string"||!/^\\d{4}-\\d{2}-\\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isFinite(e)&&new Date(e).toISOString().slice(0,10)===n}function Ye(n,e){let t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,i=t(n);if(!i||!Array.isArray(i.standings))return null;let r=new Set(e),s=new Set,o=[];for(let a of i.standings){let c=t(a);!c||typeof c.playerId!="string"||!r.has(c.playerId)||s.has(c.playerId)||(s.add(c.playerId),o.push({playerId:c.playerId,...typeof c.score=="number"&&Number.isFinite(c.score)?{score:c.score}:{},...typeof c.rank=="number"&&Number.isSafeInteger(c.rank)&&c.rank>0?{rank:c.rank}:{}}))}return o.length?{standings:o,...Array.isArray(i.winners)?{winners:[...new Set(i.winners.filter(a=>typeof a=="string"&&s.has(a)))]}:{},...typeof i.draw=="boolean"?{draw:i.draw}:{},...typeof i.unit=="string"?{unit:i.unit}:{}}:null}function p(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function $(){return p("offline","Caisual services are unavailable.")}function pe(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Wt(n){let e={};try{e=await n.json()}catch{}return p(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function be(n,e,t,i){async function r(s,o,a,c){let m=new Headers({Authorization:`Bearer ${a}`}),h;if(c!==void 0){m.set("Content-Type","application/json");try{h=JSON.stringify(c)}catch{throw p("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+s,n),{method:o,headers:m,body:h,credentials:"omit"})}catch{throw $()}}return async function(o,a,c,m=!1){let h;try{h=m?await i.rinnova():await i.ottieni()}catch{throw $()}let d=await r(o,a,h,c);if(d.status===401){try{h=await i.rinnova()}catch{throw $()}d=await r(o,a,h,c)}if(!d.ok)throw await Wt(d);try{return await d.json()}catch{throw p("internal_error","The service returned an invalid response.")}}}var Ee=.02,Ze=300,Ht=200,Qe=3e3,Kt=1e4,Yt=[1e3,2e3,4e3];function Xe(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Zt(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var we=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Zt(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=this.scegliMic(e);this.verificaIngresso(t),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(p("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw p("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=Xe(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(p(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,Xe(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(p("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(p("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}scegliMic(e){return e.mic!==void 0?e.mic:this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role!=="spectator"}verificaIngresso(e=this.micDesiderato){if(!this.contesto.connessa())throw p("offline","The room is not connected.");if(this.modeCorrente==="none")throw p("voice_disabled","Voice is disabled for this room.");if(this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role==="spectator"&&e)throw p("spectator","Spectators cannot publish voice.");if(this.dipendenze===null)throw p("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let s;try{s=await t.getUserMedia({audio:!0})}catch(a){throw this.permessoNegato(a)?p("permission_denied","Microphone permission was denied."):p("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(a){for(let c of s.getTracks())c.stop();throw a}let o=s.getAudioTracks()[0];if(o===void 0)throw p("voice_error","The microphone has no audio track.");this.stream=s,this.tracciaMic=o,o.enabled=!this.mutedCorrente,this.preparaAnalizzatore(s)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw p("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let s of this.gains.keys())this.aggiornaZero(s);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=s=>{let o=s.transceiver.mid,a=o===null?void 0:this.midGiocatori.get(o);a!==void 0&&this.collegaTraccia(a,s.track,s.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let s=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),o=await i.createOffer();await i.setLocalDescription(o),this.controllaGenerazione(t);let a=s.mid,c=i.localDescription?.sdp;if(a===null||c===void 0)throw p("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:c,mid:a})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw p("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw p("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw p("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,s)=>{let o=()=>{e.removeEventListener("connectionstatechange",a),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},a=()=>{t!==this.generazione?(o(),s(p("offline","Voice was stopped."))):e.connectionState==="connected"?(o(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(o(),s(p("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",a),this.cancellaAttesaConnessione=()=>{o(),s(p("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{o(),s(p("voice_error","The voice connection timed out."))},Kt)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(m=>[m.id,m])),r=[];for(let[m,h]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===h.session&&d.track===h.track||(r.push(h),this.riproduzioni.has(m)||h.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(h.mid),this.scollegaTraccia(m))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(m=>m.mid)});let s=[...i.values()].filter(m=>!this.sfuAttive.has(m.id));if(s.length===0)return;let o;try{o=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:s.map(m=>({session:m.session,track:m.track}))})}catch(m){if(pe(m)!=="not_allowed")throw m;for(let h of s)this.negati.add(h.id);return}if(o.op!=="subscribe")throw p("voice_error","The voice service returned an invalid response.");for(let m of o.tracks){let h=s.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&h!==void 0&&this.negati.add(h.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||h===void 0)&&(this.midGiocatori.set(m.mid,h.id),this.sfuAttive.set(h.id,{session:h.session,track:h.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:o.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let c=t.localDescription?.sdp;if(c===void 0)throw p("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:c}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=s=>{s.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:s.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=s=>{r.receiver=s.receiver,this.collegaTraccia(t,s.track,s.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(o=>o.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let s=t;try{if(s.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(s.candidate);return}if(s.kind!=="offer"&&s.kind!=="answer"||typeof s.sdp!="string")return;let o=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),a=s.kind==="offer"&&!o;if(r.ignoreOffer=!r.polite&&a,r.ignoreOffer)return;if(r.settingRemoteAnswer=s.kind==="answer",await r.pc.setRemoteDescription({type:s.kind,sdp:s.sdp}),r.settingRemoteAnswer=!1,s.kind==="offer"){let c=await r.pc.createAnswer();await r.pc.setLocalDescription(c);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(pe(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>{if(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic)return!1;if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return!1}return!0})}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<Qe})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),s=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,Qe-r));this.timerZero.set(e,s)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),s=r.creaMediaStream([t]),o=this.richiediAudioContext().createMediaStreamSource(s),a=this.richiediAudioContext().createGain();o.connect(a),a.connect(this.richiediAudioContext().destination);let c=null;try{c=this.richiediAudioContext().createAnalyser(),c.fftSize=256,o.connect(c)}catch{c=null}let m=r.creaAudioElement();m.srcObject=s,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:o,gain:a,analyser:c,audio:m,track:t,receiver:i});let h=this.sfuAttive.get(e);h!==void 0&&(h.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Ht)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Ee),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=Ze;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let s of this.copiaPeers()){let o=this.riproduzioni.get(s.id);this.livelloAnalizzatore(o?.analyser??null)>Ee?this.ultimoAudio.set(s.id,e.ora()):(o?.analyser===null||o?.analyser===void 0)&&(o?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Ee)&&this.ultimoAudio.set(s.id,e.ora());let a=!s.muted&&e.ora()-(this.ultimoAudio.get(s.id)??0)<=Ze;(this.speakingPeers.get(s.id)??!1)!==a&&(this.speakingPeers.set(s.id,a),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,s)=>r+s*s,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>{if(r.id===e)return[];if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return[]}return[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}]})}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(p("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Yt[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(p("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(s){this.richieste.delete(t),r(s)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw p("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw p("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw p("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw p("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="spectator"||t==="offline"||t==="voice_error"?e:p("voice_error","Voice could not be started.")}return p("voice_error","Voice could not be started.")}};var ne=1,et=[1e3,2e3,4e3,8e3],Qt=6e4,Xt=5e3,ei=2e4,ti=500,ii=2e3,ni=new Set([4003,4004,4005,4006,4008,4009]);function Q(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function tt(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ri(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function oi(n){let e=Q(n),t=Q(e?.players);return e!==null&&typeof e.url=="string"&&Number.isInteger(e.timeoutMs)&&e.timeoutMs>=1e3&&e.timeoutMs<=3e5&&t!==null&&Number.isInteger(t.min)&&Number.isInteger(t.max)&&t.min>=1&&t.max>=t.min}function Z(n){return JSON.parse(JSON.stringify(n))}function _e(n,e){let t=Z(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Z(i.value);continue}let r=t,s=i.path;for(let a=0;a<s.length-1;a++){let c=s[a];if(Array.isArray(r)){if(typeof c!="number"||c>=r.length)return{ok:!1};r=r[c]}else{let m=Q(r);if(m===null||typeof c!="string"||!Object.hasOwn(m,c))return{ok:!1};r=m[c]}}let o=s.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof o!="number"||o>=r.length)return{ok:!1};r[o]=Z(i.value)}else{let a=Q(r);if(a===null||typeof o!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(a,o))return{ok:!1};delete a[o]}else Object.defineProperty(a,o,{configurable:!0,enumerable:!0,value:Z(i.value),writable:!0})}}return{ok:!0,state:t}}function si(n){let e=be(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,c,m)=>{try{return await e(o,a,{...Q(c),n:n.n},m)}catch(h){if(h instanceof Error&&"code"in h&&["version_outdated","version_mismatch"].includes(String(h.code))){let d=Q(c),u=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\\s-]/g,""):void 0,v=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(h,h.code==="version_mismatch"?{code:u,roomId:v,watch:o==="/rooms/watch"}:void 0)}throw h}};async function i(o,a,c=!1){let m=await t(o,"POST",a,c);if(!tt(m))throw p("internal_error","The room service returned an invalid response.");return m}async function r(o){let a=await t("/match","POST",{mode:o.mode,key:o.key});if(!oi(a))throw p("internal_error","The matchmaking service returned an invalid response.");return a}async function s(o,a=!1){let c=await t("/rooms/watch","POST",o,a);if(!ri(c))throw p("internal_error","The room service returned an invalid response.");return c}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),watchCode:o=>s({code:o}),watchRoom:o=>s({roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var Se=class{constructor(e,t,i,r,s,o,a=!1){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=s;this.segnalaStanza=o;this.spettatore=a;this.meta={host:null,mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.scoreListeners=new Set;this.scores=[];this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.hostCorrente=null;this.resultCorrente=null;this.delaySpettatore=0;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.replay=!1;this.promessaPronta=new Promise((c,m)=>{this.risolviPronta=c,this.rifiutaPronta=m}),this.voice=new we({invia:c=>this.invia(c),connessa:()=>this.socket?.readyState===ne&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),a&&(this.rosterRicevuto=!0),this.apri(i)}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}get queuedScores(){return structuredClone(this.scores)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onScoreQueued(e){return this.scoreListeners.add(e),()=>this.scoreListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.metadataChanged({host:e.host,mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(p("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(p("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(p("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let s=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(p("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:s});try{this.invia({t:"request-role",r:t,role:e})}catch(o){this.dipendenze.clearTimeout(s),this.roleRequests.delete(t),r(o)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(p("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(p("cancelled","The room was disconnected.")))}get role(){return this.spettatore?"spectator":this.giocatoriCorrenti.find(e=>e.id===this.youCorrente)?.role??null}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get host(){return this.hostCorrente}get code(){return this.codice}get result(){return this.resultCorrente}get delayMs(){return this.delaySpettatore}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-29),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw p("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(30,this.tickRateCorrente):30);this.inviiGioco=this.inviiGioco.filter(o=>e-o<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,s=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let o=this.dipendenze.ora();if(o<this.ultimoInvioGioco+i||this.inviiGioco.filter(c=>o-c<1e3).length>=30){this.programmaInput();return}let a=this.ultimoInput;try{this.send(JSON.parse(a)),this.inputInviato=a}catch{}},Math.max(0,Math.ceil(Math.max(s,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}start(){this.invia({t:"start"})}restart(){if(this.statusCorrente!=="finished")throw p("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){if(!this.lasciata){if(this.spettatore||this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===ne){let e=this.socket;this.invia({t:"leave"}),this.spettatore&&e.close(1e3)}this.termina(1e3)}}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==ne)throw p("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw p("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Xt:ei;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===ne)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=Q(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="watching")this.riceviWatching(t);else if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="replay-ready"&&/^[A-Za-z0-9_-]{22}$/.test(t.id))this.metadataChanged({replayId:t.id});else if(t.t==="players")this.riceviGiocatori(t.players,t.host);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,Z(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="score-queued"&&!this.spettatore)this.scores.push(structuredClone(t.score)),this.scores=this.scores.slice(-32),this.notifica(this.scoreListeners,structuredClone(t.score));else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(p(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWatching(e){let t=e.room;!this.spettatore||t.id!==this.roomId||(this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.delaySpettatore=e.delayMs,this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},ii)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e,t){this.giocatoriCorrenti=e.map(i=>({...i})),t!==void 0?this.hostCorrente=t:this.giocatoriCorrenti.some(i=>i.id===this.hostCorrente&&i.connected)||(this.hostCorrente=this.giocatoriCorrenti.find(i=>i.connected)?.id??null),this.metadataChanged({host:this.hostCorrente}),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){(e.status==="playing"||e.status==="countdown"||e.status==="lobby")&&this.metadataChanged({replayId:null}),this.statusCorrente=e.status,e.host!==void 0&&(this.hostCorrente=e.host),this.resultCorrente=Z(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,host:this.hostCorrente,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=_e(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=Z(e),this.statoPubblico=Z(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==ne)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(ni.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.spettatore||this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,et.length-1),t=et[e];if(this.tempoRiconnessione+t>Qt){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=this.spettatore?await this.api.watchRoom(this.roomId):await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let o=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(p(o,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.spettatore&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},ti))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function he(n=null){return{replay:!1,invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw $()},async join(){throw $()},async watch(){throw $()},async match(){throw $()}}}function it(n,e){let t,i=new Set,r=si({...n,onVersionError(d,u){t=u;for(let v of i)try{v(d)}catch{}}}),s=!1,o=null,a=d=>{let u=d?.code??null;s&&u===o||(s=!0,o=u,n.segnalaStanza?.(d))},c=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,a);return await u.pronta(),u},m=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,()=>{},!0);return await u.pronta(),{role:"spectator",replay:!1,get mode(){return u.mode},get countdownAt(){return u.countdownAt},get connection(){return u.connection},get metadata(){return u.metadata},onMetadata:v=>u.onMetadata(v),onConnection:v=>u.onConnection(v),disconnect:()=>u.disconnect(),get state(){return u.state},get tick(){return u.tick},get tickRate(){return u.tickRate},get latency(){return u.latency},get seed(){return u.seed},get status(){return u.status},get players(){return u.players},get host(){return u.host},get code(){return u.code},get result(){return u.result},get delayMs(){return u.delayMs},onState:v=>u.onState(v),onPlayers:v=>u.onPlayers(v),onStatus:v=>u.onStatus(v),onMessage:v=>u.onMessage(v),leave:()=>{u.leave()},serverTime:()=>u.serverTime()}},h=(d,u)=>new Promise((v,x)=>{let w,N=!1,_=()=>{w.removeEventListener("message",W),w.removeEventListener("close",U),w.removeEventListener("error",F),u.signal?.removeEventListener("abort",B)},j=()=>{try{w.close(1e3)}catch{}},z=(A,M)=>{N||(N=!0,_(),M&&j(),x(A))};function B(){z(p("cancelled","The matchmaking search was cancelled."),!0)}function U(){z($(),!1)}function F(){z($(),!0)}function W(A){let M=null;try{M=typeof A.data=="string"?Q(JSON.parse(A.data)):null}catch{}if(M===null||typeof M.t!="string"){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}if(M.t==="waiting"){if(!Number.isInteger(M.players)||!Number.isInteger(M.min)||!Number.isInteger(M.max)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}try{u.onWaiting?.({players:M.players,min:M.min,max:M.max})}catch{}return}if(M.t==="matched"){if(!tt(M)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}N=!0,_(),j(),v(M);return}if(M.t==="no_match"){z(p("no_match","No match was found before the timeout."),!0);return}if(M.t==="error"){z(p(typeof M.code=="string"?M.code:"internal_error",typeof M.message=="string"?M.message:"The matchmaking service could not complete the search."),!0);return}M.t!=="pong"&&z(p("internal_error","The matchmaking service sent an invalid message."),!0)}try{w=n.apriSocket(d)}catch{x($());return}w.addEventListener("message",W),w.addEventListener("close",U),w.addEventListener("error",F),u.signal?.addEventListener("abort",B,{once:!0}),u.signal?.aborted===!0&&B()});return{replay:!1,invited:e,reload(){n.reload?.(t)},onError(d){return i.add(d),()=>{i.delete(d)}},async create(d){return c(await r.create(d.mode))},async join(d){let u=d??e;if(u==null||u.length===0)throw p("invalid_request","A room invitation code is required.");return c(await r.joinCode(u))},async watch(d){if(typeof d!="string"||d.length===0)throw p("invalid_request","A room invitation code is required.");return m(await r.watchCode(d))},async match(d){let u=()=>d.signal?.aborted===!0;if(u())throw p("cancelled","The matchmaking search was cancelled.");let v=await r.match(d);if(u())throw p("cancelled","The matchmaking search was cancelled.");return c(await h(v.url,d))}}}var K=()=>p("replay_invalid","The replay is incomplete or invalid.");function q(n,...e){for(let t of n)try{t(...e)}catch{}}function le(n,e){return n.add(e),()=>{n.delete(e)}}var li={now:()=>performance.now(),setInterval:(n,e)=>globalThis.setInterval(n,e),clearInterval:n=>globalThis.clearInterval(n)},ze=class{constructor(e,t,i=li){this.index=e;this.events=t;this.clock=i;this.replay=!0;this.role="spectator";this.delayMs=0;this.code="";this.latency=null;this.countdownAt=null;this.cursor=1;this.position=0;this.paused=!0;this.speedValue=1;this.timer=null;this.last=0;this.lastEmitted=-1/0;this.disconnected=!1;this.checkpoints=[];this.states=new Set;this.playersListeners=new Set;this.statuses=new Set;this.metadataListeners=new Set;this.connections=new Set;this.playbackListeners=new Set;this.step=()=>{let e=this.clock.now();this.position=Math.min(this.index.durationMs,this.position+Math.max(0,e-this.last)*this.speedValue),this.last=e,this.advance(!0),this.position>=this.index.durationMs&&this.pause(),e-this.lastEmitted>=100&&(this.lastEmitted=e,q(this.playbackListeners,this.playback))};if(t[0]?.message.t!=="start"||t[0].at!==0||t[0].message.room.id!==e.roomId)throw K();let r=t[0].message;this.picture=structuredClone({room:r.room,players:r.players,state:r.state,result:null}),this.checkpoints.push({cursor:1,at:0,picture:structuredClone(this.picture)});let s=Math.max(1,Math.ceil(t.length/32)),o=0;for(let a=1;a<t.length;a++){let c=t[a];if(!Number.isFinite(c.at)||c.at<o||c.at>e.durationMs||c.message.t==="start")throw K();this.apply(c.message,!1),a%s===0&&this.checkpoints.push({cursor:a+1,at:c.at,picture:structuredClone(this.picture)}),o=c.at}this.seek(0)}get mode(){return this.picture.room.mode}get connection(){return this.disconnected?"disconnected":"connected"}get metadata(){return{host:this.host,mode:this.mode,countdownAt:null,configuration:null,rematch:null,connection:this.connection,closedCode:null}}get state(){return structuredClone(this.picture.state)}get tick(){return this.picture.room.tick}get tickRate(){return this.picture.room.tickRate}get seed(){return this.picture.room.seed}get status(){return this.picture.room.status}get players(){return structuredClone(this.picture.players)}get host(){return this.picture.room.host}get result(){return structuredClone(this.picture.result)}get playback(){return{positionMs:this.position,durationMs:this.index.durationMs,speed:this.speedValue,paused:this.paused,truncated:this.index.truncated}}serverTime(){return this.index.startedAt+this.position}onState(e){return le(this.states,e)}onStatus(e){return le(this.statuses,e)}onPlayers(e){return le(this.playersListeners,e)}onMetadata(e){return le(this.metadataListeners,e)}onConnection(e){return le(this.connections,e)}onMessage(e){return()=>{}}onPlayback(e){return le(this.playbackListeners,e)}apply(e,t){let i=this.picture;switch(e.t){case"start":throw K();case"snapshot":i.state=structuredClone(e.state);break;case"state":{if(i.room.tick!==e.base)throw K();let r=_e(i.state,e.patch);if(!r.ok)throw K();i.state=r.state;break}case"players":i.players=structuredClone(e.players),e.host!==void 0&&(i.room.host=e.host),t&&q(this.playersListeners,this.players);return;case"status":i.room.status=e.status,i.result=structuredClone(e.result),e.host!==void 0&&(i.room.host=e.host),t&&q(this.statuses,this.status,this.result,e.at);return;default:throw K()}i.room.tick=e.tick,i.room.serverTime=e.serverTime,i.room.tickRate=e.tickRate??i.room.tickRate,t&&q(this.states,this.state,this.tick,e.serverTime)}seek(e){if(!Number.isFinite(e)||this.disconnected)return;this.position=Math.max(0,Math.min(e,this.index.durationMs));let t=[...this.checkpoints].reverse().find(i=>i.at<=this.position);this.picture=structuredClone(t.picture),this.cursor=t.cursor,this.advance(!1),this.last=this.clock.now(),q(this.playersListeners,this.players),q(this.statuses,this.status,this.result,this.serverTime()),q(this.states,this.state,this.tick,this.serverTime()),q(this.metadataListeners,this.metadata),this.position>=this.index.durationMs&&this.pause(),q(this.playbackListeners,this.playback)}advance(e){for(;this.events[this.cursor]&&this.events[this.cursor].at<=this.position;)this.apply(this.events[this.cursor++].message,e)}play(){!this.paused||this.disconnected||this.index.durationMs===0||(this.position>=this.index.durationMs&&this.seek(0),this.paused=!1,this.last=this.clock.now(),this.timer=this.clock.setInterval(this.step,16),q(this.playbackListeners,this.playback))}pause(){this.timer!==null&&this.clock.clearInterval(this.timer),this.timer=null,this.paused=!0,q(this.playbackListeners,this.playback)}speed(e){if(![.5,1,2,4].includes(e))throw K();this.paused||this.step(),this.speedValue=e,q(this.playbackListeners,this.playback)}disconnect(){this.disconnected||(this.pause(),this.disconnected=!0,q(this.connections,this.connection),q(this.metadataListeners,this.metadata))}leave(){this.disconnect()}};async function rt(n,e){let t=await n(e,{credentials:"omit",cache:"no-store"});if(!t.ok)throw p("replay_unavailable","This replay is no longer available.");let i=await t.json();if(i.format!==1||!de.test(i.id)||!Number.isInteger(i.chunks)||i.chunks<1||i.chunks>Math.ceil(10485760/524288)+1||!Number.isInteger(i.bytes)||i.bytes>10485760||i.bytes<1||!Number.isFinite(i.startedAt)||!Number.isFinite(i.durationMs)||i.durationMs<0||i.durationMs>18e5)throw K();let r=[],s=0;for(let o=0;o<i.chunks;o++){let a=await n(`${e}?chunk=${o}`,{credentials:"omit",cache:"no-store"});if(!a.ok)throw K();let c=await a.text();if(s+=new TextEncoder().encode(c).byteLength,s>i.bytes||!c.endsWith(`\n`))throw K();for(let m of c.trimEnd().split(`\n`))r.push(JSON.parse(m))}if(s!==i.bytes)throw K();try{return new ze(i,r)}catch{throw K()}}var ci=["en","it","es","fr","de","pt","ja"];function ot(n){let e=G(n);return e&&ci.includes(e.split("-")[0])?e:"en"}function st(n,e,t="/"){let i,r=t.match(/^\\/rt\\/[^/]+\\/[1-9][0-9]*\\//)?.[0]??"/";return()=>i??(i=(async()=>{let s={};try{let o=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(o.ok){let a=await o.json();Ge(a)&&(s=a)}}catch{}return(o,a={})=>Object.hasOwn(s,o)?s[o].replace(/\\{([^{}]+)\\}/g,(m,h)=>Object.hasOwn(a,h)?String(a[h]):m):o})())}var at="caisual-session-v1";function lt(n){let e=D(n);return!e||typeof e.code!="string"||!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(e.code)||!(e.mode===void 0||e.mode===null||typeof e.mode=="string")?null:{version:1,code:e.code,mode:typeof e.mode=="string"?e.mode:null,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}}function ct(n,e){let t=null,i=!1,r=Promise.resolve(),s=async()=>{let a={version:1,imported:!0,resume:t};return r=r.catch(()=>{}).then(async()=>{try{await n.set(at,a),i=!1}catch(c){throw i=!0,c}finally{e()}}),r},o=(async()=>{try{let a=await n.get(at),c=D(a);if(c?.version===1&&c.imported===!0)t=lt(c.resume);else{let m=await n.get("resume");t=lt(m),(a!==null||m!==null)&&await s()}}catch{i=!0}e()})();return{loaded:o,get value(){return t===null?null:{...t}},get error(){return i},async set(a){await o,t=a,e(),await s()}}}function X(n,e){for(let t of n)try{t(e)}catch{}}function ut(n,e=null,t=n.connected,i=null){let r=i!==null||e?.manifest.overlay?.version===1,s=e?.manifest,o={kind:"idle"},a=!1,c=0,m=0,h=null,d=null,u=null,v=null,x=[],w=!1,N="",_={inputBlocked:r,reservedRects:[],safeArea:{top:0,right:0,bottom:0,left:0}},j=new Set,z=new Set,B=new Set,U=new Set,F=new Set,W=new Set,A=null,M=()=>({local:i===null,rooms:i===null&&t,overlay:r,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function ue(){if(o.kind!=="room"||!s||s.voice==="none")return null;let l=o.room,y=l.voice;return!y||y.mode==="none"||l.players.find(R=>R.id===l.you)?.role==="spectator"?null:{mode:y.mode,state:y.state,mic:y.mic,muted:y.muted,speaking:y.speaking,peers:y.peers.map(({id:R,mic:C,muted:k,speaking:ae,volume:oe})=>({id:R,mic:C,muted:k,speaking:ae,volume:oe}))}}function ee(){let l=o.kind==="room"||o.kind==="watch"?o.room:null,y=l?.metadata.configuration,R=l?Ye(l.result,l.players.map(k=>k.id)):null,C=s&&l&&(l.mode===null||s.modes.some(k=>k.id===l.mode))?Ue(s,l.mode):{players:{min:1,max:1},lobby:!1};return{kind:h??(o.kind==="idle"?a?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:h?d:o.kind==="local"?o.mode:l?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:a,capabilities:M(),room:l?{...l===i?{replay:i.playback}:{},...l.metadata.replayId?{replayId:l.metadata.replayId}:{},...l.metadata.rematch?.keepSetup||l.metadata.rematch?.autoStart?{rematch:l.metadata.rematch}:{},code:l.code,mode:l.mode,status:l.status,host:l.host,you:o.kind==="room"?o.room.you:null,players:l.players.map(k=>({id:k.id,name:k.name,guest:k.guest,role:k.role,team:k.team,ready:k.ready,connected:k.connected})),...R?{result:R}:{},countdownAt:l.countdownAt,connection:l.connection,closedCode:l.metadata.closedCode,limits:{...y?.players??C.players},lobby:y?.lobby??C.lobby,persistent:y?.persistent??s?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:y?.requestRole??!1}:null,voice:h?null:ue(),waiting:u?{...u}:null,resume:A?.value??null,resumeError:A?.error??!1}}function I(){if(w)return;let l=ee(),y=JSON.stringify(l);y!==N&&(N=y,X(B,l))}function te(){X(j,{...o}),I()}function Y(){if(o.kind!=="room")throw p("no_room","There is no active player room.");return o.room}function re(){let l=Y();if(l.players.find(y=>y.id===l.you)?.role==="spectator")throw p("spectator","Spectators cannot use voice controls.");if(!s||s.voice==="none"||l.voice.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");return l.voice}function H(){c++,v?.abort(),v=null,h=null,u=null,I()}function g(l){x.splice(0).forEach(y=>y()),(o.kind==="room"||o.kind==="watch")&&(l?o.room.disconnect():o.room.leave()),o={kind:"idle"},te()}async function f(l){A?.value?.code===l&&await A.set(null).catch(()=>{})}async function L(l,y,R){if(R!==c||w)throw l.leave(),p("cancelled","The operation was cancelled.");g(!1),o=y?{kind:"watch",room:l,id:String(++m)}:{kind:"room",room:l,id:String(++m)};let C=l;if(x=[C.onPlayers(I),C.onMetadata(()=>{C.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===C?(x.splice(0).forEach(k=>k()),!y&&C.metadata.closedCode===1e3&&f(C.code),o={kind:"idle"},te()):I()}),C.onStatus(()=>{I(),!y&&C.connection==="ended"&&f(C.code)})],l===i&&x.push(i.onPlayback(I)),!y){let k=l,ae=o.id;k.voice&&x.push(k.voice.onState(I),k.voice.onPeers(I)),x.push(k.onError(oe=>X(F,{sessionId:ae,error:{...oe}}))),x.push(k.onScoreQueued(oe=>X(W,{...oe})));for(let oe of k.queuedScores)X(W,{...oe})}return h=null,u=null,te(),!y&&A&&C.connection!=="ended"&&await A.set({version:1,code:C.code,mode:C.mode,updatedAt:n.time.now()}).catch(()=>{}),l}async function S(l,y,R,C=!1){H();let k=c;v=new AbortController,h=l,d=y,I();try{let ae=await R(v.signal,k);if(await L(ae,C,k),k!==c||w)throw p("cancelled","The operation was cancelled.");return ae}finally{k===c&&(h=null,u=null,v=null,I())}}let b=n.room,O=b.onError(l=>{!r||w||(l.code==="version_mismatch"?b.reload():l.code==="version_outdated"&&X(F,{sessionId:o.kind==="idle"?null:o.id,error:l}))}),T=i||!r?b:{invited:b.invited,reload:()=>b.reload(),onError:l=>b.onError(l),create(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot create rooms.")):S("attaching",l.mode,()=>b.create(l))},join(l){return S("attaching",null,()=>b.join(l))},watch(l){return S("attaching",null,()=>b.watch(l),!0)},match(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot use matchmaking.")):S("matching",l.mode,(y,R)=>{let C=()=>{c===R&&H()};return l.signal?.addEventListener("abort",C,{once:!0}),l.signal?.aborted&&C(),b.match({...l,signal:y,onWaiting(k){R===c&&(u={...k},I(),l.onWaiting?.(k))}}).finally(()=>l.signal?.removeEventListener("abort",C))})}};return r&&!i&&(A=ct(n.save,I)),i&&(a=!0,L(i,!0,c)),{session:{get current(){return{...o}},get capabilities(){return M()},onChange(l){return j.add(l),X(new Set([l]),{...o}),()=>{j.delete(l)}},ready(){w||a||(a=!0,I())},finish(){if(o.kind==="room"||o.kind==="watch")throw p("not_local","Only a local session can be finished by the client.");o.kind==="local"&&(o={...o,status:"ended"},te())}},overlay:{open(l){if(!["home","room","invite","friends","voice","boards"].includes(l))throw p("invalid_request","Unknown overlay panel.");r&&X(U,l)},onChange(l){return z.add(l),X(new Set([l]),structuredClone(_)),()=>{z.delete(l)}}},rooms:T,snapshot:ee,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(l){return B.add(l),l(ee()),()=>{B.delete(l)}},onOpen(l){return U.add(l),()=>{U.delete(l)}},onError(l){return F.add(l),()=>{F.delete(l)}},onScore(l){return W.add(l),()=>{W.delete(l)}},async execute(l){if(!r)throw p("overlay_disabled","This game uses its own room flow.");if(l.op==="overlay.view"){if(!Oe(l.args))throw p("invalid_request","The overlay geometry is invalid.");if(_={...structuredClone(l.args),safeArea:{top:0,right:0,bottom:0,left:0,...l.args.safeArea}},typeof document<"u")for(let[y,R]of Object.entries(_.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${y}`,`${R}px`);X(z,structuredClone(_));return}if(l.sessionId!==void 0&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(l.op.startsWith("replay.")&&(!i||o.kind!=="watch"||o.room!==i||l.sessionId!==o.id))throw p("session_replaced","The replay is no longer active.");if(i&&!l.op.startsWith("replay.")&&!["session.leave","session.disconnect"].includes(l.op))throw p("replay_readonly","Replays are read only.");if(l.op.startsWith("voice.")&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(!a)throw p("game_not_ready","The game is still loading.");switch(l.op){case"replay.play":i.play();return;case"replay.pause":i.pause();return;case"replay.seek":i.seek(l.args.positionMs);return;case"replay.speed":i.speed(l.args.speed);return;case"local.start":{if(!s||!ve(s,l.args.mode))throw p("invalid_mode","This is not a local mode.");H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1),o={kind:"local",id:String(++m),mode:l.args.mode,status:"playing"},te();return}case"room.create":await T.create(l.args);return;case"room.join":await T.join(l.args.code);return;case"room.watch":await T.watch(l.args.code);return;case"room.match":{let y=s?.modes.find(C=>C.id===l.args.mode),R=l.args.key??y?.matchmaking?.defaults;if(!R)throw p("invalid_request","Matchmaking needs a complete key.");await T.match({mode:l.args.mode,key:R});return}case"voice.join":{let y=Y();if(await re().join(),o.kind!=="room"||o.room!==y)throw p("session_replaced","The active session changed.");I();return}case"voice.mute":re().mute(l.args.muted),I();return;case"voice.leave":re().leave(),I();return;case"voice.setVolume":{let y=re();if(!y.peers.some(R=>R.id===l.args.playerId))throw p("voice_peer_missing","This voice participant is no longer available.");y.setVolume(l.args.playerId,l.args.volume),I();return}case"room.ready":Y().ready(l.args.ready);return;case"room.role":Y().setRole(l.args.role);return;case"room.requestRole":await Y().requestRole(l.args.role);return;case"room.team":Y().setTeam(l.args.team);return;case"room.start":Y().start();return;case"room.restart":Y().restart();return;case"session.cancel":H();return;case"session.resume":{await S("attaching",null,async y=>{if(await A?.loaded,y.aborted)throw p("cancelled","The operation was cancelled.");if(!A?.value)throw p("no_resume","There is no saved room.");return b.join(A.value.code)});return}case"session.disconnect":{H();let y=c;if(o.kind==="room"&&o.room.connection!=="ended"&&A&&await A.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!0);return}case"session.leave":{H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1);return}}},dispose(){O(),H(),g(!0),w=!0,j.clear(),z.clear(),B.clear(),U.clear(),W.clear(),F.clear()}}}function dt(n,e,t){let i=!0,r=!1,s=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),o=a=>{let c=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||c?.closest?.(\'input,textarea,select,[contenteditable="true"]\')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",o,!0),()=>{s(),n.removeEventListener("keydown",o,!0)}}function mt(n,e,t){let i=!1,r=0,s=0,o=0,a=new Map,c=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[dt(window,t.overlay,()=>c({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>c({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>c({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:u})=>c({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:u})),t.onScore(d=>c({type:"caisual:overlay-score",v:1,epoch:e.epoch,score:d}))],h=d=>{let u=D(d.data);if(u?.type!=="caisual:overlay"||u.epoch!==e.epoch||i)return;let v={type:"caisual:overlay-response",v:1,epoch:e.epoch,requestId:typeof u.requestId=="string"?u.requestId:""};if(!Ke(u)){c({...v,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let x=JSON.stringify([u.op,u.args,u.sessionId]),w=a.get(u.requestId);if(w){w.fingerprint!==x?c({...v,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):w.response.then(c);return}if(Number(u.requestId)<=s||o>=32){c({...v,ok:!1,error:{code:"stale_request",message:"The request is stale or too many requests are pending."}});return}s=Number(u.requestId),o++;let N=Promise.resolve().then(()=>t.execute(u)).then(()=>({...v,ok:!0}),_=>({...v,ok:!1,error:{code:typeof D(_)?.code=="string"?D(_).code:"internal_error",message:_ instanceof Error?_.message:"The operation could not be completed."}}));a.set(u.requestId,{fingerprint:x,response:N}),N.then(_=>{if(o--,c(_),a.size>64)for(let j of a.keys())Number(j)<s-64&&a.delete(j)})};return n.addEventListener("message",h),n.start(),()=>{i=!0,n.removeEventListener("message",h),m.forEach(d=>d()),t.dispose(),a.clear()}}function pt(n,e,t){let i=be(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,s)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:s}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(s){if(pe(s)==="not_found")return null;throw s}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves},async boardSubmit(r,s,o){let a=await i("/scores","POST",{board:r,score:s,daily:o});return{accepted:!0,best:a.best,rank:a.rank,day:a.day,verified:a.verified}},async boardTop(r,s){if(s.day!==void 0&&(!me(s.day)||s.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");let o=new URLSearchParams;s.day!==void 0&&o.set("day",s.day),s.daily&&o.set("daily","1"),s.limit!==void 0&&o.set("limit",String(s.limit)),s.guests&&o.set("guests","1");let a=o.size===0?"":`?${o.toString()}`,{day:c,entries:m,me:h}=await i(`/scores/${encodeURIComponent(r)}${a}`,"GET");return{day:c,entries:m,me:h}}}}function ce(n){return(Math.floor(n/864e5)+1)*864e5}function Re(n,e,t){let i=new Set,r={...n},s,o=!1;function a(){!i.size||s!==void 0||o||(s=setTimeout(c,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),s.unref?.())}async function c(){s=void 0,o=!0;try{let m=await t(),h=m.day!==r.day;if(r={...m},h)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{o=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:ft(n.seed),rng:()=>ft(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&s!==void 0&&(clearTimeout(s),s=void 0)}}}}function Ve(n){return new Date(n).toISOString().slice(0,10)}async function Le(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function ft(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function ke(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function ht(n,e){return ke(n)?.type===e}function ui(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function gt(n,e,t=3e3){return new Promise(i=>{let r=!1,s=globalThis.crypto.randomUUID(),o=h=>{r||(r=!0,n.removeEventListener("message",c),n.clearTimeout(m),i(h))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:s,overlayVersion:1},e)},c=h=>{if(h.origin!==e||h.source!==n.parent)return;if(ht(h.data,"caisual:ready?")){a();return}if(!ht(h.data,"caisual:hello"))return;let d=ke(h.data),u=h.ports[0];if(typeof d?.ticket!="string"||!Ae(d.n)||u===void 0)return;u.start();let v=He(d.overlay),x=w=>Array.isArray(w)?w.map(G).filter(N=>N!==null):void 0;o({...v?{overlay:v}:{},...G(d.language)?{language:G(d.language)}:{},uiLanguage:G(d.uiLanguage)??void 0,languagePreferences:x(d.languagePreferences),gameLanguages:x(d.gameLanguages),...typeof d.replay=="string"&&de.test(d.replay)?{replay:d.replay}:{},ticket:d.ticket,n:d.n,live:ui(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:u})};n.addEventListener("message",c);let m=n.setTimeout(()=>o(null),t);a()})}function di(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=ke(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function mi(n,e,t,i){return new Promise((r,s)=>{let o=!1,a=h=>{o||(o=!0,n.removeEventListener("message",c),e.clearTimeout(m),h===null?s(new Error("Ticket refresh timed out.")):r(h))},c=h=>{let d=ke(h.data),u=d?.aud===void 0?"portal":d.aud;d?.type==="caisual:ticket"&&u===i&&typeof d.ticket=="string"&&a(d.ticket)};n.addEventListener("message",c);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function $e(n,e,t,i,r=3e3,s="portal"){let o=n,a=null,c=()=>{if(a!==null)return a;let h=mi(e,t,r,s).then(d=>(o=d,d)).finally(()=>{a===h&&(a=null)});return a=h,h};return{async ottieni(){if(o===null)return c();let m=di(o);return m!==null&&m-i()<3e4?c():o},rinnova:c}}var se="caisual:save:",pi=/^[a-z0-9][a-z0-9_-]{0,31}$/;function De(n){if(!pi.test(n))throw p("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function yt(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function vt(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(se)&&e.push(i.slice(se.length))}return e}function fi(n,e){let t=()=>{if(n===null)throw $();return n};return{async set(i,r){De(i);let s=t(),o=JSON.stringify({value:r}),a=new TextEncoder().encode(o).byteLength;if(a>262144)throw p("payload_too_large","The save is larger than 262144 bytes.");if(s.getItem(se+i)===null&&vt(s).length>=64)throw p("save_limit","A game can store at most 64 save keys.");let c={value:r,bytes:a,updatedAt:e()};return s.setItem(se+i,JSON.stringify(c)),{key:i,bytes:a,updatedAt:c.updatedAt}},async get(i){return De(i),yt(t().getItem(se+i))?.value??null},async remove(i){De(i),t().removeItem(se+i)},async list(){let i=t();return vt(i).flatMap(r=>{let s=yt(i.getItem(se+r));return s===null?[]:[{key:r,bytes:s.bytes,updatedAt:s.updatedAt}]}).sort((r,s)=>r.key.localeCompare(s.key))}}}async function xe(n,e=null){let t=n.ora(),i=Ve(t),r=await Le(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:Re({day:i,seed:r,expiresAt:ce(t)},n.ora,async()=>{let s=n.ora(),o=Ve(s);return{day:o,seed:await Le(n.hostname,o,n.subtle),expiresAt:ce(s)}}),time:{now:n.ora},save:fi(n.archivio,n.ora),board:{async submit(){return{accepted:!1,reason:"offline",verified:!1}},async top(s,o={}){if(o.day!==void 0&&(!me(o.day)||o.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");return{day:o.day??(o.daily?i:null),entries:[],me:null}}},room:he(e)}}function hi(n){let e=n?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function gi(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function yi(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:gi(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>We()}}async function vi(n){let e=hi(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return bt(n);let i=await gt(n.finestra,e,n.timeoutHandshake);if(i===null)return bt(n);if(i.replay){let u=i.overlay?.configuration.manifest.id;if(!u)throw new Error("The replay game is missing.");let v=await rt(n.fetcher,`${e}/api/replays/${encodeURIComponent(u)}/${i.replay}`),x=await xe(n),w=he();return x.connected=!0,x.room=Object.assign(v,{invited:null,reload:()=>w.reload(),onError:w.onError,create:w.create,join:w.join,match:w.match,watch:async()=>v}),Me(x,i,n,v)}let r=$e(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),s=pt(e,n.fetcher,r),o=n.ora(),a;try{a=await s.me()}catch{let u=await xe(n,i.invite);return Me(u,i,n)}let c=n.ora(),m=a.serverTime-(o+c)/2,h=i.live===null?he(i.invite):it({appOrigin:e,n:i.n,reload:u=>i.porta.postMessage({type:"caisual:reload",target:u}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:$e(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(u){if(n.apriSocket!==void 0)return n.apriSocket(u);if(typeof WebSocket>"u")throw $();return new WebSocket(u)},ora:n.ora,setTimeout:(u,v)=>globalThis.setTimeout(u,v),clearTimeout:u=>globalThis.clearTimeout(u),setInterval:(u,v)=>globalThis.setInterval(u,v),clearInterval:u=>globalThis.clearInterval(u),voce:n.voce,segnalaStanza(u){try{i.porta.postMessage({type:"caisual:room",room:u})}catch{}}},i.invite),d={connected:!0,player:a.player,daily:Re({day:a.day,seed:a.seed,expiresAt:a.expiresAt??ce(a.serverTime)},()=>n.ora()+m,async()=>{let u=await s.me();return{day:u.day,seed:u.seed,expiresAt:u.expiresAt??ce(u.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(u,v)=>s.saveSet(u,v),get:u=>s.saveGet(u),remove:u=>s.saveRemove(u),list:()=>s.saveList()},board:{async submit(u,v,x={}){try{return await s.boardSubmit(u,v,x.daily===!0)}catch(w){if(typeof w=="object"&&w!==null&&"code"in w&&w.code==="offline")return{accepted:!1,reason:"offline",verified:!1};throw w}},top:(u,v={})=>s.boardTop(u,v)},room:h};return Me(d,i,n)}function Me(n,e,t,i=null){let r=ut(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null,i);if(e?.overlay){let c=mt(e.porta,e.overlay,r);r.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",c,{once:!0})}let s=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=je(s,e?.gameLanguages??(e?.overlay?Ce(e.overlay.configuration.manifest):void 0)),a=ot(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:a},text:st(t?.fetcher??globalThis.fetch,o,t?.pathname),room:r.rooms,session:r.session,overlay:r.overlay}}async function bt(n){return Me(await xe(n),void 0,n)}function wt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function bi(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>wt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(wt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function St(n=yi()){let e=null;return{connect(){return e??(e=Promise.all([vi(n),bi(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Rt=St();globalThis.caisual=Rt;var xr=Rt;export{Rt as caisual,xr as default};\n');
5272
5272
  return;
5273
5273
  }
5274
5274
  const textMatch = url.pathname.match(/^\/__caisual\/text\/([^/]+)\.json$/);
@@ -6615,7 +6615,7 @@ var ApiError = class extends Error {
6615
6615
  hints;
6616
6616
  };
6617
6617
  function help() {
6618
- return `Caisual ${"0.17.0"}
6618
+ return `Caisual ${"0.20.0"}
6619
6619
 
6620
6620
  Usage:
6621
6621
  caisual init [--multiplayer | --arcade] [folder]
@@ -7397,7 +7397,7 @@ async function run(argumentsList) {
7397
7397
  return;
7398
7398
  }
7399
7399
  if (command === "--version" || command === "-V") {
7400
- process.stdout.write(`${"0.17.0"}
7400
+ process.stdout.write(`${"0.20.0"}
7401
7401
  `);
7402
7402
  return;
7403
7403
  }
package/package.json CHANGED
@@ -1,7 +1,18 @@
1
1
  {
2
2
  "name": "@caisual/cli",
3
- "version": "0.17.0",
3
+ "version": "0.20.0",
4
4
  "description": "Create and publish browser games on Caisual",
5
+ "license": "MIT",
6
+ "homepage": "https://caisual.com",
7
+ "keywords": [
8
+ "caisual",
9
+ "browser-games",
10
+ "multiplayer",
11
+ "publish",
12
+ "cli",
13
+ "game-dev"
14
+ ],
15
+ "author": "Damiano Rodriguez",
5
16
  "type": "module",
6
17
  "bin": {
7
18
  "caisual": "dist/caisual.mjs"