@caisual/kit 0.21.0 → 0.22.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/README.md +6 -9
- package/dist/host.d.ts +1 -0
- package/dist/host.js +169 -0
- package/dist/kit.js +2 -4
- package/dist/kit.js.map +4 -4
- package/dist/node.js +164 -409
- package/dist/runtime.js +212 -251
- package/dist/types/api.d.ts +1 -1
- package/dist/types/contracts/connessione.d.ts +1 -0
- package/dist/types/contracts/giornata.d.ts +1 -0
- package/dist/types/contracts/index.d.ts +3 -2
- package/dist/types/contracts/manifest.d.ts +6 -41
- package/dist/types/contracts/network-budget.d.ts +53 -0
- package/dist/types/contracts/versioni.d.ts +0 -1
- package/dist/types/crew/index.d.ts +4 -0
- package/dist/types/handshake.d.ts +0 -4
- package/dist/types/{overlay/host-bridge.d.ts → host/index.d.ts} +60 -37
- package/dist/types/index.d.ts +64 -50
- package/dist/types/node/index.d.ts +6 -23
- package/dist/types/protocollo.d.ts +1 -20
- package/dist/types/runtime/index.d.ts +4 -11
- package/dist/types/runtime/network-probe.d.ts +4 -0
- package/dist/types/server/index.d.ts +0 -10
- package/dist/types/stanza/nucleo.d.ts +8 -16
- package/dist/types/stanza/tipi.d.ts +4 -19
- package/dist/types/voce/index.d.ts +0 -1
- package/package.json +15 -17
- package/dist/overlay.d.ts +0 -1
- package/dist/overlay.js +0 -2157
- package/dist/overlay.js.map +0 -7
- package/dist/types/contracts/overlay.d.ts +0 -235
- package/dist/types/contracts/replay.d.ts +0 -83
- package/dist/types/overlay/bridge.d.ts +0 -3
- package/dist/types/overlay/i18n.d.ts +0 -128
- package/dist/types/overlay/index.d.ts +0 -9
- package/dist/types/overlay/locale.d.ts +0 -4
- package/dist/types/overlay/shortcut.d.ts +0 -4
- package/dist/types/overlay/styles.d.ts +0 -1
- package/dist/types/overlay/ui-model.d.ts +0 -53
- package/dist/types/overlay/ui.d.ts +0 -81
- package/dist/types/overlay/voice-panel.d.ts +0 -13
- package/dist/types/replay/index.d.ts +0 -65
- package/dist/types/session/index.d.ts +0 -49
- package/dist/types/session/resume.d.ts +0 -13
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
The game kit for [Caisual](https://caisual.com), a free home for small browser games with multiplayer built in.
|
|
4
4
|
|
|
5
|
-
The kit gives a published game a stable player identity, cloud saves, a daily challenge seed,
|
|
5
|
+
The kit gives a published game a stable player identity, cloud saves, a daily challenge seed, rooms with server-owned state, voice, matchmaking, and friends. It is one JavaScript module with no dependencies and never touches the page: the game fills the window and draws its own menu, lobby and results.
|
|
6
6
|
|
|
7
7
|
## Client
|
|
8
8
|
|
|
@@ -14,14 +14,11 @@ npm install @caisual/kit
|
|
|
14
14
|
import { caisual } from '@caisual/kit';
|
|
15
15
|
|
|
16
16
|
const c = await caisual.connect();
|
|
17
|
-
console.log(c.player.name);
|
|
17
|
+
console.log(c.player.name, c.player.language);
|
|
18
18
|
|
|
19
|
-
c.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
23
|
-
});
|
|
24
|
-
c.session.ready();
|
|
19
|
+
const room = await c.room.create({ mode: null });
|
|
20
|
+
room.onState((state) => draw(state));
|
|
21
|
+
room.ready(true);
|
|
25
22
|
```
|
|
26
23
|
|
|
27
24
|
A published game can also load the same module from its own origin, without a bundler: `import { caisual } from '/__caisual/kit/v1.js'`.
|
|
@@ -45,7 +42,7 @@ export default defineGame({
|
|
|
45
42
|
|
|
46
43
|
- [Kit reference](https://caisual.com/kit.md): every call, event and limit.
|
|
47
44
|
- [Publishing guide](https://caisual.com/publish.md): the folder, the manifest and the CLI.
|
|
48
|
-
- [Guides](https://caisual.com/docs): rooms, voice, matchmaking,
|
|
45
|
+
- [Guides](https://caisual.com/docs): rooms, voice, matchmaking, friends, saves, versions, limits.
|
|
49
46
|
- [llms.txt](https://caisual.com/llms.txt): the index of every guide for coding agents.
|
|
50
47
|
|
|
51
48
|
Publish with [`@caisual/cli`](https://www.npmjs.com/package/@caisual/cli). Publishing is free; games run on caisual.com.
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './types/host/index.js';
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
function creaErrore(code, message, version = {}) {
|
|
3
|
+
return Object.assign(new Error(message), { name: "CaisualError", code, ...version });
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
// src/host/index.ts
|
|
7
|
+
function record(valore) {
|
|
8
|
+
return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
|
|
9
|
+
}
|
|
10
|
+
var CODICE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/;
|
|
11
|
+
function eMessaggioReady(value) {
|
|
12
|
+
return record(value)?.type === "caisual:ready";
|
|
13
|
+
}
|
|
14
|
+
function eRichiestaBiglietto(value) {
|
|
15
|
+
const data = record(value);
|
|
16
|
+
return data?.type === "caisual:ticket" && (data.aud === void 0 || data.aud === "portal" || data.aud === "live");
|
|
17
|
+
}
|
|
18
|
+
function stanzaDaMessaggio(value) {
|
|
19
|
+
const data = record(value);
|
|
20
|
+
if (data?.type !== "caisual:room") return void 0;
|
|
21
|
+
if (data.room === null) return null;
|
|
22
|
+
const room = record(data.room);
|
|
23
|
+
return typeof room?.code === "string" && CODICE.test(room.code) ? { code: room.code } : void 0;
|
|
24
|
+
}
|
|
25
|
+
function creaPonteOspite(input) {
|
|
26
|
+
let port = null, instance = null;
|
|
27
|
+
let disposed = false, legacyReady = true;
|
|
28
|
+
let polling = null, pollingEnd = null;
|
|
29
|
+
let fermaCrew = null;
|
|
30
|
+
const stopPolling = () => {
|
|
31
|
+
if (polling !== null) input.finestra.clearInterval(polling);
|
|
32
|
+
if (pollingEnd !== null) input.finestra.clearTimeout(pollingEnd);
|
|
33
|
+
polling = pollingEnd = null;
|
|
34
|
+
};
|
|
35
|
+
const askReady = () => {
|
|
36
|
+
if (!disposed && input.frame.src !== "") input.frame.contentWindow?.postMessage({ type: "caisual:ready?" }, input.origineGioco);
|
|
37
|
+
};
|
|
38
|
+
const poll = () => {
|
|
39
|
+
stopPolling();
|
|
40
|
+
polling = input.finestra.setInterval(askReady, 500);
|
|
41
|
+
pollingEnd = input.finestra.setTimeout(stopPolling, 1e4);
|
|
42
|
+
askReady();
|
|
43
|
+
};
|
|
44
|
+
const loaded = () => {
|
|
45
|
+
legacyReady = true;
|
|
46
|
+
poll();
|
|
47
|
+
};
|
|
48
|
+
const listen = (event) => {
|
|
49
|
+
if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow || !eMessaggioReady(event.data)) return;
|
|
50
|
+
const data = record(event.data);
|
|
51
|
+
const nextInstance = typeof data.instance === "string" && data.instance.length <= 128 ? data.instance : null;
|
|
52
|
+
if (port && (nextInstance !== null ? nextInstance === instance : !legacyReady)) return;
|
|
53
|
+
stopPolling();
|
|
54
|
+
legacyReady = false;
|
|
55
|
+
instance = nextInstance;
|
|
56
|
+
fermaCrew?.();
|
|
57
|
+
fermaCrew = null;
|
|
58
|
+
port?.close();
|
|
59
|
+
input.onRoom(null);
|
|
60
|
+
const channel = input.creaCanale?.() ?? new MessageChannel();
|
|
61
|
+
const currentPort = channel.port1;
|
|
62
|
+
port = currentPort;
|
|
63
|
+
const current = () => !disposed && port === currentPort;
|
|
64
|
+
currentPort.onmessage = (event2) => {
|
|
65
|
+
if (!current()) return;
|
|
66
|
+
const data2 = record(event2.data);
|
|
67
|
+
if (eRichiestaBiglietto(data2)) {
|
|
68
|
+
const aud = data2?.aud === "live" ? "live" : "portal";
|
|
69
|
+
void input.rinnova(aud).then((ticket) => {
|
|
70
|
+
if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, ticket });
|
|
71
|
+
}).catch(() => {
|
|
72
|
+
if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, error: "offline" });
|
|
73
|
+
});
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (data2?.type === "caisual:reload") {
|
|
77
|
+
const target = record(data2.target);
|
|
78
|
+
const code = typeof target?.code === "string" && CODICE.test(target.code) ? target.code : void 0;
|
|
79
|
+
const roomId = typeof target?.roomId === "string" && /^g[1-9][0-9]*-[1-9][0-9]*\.[a-z0-9]{16}$/.test(target.roomId) ? target.roomId : void 0;
|
|
80
|
+
input.reload?.(code || roomId ? { code, roomId } : void 0);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const room = stanzaDaMessaggio(data2);
|
|
84
|
+
if (room !== void 0) {
|
|
85
|
+
input.onRoom(room);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (data2?.type === "caisual:crew") gestisciCrew(data2, currentPort, current);
|
|
89
|
+
};
|
|
90
|
+
currentPort.start();
|
|
91
|
+
input.frame.contentWindow?.postMessage({
|
|
92
|
+
type: "caisual:hello",
|
|
93
|
+
n: input.n,
|
|
94
|
+
ticket: input.ticket,
|
|
95
|
+
live: input.origineLive,
|
|
96
|
+
invite: input.invite,
|
|
97
|
+
...input.language ? { language: input.language } : {},
|
|
98
|
+
...input.languagePreferences ? { languagePreferences: [...input.languagePreferences] } : {},
|
|
99
|
+
...input.gameLanguages ? { gameLanguages: [...input.gameLanguages] } : {}
|
|
100
|
+
}, input.origineGioco, [channel.port2]);
|
|
101
|
+
};
|
|
102
|
+
function gestisciCrew(data, porta, current) {
|
|
103
|
+
const crew = input.crew;
|
|
104
|
+
if (!crew) {
|
|
105
|
+
if (data.op === "subscribe") porta.postMessage({ type: "caisual:crew-state", state: null });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (data.op === "subscribe") {
|
|
109
|
+
const invia = () => {
|
|
110
|
+
if (current()) porta.postMessage({ type: "caisual:crew-state", state: crew.getSnapshot() });
|
|
111
|
+
};
|
|
112
|
+
fermaCrew?.();
|
|
113
|
+
fermaCrew = crew.subscribe(invia);
|
|
114
|
+
invia();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const player = typeof data.player === "string" ? data.player : null;
|
|
118
|
+
const party = typeof data.party === "string" ? data.party : null;
|
|
119
|
+
if (data.op === "party") {
|
|
120
|
+
if (data.action === "create") crew.party.create();
|
|
121
|
+
else if (data.action === "leave") crew.party.leave();
|
|
122
|
+
else if (data.action === "invite" && player) crew.party.invite(player);
|
|
123
|
+
else if (data.action === "kick" && player) crew.party.kick(player);
|
|
124
|
+
else if (data.action === "accept" && party) crew.party.accept(party);
|
|
125
|
+
else if (data.action === "decline" && party) crew.party.decline(party);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (data.op === "follow" && typeof data.slug === "string" && typeof data.code === "string" && CODICE.test(data.code)) {
|
|
129
|
+
crew.follow(data.slug, data.code);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
input.finestra.addEventListener("message", listen);
|
|
133
|
+
input.frame.addEventListener?.("load", loaded);
|
|
134
|
+
poll();
|
|
135
|
+
return {
|
|
136
|
+
reload() {
|
|
137
|
+
input.reload?.();
|
|
138
|
+
},
|
|
139
|
+
/** Il gioco e' collegato: serve al sito per sapere se il ponte ha agganciato il documento. */
|
|
140
|
+
get collegato() {
|
|
141
|
+
return port !== null;
|
|
142
|
+
},
|
|
143
|
+
invia(message) {
|
|
144
|
+
if (!port || disposed) throw creaErrore("offline", "The game bridge is not connected.");
|
|
145
|
+
port.postMessage(message);
|
|
146
|
+
},
|
|
147
|
+
dispose() {
|
|
148
|
+
disposed = true;
|
|
149
|
+
stopPolling();
|
|
150
|
+
fermaCrew?.();
|
|
151
|
+
fermaCrew = null;
|
|
152
|
+
port?.close();
|
|
153
|
+
port = null;
|
|
154
|
+
input.finestra.removeEventListener("message", listen);
|
|
155
|
+
input.frame.removeEventListener?.("load", loaded);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function avviaHandshake(input) {
|
|
160
|
+
const bridge = creaPonteOspite(input);
|
|
161
|
+
return () => bridge.dispose();
|
|
162
|
+
}
|
|
163
|
+
export {
|
|
164
|
+
avviaHandshake,
|
|
165
|
+
creaPonteOspite,
|
|
166
|
+
eMessaggioReady,
|
|
167
|
+
eRichiestaBiglietto,
|
|
168
|
+
stanzaDaMessaggio
|
|
169
|
+
};
|
package/dist/kit.js
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
1
|
-
// Caisual game kit v0.
|
|
2
|
-
var St=["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"],Rt=new Set(St),kt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,xt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function pe(n){return n.length>=3&&n.length<=32&&kt.test(n)||xt.test(n)}function $e(n){return Rt.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 xe(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function Mt(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 De(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 Mt(r,r))if(t.includes(s))return s;return t[0]}function Ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function qe(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 he(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var I=24;var Ct=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"]),Pt=new Set(["keyboard","mouse","touch","gamepad"]),It=new Set(["desktop","mobile","both"]),Tt=new Set(["landscape","portrait"]),Ot=new Set(["public","unlisted"]),Et=new Set(["none","room","team","proximity"]),_t=new Set(["light","medium","heavy"]),zt=/^[a-z0-9-]+$/,Ge=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Vt=/^[a-z0-9][a-z0-9-]{0,31}$/,Lt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Je(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 $t(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 Me(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 fe(n,e,t,i,r){if(n[e]===void 0)return;let s=(g,d)=>{if(typeof g!="string"||g.trim().length===0||g.trim().length>t||/[\r\n\u0000-\u001f]/.test(g)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return g.trim()},o=n[e],a=i?`${i}.${e}`:e;if(typeof o=="string")return s(o,a);let l=J(o);if(!l||Object.keys(l).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[g,d]of Object.entries(l)){let u=G(g);if(!u){r.push(`${a}.${g}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,u)&&r.push(`${a}.${g}: duplicate language.`);let v=s(d,`${a}.${g}`);v!==void 0&&(m[u]=v)}return m}function Ce(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let h of Object.keys(t))At.has(h)||e.push(`${h}: 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=Me(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(pe(i)?$e(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=Me(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===""?"":fe(t,"description",500,"",e)??"",o={cover:"",card:"",icon:""},a=new Set;for(let h of["cover","card","icon"]){let f=t[h];if(f==null)e.push(`${h}: is required.`);else if(typeof f!="string"||!Je(f))e.push(`${h}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\.(png|jpe?g|webp)$/i.test(f)||e.push(`${h}: must be a PNG, JPEG or WebP file.`);let O=decodeURIComponent(f);a.has(O)&&e.push(`${h}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(O),o[h]=f}}let{cover:l,card:m,icon:g}=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[h,f]of t.screenshots.entries())typeof f!="string"||!Je(f)?e.push(`screenshots[${h}]: 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[h,f]of t.tags.entries())typeof f!="string"||f.length>24||!zt.test(f)?e.push(`tags[${h}]: must be 1-24 lowercase letters, digits, or hyphens.`):u.push(f)}let v=Me(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 M=[];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[h,f]of t.languages.entries()){let O=G(f);O?M.includes(O)?e.push(`languages[${h}]: duplicate language ${O}.`):M.push(O):e.push(`languages[${h}]: must be a BCP 47 language tag.`)}M.includes("en")||e.push("languages: English is always required alongside the game's own languages.");let k=M[0]??v;if(typeof s=="object")for(let h of Object.keys(s))M.includes(h)||e.push(`description.${h}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&v.toLowerCase()!==k.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"||!It.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"||!Tt.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[h,f]of t.input.entries())typeof f!="string"||!Pt.has(f)?e.push(`input[${h}]: must be keyboard, mouse, touch, or gamepad.`):j.includes(f)?e.push(`input[${h}]: duplicate value ${f}.`):j.push(f);let z="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!Ot.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[h,f]of t.network.entries())typeof f!="string"||!$t(f)?e.push(`network[${h}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(f)?e.push(`network[${h}]: 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 h=J(t.requires);if(h===null)e.push("requires: must be an object.");else{for(let f of Object.keys(h))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(f)||e.push(`requires.${f}: unknown field.`);for(let f of["webgl2","webgpu","wasm","threads"])h[f]!==void 0&&(typeof h[f]!="boolean"?e.push(`requires.${f}: must be a boolean.`):U[f]=h[f]);h.memoryMb!==void 0&&(h.memoryMb!==null&&(!V(h.memoryMb,512,32768)||h.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):U.memoryMb=h.memoryMb),h.performance!==void 0&&(typeof h.performance!="string"||!_t.has(h.performance)?e.push("requires.performance: must be light, medium, or heavy."):U.performance=h.performance)}}let F={min:1,max:1};if(t.players!==void 0){let h=J(t.players);if(h===null)e.push("players: must be an object with min and max.");else{for(let f of Object.keys(h))f!=="min"&&f!=="max"&&e.push(`players.${f}: unknown field.`);V(h.min,1,I)||e.push(`players.min: must be an integer from 1 to ${I}.`),V(h.max,1,I)||e.push(`players.max: must be an integer from 1 to ${I} in manifest version 1.`),V(h.min,1,I)&&V(h.max,1,I)&&(h.min>h.max?e.push("players.max: must be greater than or equal to players.min."):F={min:h.min,max:h.max})}}let T=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):T=t.lobby);let K=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):K=t.persistent);let C=t.replays===!0;t.replays!==void 0&&typeof t.replays!="boolean"&&e.push("replays: must be a boolean.");let ne={delayMs:Ct};if(t.spectators===!1||t.spectators===null)ne=null;else if(t.spectators!==void 0&&t.spectators!==!0){let h=J(t.spectators);if(h===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let f of Object.keys(h))f!=="delayMs"&&e.push(`spectators.${f}: unknown field.`);V(h.delayMs,0,3e4)?ne={delayMs:h.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let P=null;if(t.overlay!==void 0&&t.overlay!==null){let h=J(t.overlay);if(h===null)e.push("overlay: must be an object or null.");else{for(let f of Object.keys(h))["version","accent"].includes(f)||e.push(`overlay.${f}: unknown field.`);h.version!==1&&e.push("overlay.version: must be exactly 1."),h.accent!==void 0&&(typeof h.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(h.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),P={version:1,...typeof h.accent=="string"?{accent:h.accent}:{}}}}let ee={};if(t.boards!==void 0){let h=J(t.boards);if(h===null)e.push("boards: must be an object of board ids.");else{Object.keys(h).length>je&&e.push(`boards: at most ${je} boards.`);for(let[f,O]of Object.entries(h)){let b=!0;Lt.test(f)||(e.push(`boards.${f}: invalid board id.`),b=!1);let S=J(O);if(S===null){e.push(`boards.${f}.source: must be "client" or "server".`);continue}for(let E of Object.keys(S))["source","label","periods","day"].includes(E)||e.push(`boards.${f}.${E}: unknown field.`);S.source!=="client"&&S.source!=="server"&&(e.push(`boards.${f}.source: must be "client" or "server".`),b=!1),S.day!==void 0&&S.day!=="submit"&&S.day!=="start"&&e.push(`boards.${f}.day: must be "submit" or "start".`),S.day==="start"&&S.source!=="server"&&e.push(`boards.${f}.day: start requires source "server".`);let A=fe(S,"label",48,`boards.${f}`,e),L=["all-time"];S.periods!==void 0&&(!Array.isArray(S.periods)||S.periods.length<1||S.periods.length>2||S.periods.some(E=>E!=="daily"&&E!=="all-time")||new Set(S.periods).size!==S.periods.length?e.push(`boards.${f}.periods: must contain daily, all-time, or both without duplicates.`):L=[...S.periods]),b&&Object.defineProperty(ee,f,{value:{source:S.source,periods:L,...S.day===void 0?{}:{day:S.day},...A===void 0?{}:{label:A}},enumerable:!0,configurable:!0,writable:!0})}}}let H=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let h=new Set;for(let[f,O]of t.roles.entries()){let b=J(O);if(b===null){e.push(`roles[${f}]: must be an object.`);continue}for(let y of Object.keys(b))["id","min","max","label"].includes(y)||e.push(`roles[${f}].${y}: unknown field.`);let S=b.id,A=b.min,L=b.max,E=!0;typeof S!="string"||S.length>32||!Ge.test(S)?(e.push(`roles[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),E=!1):h.has(S)?(e.push(`roles[${f}].id: duplicate role ${S}.`),E=!1):h.add(S),V(A,0,I)||(e.push(`roles[${f}].min: must be an integer from 0 to ${I}.`),E=!1),L!==void 0&&!V(L,0,I)&&(e.push(`roles[${f}].max: must be an integer from 0 to ${I} when present.`),E=!1),typeof A=="number"&&typeof L=="number"&&A>L&&(e.push(`roles[${f}].max: must be greater than or equal to min.`),E=!1);let c=fe(b,"label",32,`roles[${f}]`,e);E&&H.push({id:S,min:A,...L===void 0?{}:{max:L},...c===void 0?{}:{label:c}})}}let re=null;if(t.teams!==void 0&&t.teams!==null){let h=J(t.teams);if(h===null)e.push("teams: must be null or an object with min and max.");else{for(let f of Object.keys(h))f!=="min"&&f!=="max"&&e.push(`teams.${f}: unknown field.`);V(h.min,2,I)||e.push(`teams.min: must be an integer from 2 to ${I}.`),V(h.max,2,I)||e.push(`teams.max: must be an integer from 2 to ${I}.`),V(h.min,2,I)&&V(h.max,2,I)&&(h.min>h.max?e.push("teams.max: must be greater than or equal to teams.min."):re={min:h.min,max:h.max})}}let Y="none";t.voice!==void 0&&(typeof t.voice!="string"||!Et.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):Y=t.voice);let Z=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let h=new Set;for(let[f,O]of t.modes.entries()){let b=J(O);if(b===null){e.push(`modes[${f}]: must be an object.`);continue}for(let y of Object.keys(b))["id","players","lobby","matchmaking","execution","label","instructions"].includes(y)||e.push(`modes[${f}].${y}: unknown field.`);if(typeof b.id!="string"||b.id.length>32||!Ge.test(b.id)){e.push(`modes[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(h.has(b.id)){e.push(`modes[${f}].id: duplicate mode ${b.id}.`);continue}h.add(b.id);let S={id:b.id};for(let[y,w]of[["label",48],["instructions",160]]){let R=fe(b,y,w,`modes[${f}]`,e);R!==void 0&&(S[y]=R)}if(b.execution!==void 0&&(b.execution!=="local"&&b.execution!=="room"?e.push(`modes[${f}].execution: must be local or room.`):S.execution=b.execution),P!==null&&S.execution===void 0&&e.push(`modes[${f}].execution: is required with the standard overlay.`),b.players!==void 0){let y=`modes[${f}].players`,w=J(b.players);if(w===null)e.push(`${y}: must be an object with min and max.`);else{for(let R of Object.keys(w))R!=="min"&&R!=="max"&&e.push(`${y}.${R}: unknown field.`);V(w.min,1,I)||e.push(`${y}.min: must be an integer from 1 to ${I}.`),V(w.max,1,I)||e.push(`${y}.max: must be an integer from 1 to ${I}.`),V(w.min,1,I)&&V(w.max,1,I)&&(w.min>w.max?e.push(`${y}.max: must be greater than or equal to min.`):S.players={min:w.min,max:w.max})}}if(b.lobby!==void 0&&(typeof b.lobby!="boolean"?e.push(`modes[${f}].lobby: must be a boolean.`):S.lobby=b.lobby),S.execution==="local"){let y=S.players??F;(y.min!==1||y.max!==1)&&e.push(`modes[${f}].players: local execution requires min and max to be 1.`),(S.lobby??T)&&e.push(`modes[${f}].lobby: local execution requires false.`),b.matchmaking!==void 0&&e.push(`modes[${f}].matchmaking: local execution cannot use matchmaking.`)}if(b.matchmaking===void 0){Z.push(S);continue}let A=J(b.matchmaking);if(A===null){e.push(`modes[${f}].matchmaking: must be an object.`);continue}for(let y of Object.keys(A))["key","timeoutMs","defaults"].includes(y)||e.push(`modes[${f}].matchmaking.${y}: unknown field.`);let L=!0,E=[];if(!Array.isArray(A.key)||A.key.length<1||A.key.length>8)e.push(`modes[${f}].matchmaking.key: must contain from 1 to 8 fields.`),L=!1;else for(let[y,w]of A.key.entries())typeof w!="string"||!Vt.test(w)?(e.push(`modes[${f}].matchmaking.key[${y}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),L=!1):E.includes(w)?(e.push(`modes[${f}].matchmaking.key[${y}]: duplicate field ${w}.`),L=!1):E.push(w);V(A.timeoutMs,1e3,3e5)||(e.push(`modes[${f}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),L=!1);let c;if(A.defaults!==void 0){let y=J(A.defaults);if(y===null||Object.keys(y).length!==E.length||E.some(w=>!Object.hasOwn(y,w)))e.push(`modes[${f}].matchmaking.defaults: must contain exactly the declared key fields.`);else{c={};for(let[w,R]of Object.entries(y))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${f}].matchmaking.defaults.${w}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(c,w,{value:R,enumerable:!0})}}L&&Z.push({...S,matchmaking:{...c===void 0?{}:{defaults:c},key:E,timeoutMs:A.timeoutMs}})}}return P!==null&&Z.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:P,id:i,name:r,description:s,cover:l,card:m,icon:g,screenshots:d,tags:u,languages:M,language:k,platform:N,orientation:_,input:j,visibility:z,network:B,requires:U,players:F,lobby:T,persistent:K,replays:C,spectators:ne,boards:ee,roles:H,teams:re,voice:Y,modes:Z}}}function Dt(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 Be(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Nt(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 Ue(n,e=1500){let t=n??globalThis,i=Nt(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let g=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(g!==null){i.webgl2=!0,i.gpu="hardware",Be(g);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Be(d))}catch{i.webgl2=!1,i.gpu="none"}}),s=Promise.resolve().then(async()=>{let m;try{let g=t.navigator?.gpu;if(g===void 0)return;let d=await g.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}}),l;return await Promise.race([Promise.all([r,s,o,a]),new Promise(m=>{l=setTimeout(m,Math.max(0,e))})]),l!==void 0&&clearTimeout(l),{...i,tier:Dt(i)}}function Ae(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var ce=/^[A-Za-z0-9_-]{22}$/;function Jt(n,e=null,t=null,i=null){let r=Ce(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");let{boards:s,...o}=r.manifest;return{manifest:o,coverUrl:e,iconUrl:i,invite:t}}function D(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function qt(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))&&Ce(t.manifest).ok}function Fe(n){return qt(n)?{v:1,epoch:n.epoch,configuration:Jt(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Bt(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 Ie(n){let e=D(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Bt(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 We(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 Ie(t);default:return!1}}function He(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 l=t(a);!l||typeof l.playerId!="string"||!r.has(l.playerId)||s.has(l.playerId)||(s.add(l.playerId),o.push({playerId:l.playerId,...typeof l.score=="number"&&Number.isFinite(l.score)?{score:l.score}:{},...typeof l.rank=="number"&&Number.isSafeInteger(l.rank)&&l.rank>0?{rank:l.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 ue(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Ut(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 ge(n,e,t,i){async function r(s,o,a,l){let m=new Headers({Authorization:`Bearer ${a}`}),g;if(l!==void 0){m.set("Content-Type","application/json");try{g=JSON.stringify(l)}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:g,credentials:"omit"})}catch{throw $()}}return async function(o,a,l,m=!1){let g;try{g=m?await i.rinnova():await i.ottieni()}catch{throw $()}let d=await r(o,a,g,l);if(d.status===401){try{g=await i.rinnova()}catch{throw $()}d=await r(o,a,g,l)}if(!d.ok)throw await Ut(d);try{return await d.json()}catch{throw p("internal_error","The service returned an invalid response.")}}}var Te=.02,Ke=300,Ft=200,Ye=3e3,Wt=1e4,Ht=[1e3,2e3,4e3];function Ze(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Kt(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 ye=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??Kt(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=Ze(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,Ze(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 l of s.getTracks())l.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,l=i.localDescription?.sdp;if(a===null||l===void 0)throw p("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:l,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."))},Wt)})}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,g]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===g.session&&d.track===g.track||(r.push(g),this.riproduzioni.has(m)||g.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(g.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(ue(m)!=="not_allowed")throw m;for(let g of s)this.negati.add(g.id);return}if(o.op!=="subscribe")throw p("voice_error","The voice service returned an invalid response.");for(let m of o.tracks){let g=s.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&g!==void 0&&this.negati.add(g.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||g===void 0)&&(this.midGiocatori.set(m.mid,g.id),this.sfuAttive.set(g.id,{session:g.session,track:g.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:o.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let l=t.localDescription?.sdp;if(l===void 0)throw p("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:l}),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 l=await r.pc.createAnswer();await r.pc.setLocalDescription(l);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(ue(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<Ye})}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,Ye-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 l=null;try{l=this.richiediAudioContext().createAnalyser(),l.fftSize=256,o.connect(l)}catch{l=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:l,audio:m,track:t,receiver:i});let g=this.sfuAttive.get(e);g!==void 0&&(g.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(),Ft)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Te),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=Ke;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)>Te?this.ultimoAudio.set(s.id,e.ora()):(o?.analyser===null||o?.analyser===void 0)&&(o?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Te)&&this.ultimoAudio.set(s.id,e.ora());let a=!s.muted&&e.ora()-(this.ultimoAudio.get(s.id)??0)<=Ke;(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=Ht[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 te=1,Qe=[1e3,2e3,4e3,8e3],Yt=6e4,Zt=5e3,Qt=2e4,Xt=500,ei=2e3,ti=new Set([4003,4004,4005,4006,4008,4009]);function X(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Xe(n){let e=X(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ii(n){let e=X(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function ni(n){let e=X(n),t=X(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 Q(n){return JSON.parse(JSON.stringify(n))}function Oe(n,e){let t=Q(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Q(i.value);continue}let r=t,s=i.path;for(let a=0;a<s.length-1;a++){let l=s[a];if(Array.isArray(r)){if(typeof l!="number"||l>=r.length)return{ok:!1};r=r[l]}else{let m=X(r);if(m===null||typeof l!="string"||!Object.hasOwn(m,l))return{ok:!1};r=m[l]}}let o=s.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof o!="number"||o>=r.length)return{ok:!1};r[o]=Q(i.value)}else{let a=X(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:Q(i.value),writable:!0})}}return{ok:!0,state:t}}function ri(n){let e=ge(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,l,m)=>{try{return await e(o,a,{...X(l),n:n.n},m)}catch(g){if(g instanceof Error&&"code"in g&&["version_outdated","version_mismatch"].includes(String(g.code))){let d=X(l),u=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\s-]/g,""):void 0,v=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(g,g.code==="version_mismatch"?{code:u,roomId:v,watch:o==="/rooms/watch"}:void 0)}throw g}};async function i(o,a,l=!1){let m=await t(o,"POST",a,l);if(!Xe(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(!ni(a))throw p("internal_error","The matchmaking service returned an invalid response.");return a}async function s(o,a=!1){let l=await t("/rooms/watch","POST",o,a);if(!ii(l))throw p("internal_error","The room service returned an invalid response.");return l}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 ve=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((l,m)=>{this.risolviPronta=l,this.rifiutaPronta=m}),this.voice=new ye({invia:l=>this.invia(l),connessa:()=>this.socket?.readyState===te&&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!==te||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!==te||this.terminata||this.lasciata)return;let o=this.dipendenze.ora();if(o<this.ultimoInvioGioco+i||this.inviiGioco.filter(l=>o-l<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===te){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!==te)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!==te||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Zt:Qt;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===te)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=X(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,Q(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=Q(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=Q(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()},ei)),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=Q(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=Oe(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=Q(e),this.statoPubblico=Q(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==te)){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(ti.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,Qe.length-1),t=Qe[e];if(this.tempoRiconnessione+t>Yt){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()},Xt))}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 me(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 et(n,e){let t,i=new Set,r=ri({...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))},l=async d=>{let u=new ve(d.roomId,d.code,d.url,n,r,a);return await u.pronta(),u},m=async d=>{let u=new ve(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()}},g=(d,u)=>new Promise((v,M)=>{let k,N=!1,_=()=>{k.removeEventListener("message",T),k.removeEventListener("close",U),k.removeEventListener("error",F),u.signal?.removeEventListener("abort",B)},j=()=>{try{k.close(1e3)}catch{}},z=(K,C)=>{N||(N=!0,_(),C&&j(),M(K))};function B(){z(p("cancelled","The matchmaking search was cancelled."),!0)}function U(){z($(),!1)}function F(){z($(),!0)}function T(K){let C=null;try{C=typeof K.data=="string"?X(JSON.parse(K.data)):null}catch{}if(C===null||typeof C.t!="string"){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}if(C.t==="waiting"){if(!Number.isInteger(C.players)||!Number.isInteger(C.min)||!Number.isInteger(C.max)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}try{u.onWaiting?.({players:C.players,min:C.min,max:C.max})}catch{}return}if(C.t==="matched"){if(!Xe(C)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}N=!0,_(),j(),v(C);return}if(C.t==="no_match"){z(p("no_match","No match was found before the timeout."),!0);return}if(C.t==="error"){z(p(typeof C.code=="string"?C.code:"internal_error",typeof C.message=="string"?C.message:"The matchmaking service could not complete the search."),!0);return}C.t!=="pong"&&z(p("internal_error","The matchmaking service sent an invalid message."),!0)}try{k=n.apriSocket(d)}catch{M($());return}k.addEventListener("message",T),k.addEventListener("close",U),k.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 l(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 l(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 l(await g(v.url,d))}}}var W=()=>p("replay_invalid","The replay is incomplete or invalid.");function q(n,...e){for(let t of n)try{t(...e)}catch{}}function ae(n,e){return n.add(e),()=>{n.delete(e)}}var si={now:()=>performance.now(),setInterval:(n,e)=>globalThis.setInterval(n,e),clearInterval:n=>globalThis.clearInterval(n)},Ee=class{constructor(e,t,i=si){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 W();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 l=t[a];if(!Number.isFinite(l.at)||l.at<o||l.at>e.durationMs||l.message.t==="start")throw W();this.apply(l.message,!1),a%s===0&&this.checkpoints.push({cursor:a+1,at:l.at,picture:structuredClone(this.picture)}),o=l.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 ae(this.states,e)}onStatus(e){return ae(this.statuses,e)}onPlayers(e){return ae(this.playersListeners,e)}onMetadata(e){return ae(this.metadataListeners,e)}onConnection(e){return ae(this.connections,e)}onMessage(e){return()=>{}}onPlayback(e){return ae(this.playbackListeners,e)}apply(e,t){let i=this.picture;switch(e.t){case"start":throw W();case"snapshot":i.state=structuredClone(e.state);break;case"state":{if(i.room.tick!==e.base)throw W();let r=Oe(i.state,e.patch);if(!r.ok)throw W();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 W()}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 W();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 it(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||!ce.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 W();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 W();let l=await a.text();if(s+=new TextEncoder().encode(l).byteLength,s>i.bytes||!l.endsWith(`
|
|
3
|
-
`))throw W();for(let m of l.trimEnd().split(`
|
|
4
|
-
`))r.push(JSON.parse(m))}if(s!==i.bytes)throw W();try{return new Ee(i,r)}catch{throw W()}}var ai=["en","it","es","fr","de","pt","ja"];function nt(n){let e=G(n);return e&&ai.includes(e.split("-")[0])?e:"en"}function rt(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();Ne(a)&&(s=a)}}catch{}return(o,a={})=>Object.hasOwn(s,o)?s[o].replace(/\{([^{}]+)\}/g,(m,g)=>Object.hasOwn(a,g)?String(a[g]):m):o})())}var ot="caisual-session-v1";function st(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 at(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(ot,a),i=!1}catch(l){throw i=!0,l}finally{e()}}),r},o=(async()=>{try{let a=await n.get(ot),l=D(a);if(l?.version===1&&l.imported===!0)t=st(l.resume);else{let m=await n.get("resume");t=st(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 ie(n,e){for(let t of n)try{t(e)}catch{}}function lt(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,l=0,m=0,g=null,d=null,u=null,v=null,M=[],k=!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,T=null,K=()=>({local:i===null,rooms:i===null&&t,overlay:r,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function C(){if(o.kind!=="room"||!s||s.voice==="none")return null;let c=o.room,y=c.voice;return!y||y.mode==="none"||c.players.find(w=>w.id===c.you)?.role==="spectator"?null:{mode:y.mode,state:y.state,mic:y.mic,muted:y.muted,speaking:y.speaking,peers:y.peers.map(({id:w,mic:R,muted:x,speaking:se,volume:ke})=>({id:w,mic:R,muted:x,speaking:se,volume:ke}))}}function ne(){let c=o.kind==="room"||o.kind==="watch"?o.room:null,y=c?.metadata.configuration,w=c?He(c.result,c.players.map(x=>x.id)):null,R=s&&c&&(c.mode===null||s.modes.some(x=>x.id===c.mode))?qe(s,c.mode):{players:{min:1,max:1},lobby:!1};return{kind:g??(o.kind==="idle"?a?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:g?d:o.kind==="local"?o.mode:c?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:a,capabilities:K(),room:c?{...c===i?{replay:i.playback}:{},...c.metadata.replayId?{replayId:c.metadata.replayId}:{},...c.metadata.rematch?.keepSetup||c.metadata.rematch?.autoStart?{rematch:c.metadata.rematch}:{},code:c.code,mode:c.mode,status:c.status,host:c.host,you:o.kind==="room"?o.room.you:null,players:c.players.map(x=>({id:x.id,name:x.name,guest:x.guest,role:x.role,team:x.team,ready:x.ready,connected:x.connected})),...w?{result:w}:{},countdownAt:c.countdownAt,connection:c.connection,closedCode:c.metadata.closedCode,limits:{...y?.players??R.players},lobby:y?.lobby??R.lobby,persistent:y?.persistent??s?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:y?.requestRole??!1}:null,voice:g?null:C(),waiting:u?{...u}:null,resume:T?.value??null,resumeError:T?.error??!1}}function P(){if(k)return;let c=ne(),y=JSON.stringify(c);y!==N&&(N=y,ie(B,c))}function ee(){ie(j,{...o}),P()}function H(){if(o.kind!=="room")throw p("no_room","There is no active player room.");return o.room}function re(){let c=H();if(c.players.find(y=>y.id===c.you)?.role==="spectator")throw p("spectator","Spectators cannot use voice controls.");if(!s||s.voice==="none"||c.voice.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");return c.voice}function Y(){l++,v?.abort(),v=null,g=null,u=null,P()}function Z(c){M.splice(0).forEach(y=>y()),(o.kind==="room"||o.kind==="watch")&&(c?o.room.disconnect():o.room.leave()),o={kind:"idle"},ee()}async function h(c){T?.value?.code===c&&await T.set(null).catch(()=>{})}async function f(c,y,w){if(w!==l||k)throw c.leave(),p("cancelled","The operation was cancelled.");Z(!1),o=y?{kind:"watch",room:c,id:String(++m)}:{kind:"room",room:c,id:String(++m)};let R=c;if(M=[R.onPlayers(P),R.onMetadata(()=>{R.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===R?(M.splice(0).forEach(x=>x()),!y&&R.metadata.closedCode===1e3&&h(R.code),o={kind:"idle"},ee()):P()}),R.onStatus(()=>{P(),!y&&R.connection==="ended"&&h(R.code)})],c===i&&M.push(i.onPlayback(P)),!y){let x=c,se=o.id;x.voice&&M.push(x.voice.onState(P),x.voice.onPeers(P)),M.push(x.onError(ke=>ie(F,{sessionId:se,error:{...ke}})))}return g=null,u=null,ee(),!y&&T&&R.connection!=="ended"&&await T.set({version:1,code:R.code,mode:R.mode,updatedAt:n.time.now()}).catch(()=>{}),c}async function O(c,y,w,R=!1){Y();let x=l;v=new AbortController,g=c,d=y,P();try{let se=await w(v.signal,x);if(await f(se,R,x),x!==l||k)throw p("cancelled","The operation was cancelled.");return se}finally{x===l&&(g=null,u=null,v=null,P())}}let b=n.room,S=b.onError(c=>{!r||k||(c.code==="version_mismatch"?b.reload():c.code==="version_outdated"&&ie(F,{sessionId:o.kind==="idle"?null:o.id,error:c}))}),A=i||!r?b:{invited:b.invited,reload:()=>b.reload(),onError:c=>b.onError(c),create(c){return s&&he(s,c.mode)?Promise.reject(p("invalid_request","Local modes cannot create rooms.")):O("attaching",c.mode,()=>b.create(c))},join(c){return O("attaching",null,()=>b.join(c))},watch(c){return O("attaching",null,()=>b.watch(c),!0)},match(c){return s&&he(s,c.mode)?Promise.reject(p("invalid_request","Local modes cannot use matchmaking.")):O("matching",c.mode,(y,w)=>{let R=()=>{l===w&&Y()};return c.signal?.addEventListener("abort",R,{once:!0}),c.signal?.aborted&&R(),b.match({...c,signal:y,onWaiting(x){w===l&&(u={...x},P(),c.onWaiting?.(x))}}).finally(()=>c.signal?.removeEventListener("abort",R))})}};return r&&!i&&(T=at(n.save,P)),i&&(a=!0,f(i,!0,l)),{session:{get current(){return{...o}},get capabilities(){return K()},onChange(c){return j.add(c),ie(new Set([c]),{...o}),()=>{j.delete(c)}},ready(){k||a||(a=!0,P())},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"},ee())}},overlay:{open(c){if(!["home","room","invite","friends","voice"].includes(c))throw p("invalid_request","Unknown overlay panel.");r&&ie(U,c)},onChange(c){return z.add(c),ie(new Set([c]),structuredClone(_)),()=>{z.delete(c)}}},rooms:A,snapshot:ne,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(c){return B.add(c),c(ne()),()=>{B.delete(c)}},onOpen(c){return U.add(c),()=>{U.delete(c)}},onError(c){return F.add(c),()=>{F.delete(c)}},async execute(c){if(!r)throw p("overlay_disabled","This game uses its own room flow.");if(c.op==="overlay.view"){if(!Ie(c.args))throw p("invalid_request","The overlay geometry is invalid.");if(_={...structuredClone(c.args),safeArea:{top:0,right:0,bottom:0,left:0,...c.args.safeArea}},typeof document<"u")for(let[y,w]of Object.entries(_.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${y}`,`${w}px`);ie(z,structuredClone(_));return}if(c.sessionId!==void 0&&c.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(c.op.startsWith("replay.")&&(!i||o.kind!=="watch"||o.room!==i||c.sessionId!==o.id))throw p("session_replaced","The replay is no longer active.");if(i&&!c.op.startsWith("replay.")&&!["session.leave","session.disconnect"].includes(c.op))throw p("replay_readonly","Replays are read only.");if(c.op.startsWith("voice.")&&c.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(c.op){case"replay.play":i.play();return;case"replay.pause":i.pause();return;case"replay.seek":i.seek(c.args.positionMs);return;case"replay.speed":i.speed(c.args.speed);return;case"local.start":{if(!s||!he(s,c.args.mode))throw p("invalid_mode","This is not a local mode.");Y();let y=l;if(o.kind==="room"&&await h(o.room.code),y!==l||k)throw p("cancelled","The operation was cancelled.");Z(!1),o={kind:"local",id:String(++m),mode:c.args.mode,status:"playing"},ee();return}case"room.create":await A.create(c.args);return;case"room.join":await A.join(c.args.code);return;case"room.watch":await A.watch(c.args.code);return;case"room.match":{let y=s?.modes.find(R=>R.id===c.args.mode),w=c.args.key??y?.matchmaking?.defaults;if(!w)throw p("invalid_request","Matchmaking needs a complete key.");await A.match({mode:c.args.mode,key:w});return}case"voice.join":{let y=H();if(await re().join(),o.kind!=="room"||o.room!==y)throw p("session_replaced","The active session changed.");P();return}case"voice.mute":re().mute(c.args.muted),P();return;case"voice.leave":re().leave(),P();return;case"voice.setVolume":{let y=re();if(!y.peers.some(w=>w.id===c.args.playerId))throw p("voice_peer_missing","This voice participant is no longer available.");y.setVolume(c.args.playerId,c.args.volume),P();return}case"room.ready":H().ready(c.args.ready);return;case"room.role":H().setRole(c.args.role);return;case"room.requestRole":await H().requestRole(c.args.role);return;case"room.team":H().setTeam(c.args.team);return;case"room.start":H().start();return;case"room.restart":H().restart();return;case"session.cancel":Y();return;case"session.resume":{await O("attaching",null,async y=>{if(await T?.loaded,y.aborted)throw p("cancelled","The operation was cancelled.");if(!T?.value)throw p("no_resume","There is no saved room.");return b.join(T.value.code)});return}case"session.disconnect":{Y();let y=l;if(o.kind==="room"&&o.room.connection!=="ended"&&T&&await T.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),y!==l||k)throw p("cancelled","The operation was cancelled.");Z(!0);return}case"session.leave":{Y();let y=l;if(o.kind==="room"&&await h(o.room.code),y!==l||k)throw p("cancelled","The operation was cancelled.");Z(!1);return}}},dispose(){S(),Y(),Z(!0),k=!0,j.clear(),z.clear(),B.clear(),U.clear(),F.clear()}}}function ct(n,e,t){let i=!0,r=!1,s=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),o=a=>{let l=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||l?.closest?.('input,textarea,select,[contenteditable="true"]')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",o,!0),()=>{s(),n.removeEventListener("keydown",o,!0)}}function ut(n,e,t){let i=!1,r=0,s=0,o=0,a=new Map,l=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[ct(window,t.overlay,()=>l({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>l({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>l({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:u})=>l({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:u}))],g=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(!We(u)){l({...v,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let M=JSON.stringify([u.op,u.args,u.sessionId]),k=a.get(u.requestId);if(k){k.fingerprint!==M?l({...v,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):k.response.then(l);return}if(Number(u.requestId)<=s||o>=32){l({...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:M,response:N}),N.then(_=>{if(o--,l(_),a.size>64)for(let j of a.keys())Number(j)<s-64&&a.delete(j)})};return n.addEventListener("message",g),n.start(),()=>{i=!0,n.removeEventListener("message",g),m.forEach(d=>d()),t.dispose(),a.clear()}}function dt(n,e,t){let i=ge(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(ue(s)==="not_found")return null;throw s}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves}}}function le(n){return(Math.floor(n/864e5)+1)*864e5}function be(n,e,t){let i=new Set,r={...n},s,o=!1;function a(){!i.size||s!==void 0||o||(s=setTimeout(l,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),s.unref?.())}async function l(){s=void 0,o=!0;try{let m=await t(),g=m.day!==r.day;if(r={...m},g)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{o=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:mt(n.seed),rng:()=>mt(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&s!==void 0&&(clearTimeout(s),s=void 0)}}}}function _e(n){return new Date(n).toISOString().slice(0,10)}async function ze(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 mt(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 we(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function pt(n,e){return we(n)?.type===e}function li(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 ft(n,e,t=3e3){return new Promise(i=>{let r=!1,s=globalThis.crypto.randomUUID(),o=g=>{r||(r=!0,n.removeEventListener("message",l),n.clearTimeout(m),i(g))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:s,overlayVersion:1},e)},l=g=>{if(g.origin!==e||g.source!==n.parent)return;if(pt(g.data,"caisual:ready?")){a();return}if(!pt(g.data,"caisual:hello"))return;let d=we(g.data),u=g.ports[0];if(typeof d?.ticket!="string"||!Ae(d.n)||u===void 0)return;u.start();let v=Fe(d.overlay),M=k=>Array.isArray(k)?k.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:M(d.languagePreferences),gameLanguages:M(d.gameLanguages),...typeof d.replay=="string"&&ce.test(d.replay)?{replay:d.replay}:{},ticket:d.ticket,n:d.n,live:li(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:u})};n.addEventListener("message",l);let m=n.setTimeout(()=>o(null),t);a()})}function ci(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=we(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function ui(n,e,t,i){return new Promise((r,s)=>{let o=!1,a=g=>{o||(o=!0,n.removeEventListener("message",l),e.clearTimeout(m),g===null?s(new Error("Ticket refresh timed out.")):r(g))},l=g=>{let d=we(g.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",l);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function Ve(n,e,t,i,r=3e3,s="portal"){let o=n,a=null,l=()=>{if(a!==null)return a;let g=ui(e,t,r,s).then(d=>(o=d,d)).finally(()=>{a===g&&(a=null)});return a=g,g};return{async ottieni(){if(o===null)return l();let m=ci(o);return m!==null&&m-i()<3e4?l():o},rinnova:l}}var oe="caisual:save:",di=/^[a-z0-9][a-z0-9_-]{0,31}$/;function Le(n){if(!di.test(n))throw p("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function ht(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function gt(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(oe)&&e.push(i.slice(oe.length))}return e}function mi(n,e){let t=()=>{if(n===null)throw $();return n};return{async set(i,r){Le(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(oe+i)===null&>(s).length>=64)throw p("save_limit","A game can store at most 64 save keys.");let l={value:r,bytes:a,updatedAt:e()};return s.setItem(oe+i,JSON.stringify(l)),{key:i,bytes:a,updatedAt:l.updatedAt}},async get(i){return Le(i),ht(t().getItem(oe+i))?.value??null},async remove(i){Le(i),t().removeItem(oe+i)},async list(){let i=t();return gt(i).flatMap(r=>{let s=ht(i.getItem(oe+r));return s===null?[]:[{key:r,bytes:s.bytes,updatedAt:s.updatedAt}]}).sort((r,s)=>r.key.localeCompare(s.key))}}}async function Se(n,e=null){let t=n.ora(),i=_e(t),r=await ze(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:be({day:i,seed:r,expiresAt:le(t)},n.ora,async()=>{let s=n.ora(),o=_e(s);return{day:o,seed:await ze(n.hostname,o,n.subtle),expiresAt:le(s)}}),time:{now:n.ora},save:mi(n.archivio,n.ora),room:me(e)}}function pi(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 fi(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function hi(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:fi(),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:()=>Ue()}}async function gi(n){let e=pi(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return yt(n);let i=await ft(n.finestra,e,n.timeoutHandshake);if(i===null)return yt(n);if(i.replay){let u=i.overlay?.configuration.manifest.id;if(!u)throw new Error("The replay game is missing.");let v=await it(n.fetcher,`${e}/api/replays/${encodeURIComponent(u)}/${i.replay}`),M=await Se(n),k=me();return M.connected=!0,M.room=Object.assign(v,{invited:null,reload:()=>k.reload(),onError:k.onError,create:k.create,join:k.join,match:k.match,watch:async()=>v}),Re(M,i,n,v)}let r=Ve(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),s=dt(e,n.fetcher,r),o=n.ora(),a;try{a=await s.me()}catch{let u=await Se(n,i.invite);return Re(u,i,n)}let l=n.ora(),m=a.serverTime-(o+l)/2,g=i.live===null?me(i.invite):et({appOrigin:e,n:i.n,reload:u=>i.porta.postMessage({type:"caisual:reload",target:u}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:Ve(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:be({day:a.day,seed:a.seed,expiresAt:a.expiresAt??le(a.serverTime)},()=>n.ora()+m,async()=>{let u=await s.me();return{day:u.day,seed:u.seed,expiresAt:u.expiresAt??le(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()},room:g};return Re(d,i,n)}function Re(n,e,t,i=null){let r=lt(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null,i);if(e?.overlay){let l=ut(e.porta,e.overlay,r);r.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",l,{once:!0})}let s=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=De(s,e?.gameLanguages??(e?.overlay?xe(e.overlay.configuration.manifest):void 0)),a=nt(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:a},text:rt(t?.fetcher??globalThis.fetch,o,t?.pathname),room:r.rooms,session:r.session,overlay:r.overlay}}async function yt(n){return Re(await Se(n),void 0,n)}function vt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function yi(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>vt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(vt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function bt(n=hi()){let e=null;return{connect(){return e??(e=Promise.all([gi(n),yi(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var wt=bt();globalThis.caisual=wt;var yr=wt;export{wt as caisual,yr as default};
|
|
1
|
+
// Caisual game kit v0.22.0
|
|
2
|
+
var xe=["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"],nt=new Set(xe);function b(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function ke(n,e="en"){let t=[],i=b(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(b(e)??e),[...new Set(t)]}function Q(n,e=[]){let t=e.map(b).filter(r=>r!==null),i=n.map(b).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let o of ke(r,r))if(t.includes(o))return o;return t.includes("en")?"en":t[0]}function ee(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function Re(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 te(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Pe(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let a=e?.deviceMemory,s=typeof a=="number"?a*1024:NaN;Number.isFinite(s)&&(t=s)}catch{t=null}let i=null;try{let a=e?.hardwareConcurrency;typeof a=="number"&&Number.isFinite(a)&&(i=a)}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 o=!1;try{o=n.crossOriginIsolated===!0}catch{o=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:o,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function ie(n,e=1500){let t=n??globalThis,i=Pe(t),r=Promise.resolve().then(()=>{try{let c=t.document?.createElement("canvas");if(c===void 0)return;let l=c.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(l!==null){i.webgl2=!0,i.gpu="hardware",te(l);return}let m=c.getContext("webgl2");m!==null&&(i.webgl2=!0,i.gpu="software",te(m))}catch{i.webgl2=!1,i.gpu="none"}}),o=Promise.resolve().then(async()=>{let c;try{let l=t.navigator?.gpu;if(l===void 0)return;let m=await l.requestAdapter();if(m===null)return;c=await m.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{c?.destroy?.()}catch{}}}),a=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),s=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}}),u;return await Promise.race([Promise.all([r,o,a,s]),new Promise(c=>{u=setTimeout(c,Math.max(0,e))})]),u!==void 0&&clearTimeout(u),{...i,tier:Re(i)}}function G(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var L=Object.freeze({recipientBytesPerSecond:1e5,roomBytesPerSecond:2e6,warningRatio:.8,windowMs:5e3,blockingWindows:3}),Tt=`Multiplayer budget: ${L.recipientBytesPerSecond/1e3} kB/s per recipient, ${L.roomBytesPerSecond/1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${L.recipientBytesPerSecond/2e4} kB per update. Keep visual trails and animation on the client. Warnings start at 80%. Publication measures your server automatically; repeated excess in real matches blocks new rooms only. Game input: 30 messages/s per connection.`;function ne(n,e,t="/"){let i,r=t.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0]??"/";return()=>i??(i=(async()=>{let o={};try{let a=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(a.ok){let s=await a.json();ee(s)&&(o=s)}}catch{}return(a,s={})=>Object.hasOwn(o,a)?o[a].replace(/\{([^{}]+)\}/g,(c,l)=>Object.hasOwn(s,l)?String(s[l]):c):a})())}function d(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function p(){return d("offline","Caisual services are unavailable.")}function C(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Ie(n){let e={};try{e=await n.json()}catch{}return d(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 T(n,e,t,i){async function r(o,a,s,u){let c=new Headers({Authorization:`Bearer ${s}`}),l;if(u!==void 0){c.set("Content-Type","application/json");try{l=JSON.stringify(u)}catch{throw d("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+o,n),{method:a,headers:c,body:l,credentials:"omit"})}catch{throw p()}}return async function(a,s,u,c=!1){let l;try{l=c?await i.rinnova():await i.ottieni()}catch{throw p()}let m=await r(a,s,l,u);if(m.status===401){try{l=await i.rinnova()}catch{throw p()}m=await r(a,s,l,u)}if(!m.ok)throw await Ie(m);try{return await m.json()}catch{throw d("internal_error","The service returned an invalid response.")}}}function re(n,e,t){let i=T(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,o)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:o}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(o){if(C(o)==="not_found")return null;throw o}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves}}}function w(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}var z={connected:!1,you:null,friends:[],party:null,invites:[]};function oe(n){let e=w(n);if(!e||typeof e.id!="string"||typeof e.name!="string")return null;let t=w(e.game),i=w(e.room);return{id:e.id,name:e.name,online:e.online===!0,game:t&&typeof t.slug=="string"?{slug:t.slug,name:typeof t.name=="string"?t.name:t.slug,iconUrl:typeof t.iconUrl=="string"?t.iconUrl:""}:null,room:i&&typeof i.code=="string"?{code:i.code}:null}}function Te(n){let e=w(n);if(!e||typeof e.id!="string"||typeof e.leader!="string")return null;let t=Array.isArray(e.members)?e.members.map(i=>oe(i)).filter(i=>i!==null):[];return{id:e.id,leader:e.leader,members:t}}function ze(n){let e=w(n),t=w(e?.from);return!e||typeof e.party!="string"||!t||typeof t.id!="string"?null:{party:e.party,from:{id:t.id,name:typeof t.name=="string"?t.name:t.id},at:typeof e.at=="number"?e.at:0}}function _e(n){let e=w(n);if(!e)return z;let t=w(e.you);return{connected:e.connected===!0,you:t&&typeof t.id=="string"?{id:t.id,name:typeof t.name=="string"?t.name:""}:null,friends:Array.isArray(e.friends)?e.friends.map(i=>oe(i)).filter(i=>i!==null):[],party:Te(e.party),invites:Array.isArray(e.invites)?e.invites.map(i=>ze(i)).filter(i=>i!==null):[]}}function se(){return{available:!1,get connected(){return!1},get you(){return null},get friends(){return[]},get party(){return null},get invites(){return[]},onChange(n){return n({...z}),()=>{}},createParty(){},invite(){},accept(){},decline(){},kick(){},leave(){},follow(){},join(){return Promise.reject(d("offline","Friends are unavailable in this copy of the game."))}}}function ae(n,e,t){let i={...z},r=new Set,o=s=>{try{n.postMessage({type:"caisual:crew",...s})}catch{}};n.addEventListener("message",s=>{let u=w(s.data);if(u?.type==="caisual:crew-state"){i=u.state===null?{...z}:_e(u.state);for(let c of r)try{c({...i})}catch{}}}),o({op:"subscribe"});let a=s=>{let u=i.friends.find(c=>c.id===s)??i.party?.members.find(c=>c.id===s);if(!u)throw d("friend_not_found","This player is not in your friends list.");return u};return{available:!0,get connected(){return i.connected},get you(){return i.you===null?null:{...i.you}},get friends(){return i.friends.map(s=>({...s}))},get party(){return i.party===null?null:{...i.party,members:i.party.members.map(s=>({...s}))}},get invites(){return i.invites.map(s=>({...s}))},onChange(s){return r.add(s),s({...i}),()=>{r.delete(s)}},createParty(){o({op:"party",action:"create"})},invite(s){o({op:"party",action:"invite",player:s})},accept(s){o({op:"party",action:"accept",party:s})},decline(s){o({op:"party",action:"decline",party:s})},kick(s){o({op:"party",action:"kick",player:s})},leave(){o({op:"party",action:"leave"})},follow(s){let u=a(s);if(!u.room||!u.game)throw d("no_room","This player is not in a room.");o({op:"follow",slug:u.game.slug,code:u.room.code})},join(s){let u=a(s);return u.room?e!==null&&u.game!==null&&u.game.slug!==e?Promise.reject(d("other_game","This player is playing another game. Use follow instead.")):t.join(u.room.code):Promise.reject(d("no_room","This player is not in a room."))}}}function P(n){return(Math.floor(n/864e5)+1)*864e5}function _(n,e,t){let i=new Set,r={...n},o,a=!1;function s(){!i.size||o!==void 0||a||(o=setTimeout(u,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),o.unref?.())}async function u(){o=void 0,a=!0;try{let c=await t(),l=c.day!==r.day;if(r={...c},l)for(let m of[...i])try{m({...c})}catch{}}catch{}finally{a=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),s()}}return{...n,random:ce(n.seed),rng:()=>ce(n.seed),onChange(c){return i.add(c),s(),()=>{i.delete(c),!i.size&&o!==void 0&&(clearTimeout(o),o=void 0)}}}}function j(n){return new Date(n).toISOString().slice(0,10)}async function B(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 ce(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 E(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function le(n,e){return E(n)?.type===e}function Ee(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 ue(n,e,t=3e3){return new Promise(i=>{let r=!1,o=globalThis.crypto.randomUUID(),a=l=>{r||(r=!0,n.removeEventListener("message",u),n.clearTimeout(c),i(l))},s=()=>{n.parent.postMessage({type:"caisual:ready",instance:o},e)},u=l=>{if(l.origin!==e||l.source!==n.parent)return;if(le(l.data,"caisual:ready?")){s();return}if(!le(l.data,"caisual:hello"))return;let m=E(l.data),f=l.ports[0];if(typeof m?.ticket!="string"||!G(m.n)||f===void 0)return;f.start();let g=v=>Array.isArray(v)?v.map(b).filter(M=>M!==null):void 0;a({...b(m.language)?{language:b(m.language)}:{},languagePreferences:g(m.languagePreferences),gameLanguages:g(m.gameLanguages),ticket:m.ticket,n:m.n,live:Ee(m.live),invite:typeof m.invite=="string"?m.invite:null,porta:f})};n.addEventListener("message",u);let c=n.setTimeout(()=>a(null),t);s()})}function Ve(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=E(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function Oe(n,e,t,i){return new Promise((r,o)=>{let a=!1,s=l=>{a||(a=!0,n.removeEventListener("message",u),e.clearTimeout(c),l===null?o(new Error("Ticket refresh timed out.")):r(l))},u=l=>{let m=E(l.data),f=m?.aud===void 0?"portal":m.aud;m?.type==="caisual:ticket"&&f===i&&typeof m.ticket=="string"&&s(m.ticket)};n.addEventListener("message",u);let c=e.setTimeout(()=>s(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{s(null)}})}function J(n,e,t,i,r=3e3,o="portal"){let a=n,s=null,u=()=>{if(s!==null)return s;let l=Oe(e,t,r,o).then(m=>(a=m,m)).finally(()=>{s===l&&(s=null)});return s=l,l};return{async ottieni(){if(a===null)return u();let c=Ve(a);return c!==null&&c-i()<3e4?u():a},rinnova:u}}var U=.02,de=300,De=200,me=3e3,$e=1e4,Ne=[1e3,2e3,4e3];function fe(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Ge(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 V=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??Ge(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=e.mic??!0;this.verificaIngresso(),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(d("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw d("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=fe(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(d(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,fe(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(d("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(d("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}verificaIngresso(){if(!this.contesto.connessa())throw d("offline","The room is not connected.");if(this.modeCorrente==="none")throw d("voice_disabled","Voice is disabled for this room.");if(this.dipendenze===null)throw d("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 o;try{o=await t.getUserMedia({audio:!0})}catch(s){throw this.permessoNegato(s)?d("permission_denied","Microphone permission was denied."):d("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(s){for(let u of o.getTracks())u.stop();throw s}let a=o.getAudioTracks()[0];if(a===void 0)throw d("voice_error","The microphone has no audio track.");this.stream=o,this.tracciaMic=a,a.enabled=!this.mutedCorrente,this.preparaAnalizzatore(o)}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 d("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw d("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 o of this.gains.keys())this.aggiornaZero(o);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=o=>{let a=o.transceiver.mid,s=a===null?void 0:this.midGiocatori.get(a);s!==void 0&&this.collegaTraccia(s,o.track,o.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let o=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),a=await i.createOffer();await i.setLocalDescription(a),this.controllaGenerazione(t);let s=o.mid,u=i.localDescription?.sdp;if(s===null||u===void 0)throw d("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:u,mid:s})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw d("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw d("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 d("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,o)=>{let a=()=>{e.removeEventListener("connectionstatechange",s),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},s=()=>{t!==this.generazione?(a(),o(d("offline","Voice was stopped."))):e.connectionState==="connected"?(a(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(a(),o(d("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",s),this.cancellaAttesaConnessione=()=>{a(),o(d("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{a(),o(d("voice_error","The voice connection timed out."))},$e)})}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(c=>[c.id,c])),r=[];for(let[c,l]of this.sfuAttive){let m=i.get(c);m!==void 0&&m.session===l.session&&m.track===l.track||(r.push(l),this.riproduzioni.has(c)||l.receiver?.track.stop(),this.sfuAttive.delete(c),this.midGiocatori.delete(l.mid),this.scollegaTraccia(c))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(c=>c.mid)});let o=[...i.values()].filter(c=>!this.sfuAttive.has(c.id));if(o.length===0)return;let a;try{a=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:o.map(c=>({session:c.session,track:c.track}))})}catch(c){if(C(c)!=="not_allowed")throw c;for(let l of o)this.negati.add(l.id);return}if(a.op!=="subscribe")throw d("voice_error","The voice service returned an invalid response.");for(let c of a.tracks){let l=o.find(m=>m.session===c.session&&m.track===c.track);c.error==="not_allowed"&&l!==void 0&&this.negati.add(l.id),!(c?.mid===null||c?.mid===void 0||c.error!==null||l===void 0)&&(this.midGiocatori.set(c.mid,l.id),this.sfuAttive.set(l.id,{session:l.session,track:l.track,mid:c.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:a.sdp});let s=await t.createAnswer();await t.setLocalDescription(s);let u=t.localDescription?.sdp;if(u===void 0)throw d("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:u}),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=o=>{o.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:o.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=o=>{r.receiver=o.receiver,this.collegaTraccia(t,o.track,o.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(a=>a.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 o=t;try{if(o.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(o.candidate);return}if(o.kind!=="offer"&&o.kind!=="answer"||typeof o.sdp!="string")return;let a=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),s=o.kind==="offer"&&!a;if(r.ignoreOffer=!r.polite&&s,r.ignoreOffer)return;if(r.settingRemoteAnswer=o.kind==="answer",await r.pc.setRemoteDescription({type:o.kind,sdp:o.sdp}),r.settingRemoteAnswer=!1,o.kind==="offer"){let u=await r.pc.createAnswer();await r.pc.setLocalDescription(u);let c=r.pc.localDescription?.sdp;c!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:c})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(C(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=>!(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic||this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team))}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<me})}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()),o=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,me-r));this.timerZero.set(e,o)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),o=r.creaMediaStream([t]),a=this.richiediAudioContext().createMediaStreamSource(o),s=this.richiediAudioContext().createGain();a.connect(s),s.connect(this.richiediAudioContext().destination);let u=null;try{u=this.richiediAudioContext().createAnalyser(),u.fftSize=256,a.connect(u)}catch{u=null}let c=r.creaAudioElement();c.srcObject=o,c.muted=!0,c.playsInline=!0,c.play().catch(()=>{}),this.riproduzioni.set(e,{source:a,gain:s,analyser:u,audio:c,track:t,receiver:i});let l=this.sfuAttive.get(e);l!==void 0&&(l.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(),De)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>U),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=de;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let o of this.copiaPeers()){let a=this.riproduzioni.get(o.id);this.livelloAnalizzatore(a?.analyser??null)>U?this.ultimoAudio.set(o.id,e.ora()):(a?.analyser===null||a?.analyser===void 0)&&(a?.receiver?.getSynchronizationSources?.()??[]).some(c=>(c.audioLevel??0)>U)&&this.ultimoAudio.set(o.id,e.ora());let s=!o.muted&&e.ora()-(this.ultimoAudio.get(o.id)??0)<=de;(this.speakingPeers.get(o.id)??!1)!==s&&(this.speakingPeers.set(o.id,s),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,o)=>r+o*o,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=>r.id===e?[]:this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team?[]:[{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(d("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=Ne[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(d("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(o){this.richieste.delete(t),r(o)}})}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 d("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw d("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw d("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw d("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==="offline"||t==="voice_error"?e:d("voice_error","Voice could not be started.")}return d("voice_error","Voice could not be started.")}};var k=1,he=[1e3,2e3,4e3,8e3],Le=6e4,je=5e3,Be=2e4,Je=500,Ue=2e3,qe=new Set([4003,4004,4005,4006,4008,4009]);function x(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function pe(n){let e=x(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function Fe(n){let e=x(n),t=x(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 S(n){return JSON.parse(JSON.stringify(n))}function We(n,e){let t=S(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=S(i.value);continue}let r=t,o=i.path;for(let s=0;s<o.length-1;s++){let u=o[s];if(Array.isArray(r)){if(typeof u!="number"||u>=r.length)return{ok:!1};r=r[u]}else{let c=x(r);if(c===null||typeof u!="string"||!Object.hasOwn(c,u))return{ok:!1};r=c[u]}}let a=o.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof a!="number"||a>=r.length)return{ok:!1};r[a]=S(i.value)}else{let s=x(r);if(s===null||typeof a!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(s,a))return{ok:!1};delete s[a]}else Object.defineProperty(s,a,{configurable:!0,enumerable:!0,value:S(i.value),writable:!0})}}return{ok:!0,state:t}}function He(n){let e=T(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,s,u)=>{try{return await e(o,a,{...x(s),n:n.n},u)}catch(c){if(c instanceof Error&&"code"in c&&["version_outdated","version_mismatch"].includes(String(c.code))){let l=x(s),m=typeof l?.code=="string"?l.code.toUpperCase().replace(/[\s-]/g,""):void 0,f=typeof l?.roomId=="string"?l.roomId:void 0;n.onVersionError?.(c,c.code==="version_mismatch"?{code:m,roomId:f}:void 0)}throw c}};async function i(o,a,s=!1){let u=await t(o,"POST",a,s);if(!pe(u))throw d("internal_error","The room service returned an invalid response.");return u}async function r(o){let a=await t("/match","POST",{mode:o.mode,key:o.key});if(!Fe(a))throw d("internal_error","The matchmaking service returned an invalid response.");return a}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var q=class{constructor(e,t,i,r,o,a){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=o;this.segnalaStanza=a;this.meta={mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;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.resultCorrente=null;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.promessaPronta=new Promise((s,u)=>{this.risolviPronta=s,this.rifiutaPronta=u}),this.voice=new V({invia:s=>this.invia(s),connessa:()=>this.socket?.readyState===k&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),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)}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)}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({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(d("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(d("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(d("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let o=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(d("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:o});try{this.invia({t:"request-role",r:t,role:e})}catch(a){this.dipendenze.clearTimeout(o),this.roleRequests.delete(t),r(a)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(d("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(d("cancelled","The room was disconnected.")))}get role(){return 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 code(){return this.codice}get result(){return this.resultCorrente}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 d("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!==k||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(a=>e-a<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,o=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!==k||this.terminata||this.lasciata)return;let a=this.dipendenze.ora();if(a<this.ultimoInvioGioco+i||this.inviiGioco.filter(u=>a-u<1e3).length>=30){this.programmaInput();return}let s=this.ultimoInput;try{this.send(JSON.parse(s)),this.inputInviato=s}catch{}},Math.max(0,Math.ceil(Math.max(o,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})}restart(){if(this.statusCorrente!=="finished")throw d("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){this.lasciata||(this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===k&&this.invia({t:"leave"}),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!==k)throw d("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw d("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!==k||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?je:Be;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===k)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=x(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="players")this.riceviGiocatori(t.players);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,S(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==="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(d(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()}}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=S(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()},Ue)),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){this.giocatoriCorrenti=e.map(t=>({...t})),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){this.statusCorrente=e.status,this.resultCorrente=S(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,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=We(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=S(e),this.statoPubblico=S(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==k)){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(qe.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.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,he.length-1),t=he[e];if(this.tempoRiconnessione+t>Le){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=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.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let a=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(d(a,"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.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()},Je))}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 O(n=null){return{invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw p()},async join(){throw p()},async match(){throw p()}}}function ge(n,e){let t,i=new Set,r=He({...n,onVersionError(l,m){t=m;for(let f of i)try{f(l)}catch{}}}),o=!1,a=null,s=l=>{let m=l?.code??null;o&&m===a||(o=!0,a=m,n.segnalaStanza?.(l))},u=async l=>{let m=new q(l.roomId,l.code,l.url,n,r,s);return await m.pronta(),m},c=(l,m)=>new Promise((f,g)=>{let v,M=!1,W=()=>{v.removeEventListener("message",Y),v.removeEventListener("close",Z),v.removeEventListener("error",K),m.signal?.removeEventListener("abort",N)},H=()=>{try{v.close(1e3)}catch{}},y=(I,h)=>{M||(M=!0,W(),h&&H(),g(I))};function N(){y(d("cancelled","The matchmaking search was cancelled."),!0)}function Z(){y(p(),!1)}function K(){y(p(),!0)}function Y(I){let h=null;try{h=typeof I.data=="string"?x(JSON.parse(I.data)):null}catch{}if(h===null||typeof h.t!="string"){y(d("internal_error","The matchmaking service sent an invalid message."),!0);return}if(h.t==="waiting"){if(!Number.isInteger(h.players)||!Number.isInteger(h.min)||!Number.isInteger(h.max)){y(d("internal_error","The matchmaking service sent an invalid message."),!0);return}try{m.onWaiting?.({players:h.players,min:h.min,max:h.max})}catch{}return}if(h.t==="matched"){if(!pe(h)){y(d("internal_error","The matchmaking service sent an invalid message."),!0);return}M=!0,W(),H(),f(h);return}if(h.t==="no_match"){y(d("no_match","No match was found before the timeout."),!0);return}if(h.t==="error"){y(d(typeof h.code=="string"?h.code:"internal_error",typeof h.message=="string"?h.message:"The matchmaking service could not complete the search."),!0);return}h.t!=="pong"&&y(d("internal_error","The matchmaking service sent an invalid message."),!0)}try{v=n.apriSocket(l)}catch{g(p());return}v.addEventListener("message",Y),v.addEventListener("close",Z),v.addEventListener("error",K),m.signal?.addEventListener("abort",N,{once:!0}),m.signal?.aborted===!0&&N()});return{invited:e,reload(){n.reload?.(t)},onError(l){return i.add(l),()=>{i.delete(l)}},async create(l){return u(await r.create(l.mode))},async join(l){let m=l??e;if(m==null||m.length===0)throw d("invalid_request","A room invitation code is required.");return u(await r.joinCode(m))},async match(l){let m=()=>l.signal?.aborted===!0;if(m())throw d("cancelled","The matchmaking search was cancelled.");let f=await r.match(l);if(m())throw d("cancelled","The matchmaking search was cancelled.");return u(await c(f.url,l))}}}var R="caisual:save:",Ze=/^[a-z0-9][a-z0-9_-]{0,31}$/;function F(n){if(!Ze.test(n))throw d("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function ve(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function ye(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(R)&&e.push(i.slice(R.length))}return e}function Ke(n,e){let t=()=>{if(n===null)throw p();return n};return{async set(i,r){F(i);let o=t(),a=JSON.stringify({value:r}),s=new TextEncoder().encode(a).byteLength;if(s>262144)throw d("payload_too_large","The save is larger than 262144 bytes.");if(o.getItem(R+i)===null&&ye(o).length>=64)throw d("save_limit","A game can store at most 64 save keys.");let u={value:r,bytes:s,updatedAt:e()};return o.setItem(R+i,JSON.stringify(u)),{key:i,bytes:s,updatedAt:u.updatedAt}},async get(i){return F(i),ve(t().getItem(R+i))?.value??null},async remove(i){F(i),t().removeItem(R+i)},async list(){let i=t();return ye(i).flatMap(r=>{let o=ve(i.getItem(R+r));return o===null?[]:[{key:r,bytes:o.bytes,updatedAt:o.updatedAt}]}).sort((r,o)=>r.key.localeCompare(o.key))}}}async function D(n,e=null){let t=n.ora(),i=j(t),r=await B(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:_({day:i,seed:r,expiresAt:P(t)},n.ora,async()=>{let o=n.ora(),a=j(o);return{day:a,seed:await B(n.hostname,a,n.subtle),expiresAt:P(o)}}),time:{now:n.ora},save:Ke(n.archivio,n.ora),room:O(e)}}function Ye(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 Xe(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Qe(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:Xe(),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:()=>ie()}}async function et(n){let e=Ye(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return $(await D(n),void 0,n,null);let i=await ue(n.finestra,e,n.timeoutHandshake);if(i===null)return $(await D(n),void 0,n,null);let r=J(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),o=re(e,n.fetcher,r),a=n.ora(),s;try{s=await o.me()}catch{let f=await D(n,i.invite);return $(f,i,n,null)}let u=n.ora(),c=s.serverTime-(a+u)/2,l=i.live===null?O(i.invite):ge({appOrigin:e,n:i.n,reload:f=>i.porta.postMessage({type:"caisual:reload",target:f}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:J(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(f){if(n.apriSocket!==void 0)return n.apriSocket(f);if(typeof WebSocket>"u")throw p();return new WebSocket(f)},ora:n.ora,setTimeout:(f,g)=>globalThis.setTimeout(f,g),clearTimeout:f=>globalThis.clearTimeout(f),setInterval:(f,g)=>globalThis.setInterval(f,g),clearInterval:f=>globalThis.clearInterval(f),voce:n.voce,segnalaStanza(f){try{i.porta.postMessage({type:"caisual:room",room:f})}catch{}}},i.invite),m={connected:!0,player:s.player,daily:_({day:s.day,seed:s.seed,expiresAt:s.expiresAt??P(s.serverTime)},()=>n.ora()+c,async()=>{let f=await o.me();return{day:f.day,seed:f.seed,expiresAt:f.expiresAt??P(f.serverTime)}}),time:{now:()=>n.ora()+c},save:{set:(f,g)=>o.saveSet(f,g),get:f=>o.saveGet(f),remove:f=>o.saveRemove(f),list:()=>o.saveList()},room:l};return $(m,i,n,s.game.slug)}function $(n,e,t,i){let r=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=Q(r,e?.gameLanguages);return{...n,player:{...n.player,language:o},text:ne(t?.fetcher??globalThis.fetch,o,t?.pathname),crew:e?ae(e.porta,i,n.room):se()}}function be(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function tt(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>be()),new Promise(t=>{e=globalThis.setTimeout(()=>t(be()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function we(n=Qe()){let e=null;return{connect(){return e??(e=Promise.all([et(n),tt(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Se=we();globalThis.caisual=Se;var Ni=Se;export{Se as caisual,Ni as default};
|