@caisual/kit 0.8.0 → 0.10.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/dist/kit.js CHANGED
@@ -1,4 +1,4 @@
1
- // Caisual game kit v0.8.0
1
+ // Caisual game kit v0.10.0
2
2
 
3
3
  // ../contracts/src/slug.ts
4
4
  var NOMI_RISERVATI = [
@@ -43,6 +43,46 @@ function isReservedSlug(value) {
43
43
  return RISERVATI.has(value);
44
44
  }
45
45
 
46
+ // ../contracts/src/i18n.ts
47
+ function normalizeLanguage(value) {
48
+ if (typeof value !== "string" || value.length > 128) return null;
49
+ try {
50
+ return Intl.getCanonicalLocales(value)[0] ?? null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function manifestLanguages(manifest) {
56
+ return manifest.languages?.length ? [...manifest.languages] : [manifest.language ?? "en"];
57
+ }
58
+ function languageFallbacks(language, defaultLanguage = "en") {
59
+ const result = [];
60
+ let tag = normalizeLanguage(language);
61
+ while (tag) {
62
+ result.push(tag);
63
+ const parts = tag.split("-");
64
+ parts.pop();
65
+ if (parts.at(-1)?.length === 1) parts.pop();
66
+ tag = parts.join("-");
67
+ }
68
+ result.push(normalizeLanguage(defaultLanguage) ?? defaultLanguage);
69
+ return [...new Set(result)];
70
+ }
71
+ function resolveGameLanguage(preferences, languages2 = []) {
72
+ const declared = languages2.map(normalizeLanguage).filter((tag) => tag !== null);
73
+ const preferred = preferences.map(normalizeLanguage).filter((tag) => tag !== null);
74
+ if (!declared.length) return preferred[0] ?? "en";
75
+ for (const preference of preferred) {
76
+ for (const tag of languageFallbacks(preference, preference)) {
77
+ if (declared.includes(tag)) return tag;
78
+ }
79
+ }
80
+ return declared[0];
81
+ }
82
+ function isTextDictionary(value) {
83
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === "string");
84
+ }
85
+
46
86
  // ../contracts/src/manifest.ts
47
87
  function risolviModalita(manifest, mode) {
48
88
  const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
@@ -64,6 +104,7 @@ var CAMPI = /* @__PURE__ */ new Set([
64
104
  "cover",
65
105
  "screenshots",
66
106
  "tags",
107
+ "languages",
67
108
  "language",
68
109
  "platform",
69
110
  "orientation",
@@ -130,12 +171,32 @@ function stringaDefault(dati, campo, valoreDefault, errori) {
130
171
  }
131
172
  function testoFacoltativo(value, key, max, path, errors) {
132
173
  if (value[key] === void 0) return void 0;
133
- const text = value[key];
134
- if (typeof text !== "string" || text.trim().length === 0 || text.trim().length > max || /[\r\n\u0000-\u001f]/.test(text)) {
135
- errors.push(`${path}.${key}: must contain 1-${max} characters on one line.`);
174
+ const check = (text2, field2) => {
175
+ if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\r\n\u0000-\u001f]/.test(text2)) {
176
+ errors.push(`${field2}: must contain 1-${max} characters on one line.`);
177
+ return void 0;
178
+ }
179
+ return text2.trim();
180
+ };
181
+ const text = value[key], field = `${path}.${key}`;
182
+ if (typeof text === "string") return check(text, field);
183
+ const translations = oggetto(text);
184
+ if (!translations || Object.keys(translations).length === 0) {
185
+ errors.push(`${field}: must be a string or a non-empty language-to-text object.`);
136
186
  return void 0;
137
187
  }
138
- return text.trim();
188
+ const result = {};
189
+ for (const [raw, text2] of Object.entries(translations)) {
190
+ const tag = normalizeLanguage(raw);
191
+ if (!tag) {
192
+ errors.push(`${field}.${raw}: must be a BCP 47 language tag.`);
193
+ continue;
194
+ }
195
+ if (Object.hasOwn(result, tag)) errors.push(`${field}.${raw}: duplicate language.`);
196
+ const checked = check(text2, `${field}.${raw}`);
197
+ if (checked !== void 0) result[tag] = checked;
198
+ }
199
+ return result;
139
200
  }
140
201
  function validaManifest(valore) {
141
202
  const errori = [];
@@ -190,10 +251,24 @@ function validaManifest(valore) {
190
251
  }
191
252
  }
192
253
  }
193
- const language = stringaDefault(dati, "language", "en", errori);
194
- if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language)) {
254
+ const legacyLanguage = stringaDefault(dati, "language", "en", errori);
255
+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {
195
256
  errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
196
257
  }
258
+ const languages2 = [];
259
+ if (dati.languages === void 0) languages2.push(normalizeLanguage(legacyLanguage) ?? legacyLanguage);
260
+ else if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
261
+ errori.push("languages: must be a non-empty array of BCP 47 language tags.");
262
+ } else for (const [index, raw] of dati.languages.entries()) {
263
+ const tag = normalizeLanguage(raw);
264
+ if (!tag) errori.push(`languages[${index}]: must be a BCP 47 language tag.`);
265
+ else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);
266
+ else languages2.push(tag);
267
+ }
268
+ const language = languages2[0] ?? legacyLanguage;
269
+ if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
270
+ errori.push("language: must match the first entry in languages when both are present.");
271
+ }
197
272
  let platform = "both";
198
273
  if (dati.platform === void 0) errori.push("platform: is required.");
199
274
  else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
@@ -559,6 +634,7 @@ function validaManifest(valore) {
559
634
  cover,
560
635
  screenshots,
561
636
  tags,
637
+ languages: languages2,
562
638
  language,
563
639
  platform,
564
640
  orientation,
@@ -726,9 +802,13 @@ function normalizeOverlayHello(value) {
726
802
  if (!validOverlayHello(value)) return null;
727
803
  return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite) };
728
804
  }
805
+ function validSafeArea(value) {
806
+ const area = record(value);
807
+ return area !== null && Object.keys(area).length === 4 && ["top", "right", "bottom", "left"].every((key) => typeof area[key] === "number" && Number.isFinite(area[key]) && Number(area[key]) >= 0 && Number(area[key]) <= 1e5);
808
+ }
729
809
  function validOverlayView(value) {
730
810
  const data = record(value);
731
- return data !== null && Object.keys(data).every((key) => ["inputBlocked", "reservedRects", "shortcutEnabled"].includes(key)) && (data.shortcutEnabled === void 0 || typeof data.shortcutEnabled === "boolean") && typeof data.inputBlocked === "boolean" && Array.isArray(data.reservedRects) && data.reservedRects.length <= 8 && data.reservedRects.every((value2) => {
811
+ return data !== null && Object.keys(data).every((key) => ["inputBlocked", "reservedRects", "safeArea", "shortcutEnabled"].includes(key)) && (data.safeArea === void 0 || validSafeArea(data.safeArea)) && (data.shortcutEnabled === void 0 || typeof data.shortcutEnabled === "boolean") && typeof data.inputBlocked === "boolean" && Array.isArray(data.reservedRects) && data.reservedRects.length <= 8 && data.reservedRects.every((value2) => {
732
812
  const rect = record(value2);
733
813
  return rect !== null && Object.keys(rect).length === 4 && ["x", "y", "width", "height"].every((key) => typeof rect[key] === "number" && Number.isFinite(rect[key]) && rect[key] >= 0 && rect[key] <= 1e5);
734
814
  });
@@ -759,6 +839,7 @@ function validOverlayRequest(value) {
759
839
  return keys("role") && text("role");
760
840
  case "room.team":
761
841
  return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;
842
+ case "room.restart":
762
843
  case "room.start":
763
844
  case "session.cancel":
764
845
  case "session.leave":
@@ -784,6 +865,158 @@ function validBoardDay(value) {
784
865
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
785
866
  }
786
867
 
868
+ // ../contracts/src/room-limits.ts
869
+ var MESSAGGI_GIOCO_AL_SECONDO = 20;
870
+
871
+ // src/overlay/i18n.ts
872
+ var languages = ["en", "it", "es", "fr", "de", "pt"];
873
+ var words = {
874
+ gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo"],
875
+ loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando..."],
876
+ loadingSlow: ["This game is taking longer than expected. You can wait a little longer or try again.", "Il gioco ci sta mettendo pi\xF9 del previsto. Puoi aspettare ancora un po\u2019 o riprovare.", "El juego est\xE1 tardando m\xE1s de lo esperado. Puedes esperar un poco m\xE1s o volver a intentarlo.", "Le jeu met plus de temps que pr\xE9vu. Vous pouvez patienter encore un peu ou r\xE9essayer.", "Das Spiel braucht l\xE4nger als erwartet. Du kannst noch etwas warten oder es erneut versuchen.", "O jogo est\xE1 demorando mais do que o esperado. Voc\xEA pode esperar mais um pouco ou tentar novamente."],
877
+ home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
878
+ homeMenu: ["Menu", "Menu", "Men\xFA", "Menu", "Men\xFC", "Menu"],
879
+ mode: ["Mode", "Modalit\xE0", "Modo", "Mode", "Modus", "Modo"],
880
+ play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
881
+ friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos"],
882
+ find: ["Find players", "Trova giocatori", "Buscar jugadores", "Trouver des joueurs", "Spieler finden", "Buscar jogadores"],
883
+ join: ["Join with code", "Entra con codice", "Entrar con c\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\xF3digo"],
884
+ joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\xE1 sala"],
885
+ watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala"],
886
+ resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar"],
887
+ room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala"],
888
+ code: ["Room code", "Codice stanza", "C\xF3digo de sala", "Code de salle", "Raumcode", "C\xF3digo da sala"],
889
+ copy: ["Copy invite", "Copia invito", "Copiar invitaci\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite"],
890
+ copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\xE9", "Einladung kopiert", "Convite copiado"],
891
+ copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:"],
892
+ joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \xE0 la salle...", "Raum wird betreten...", "Entrando na sala..."],
893
+ matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores..."],
894
+ queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores"],
895
+ cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar"],
896
+ close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\xDFen", "Fechar"],
897
+ back: ["Back", "Indietro", "Volver", "Retour", "Zur\xFCck", "Voltar"],
898
+ ready: ["Ready", "Pronto", "Listo", "Pr\xEAt", "Bereit", "Pronto"],
899
+ unready: ["Not ready", "Non pronto", "No listo", "Pas pr\xEAt", "Nicht bereit", "N\xE3o pronto"],
900
+ start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\xE7ar"],
901
+ role: ["Role", "Ruolo", "Rol", "R\xF4le", "Rolle", "Fun\xE7\xE3o"],
902
+ team: ["Team", "Squadra", "Equipo", "\xC9quipe", "Team", "Equipe"],
903
+ host: ["Host", "Host", "Anfitrion", "H\xF4te", "Host", "Anfitri\xE3o"],
904
+ you: ["You", "Tu", "T\xFA", "Vous", "Du", "Voc\xEA"],
905
+ away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente"],
906
+ needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores"],
907
+ needReady: ["Everyone needs to be ready", "Tutti devono essere pronti", "Todos deben estar listos", "Tout le monde doit \xEAtre pr\xEAt", "Alle m\xFCssen bereit sein", "Todos precisam estar prontos"],
908
+ needRoles: ["Fill the required roles", "Completa i ruoli richiesti", "Completa los roles", "Compl\xE9tez les r\xF4les", "Ben\xF6tigte Rollen besetzen", "Complete as fun\xE7\xF5es"],
909
+ needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \xE9quipes", "Teams auswahlen", "Escolha as equipes"],
910
+ waitHost: ["Waiting for the host", "In attesa dell'host", "Esperando al anfitrion", "En attente de l\u2019h\xF4te", "Warten auf den Host", "Esperando o anfitri\xE3o"],
911
+ starting: ["Starting in", "Si inizia tra", "Empieza en", "D\xE9but dans", "Start in", "Come\xE7a em"],
912
+ playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando"],
913
+ ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada"],
914
+ rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos"],
915
+ rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche"],
916
+ again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente"],
917
+ newRoom: ["New room. Share the new invite.", "Nuova stanza. Condividi il nuovo invito.", "Nueva sala. Comparte la invitaci\xF3n.", "Nouvelle salle. Partagez le lien.", "Neuer Raum. Neue Einladung teilen.", "Nova sala. Compartilhe o convite."],
918
+ watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo"],
919
+ delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\xF6gerung", "Atraso de {n}s"],
920
+ exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair"],
921
+ leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\xFCbergehend verlassen", "Sair por enquanto"],
922
+ leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala"],
923
+ leaveHint: ["Your room stays available for Resume.", "La stanza resta disponibile con Riprendi.", "Podr\xE1s volver a est\xE1 sala.", "Vous pourrez reprendre cette salle.", "Du kannst den Raum fortsetzen.", "Voc\xEA pode voltar a est\xE1 sala."],
924
+ temporaryHint: ["The game continues. Rejoining may only be possible briefly.", "La partita continua. Il rientro pu\xF2 essere disponibile solo per poco.", "La partida continua. Volver puede ser posible solo por poco tiempo.", "La partie continue. Le retour peut \xEAtre limit\xE9.", "Das Spiel l\xE4uft weiter. R\xFCckkehr nur kurz m\xF6glich.", "A partida continua. O retorno pode ser limitado."],
925
+ abandonHint: ["Leave room gives up your place.", "Lascia la stanza libera il tuo posto.", "Abandonar libera tu plaza.", "Abandonner lib\xE8re votre place.", "Raum verlassen gibt deinen Platz frei.", "Deixar a sala libera sua vaga."],
926
+ reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando..."],
927
+ replaced: ["Opened in another tab", "Aperta in un\u2019altra scheda", "Abierta en otra pest\xE1na", "Ouverte dans un autre onglet", "In anderem Tab ge\xF6ffnet", "Aberta em outra aba"],
928
+ error: ["Something went wrong. Try again.", "Qualcosa non va. Riprova.", "Algo sali\xF3 mal. Reintenta.", "Une erreur est survenue. R\xE9essayez.", "Etwas ist schiefgelaufen. Erneut versuchen.", "Algo deu errado. Tente novamente."],
929
+ noRoom: ["This room is no longer available.", "Questa stanza non \xE8 pi\xF9 disponibile.", "Esta sala ya no est\xE1 disponible.", "Cette salle n'est plus disponible.", "Dieser Raum ist nicht mehr verf\xFCgbar.", "Esta sala n\xE3o est\xE1 mais disponivel."],
930
+ full: ["This room is full.", "La stanza \xE8 piena.", "La sala est\xE1 llena.", "Cette salle est pleine.", "Dieser Raum ist voll.", "Esta sala est\xE1 cheia."],
931
+ noMatch: ["No match this time. Try again.", "Nessun gruppo trovato. Riprova.", "No hay grupo. Reintenta.", "Aucun groupe trouv\xE9. R\xE9essayez.", "Keine Gruppe gefunden. Erneut versuchen.", "Nenhum grupo encontrado. Tente novamente."],
932
+ invalidCode: ["Enter a six-character room code.", "Inserisci un codice di sei caratteri.", "Escribe un c\xF3digo de seis caracteres.", "Entrez un code de six caracteres.", "Sechsstelligen Raumcode eingeben.", "Digite um c\xF3digo de seis caracteres."],
933
+ refused: ["The room did not accept that change.", "La stanza ha rifiutato la modifica.", "La sala rechaz\xF3 el cambio.", "La salle a refus\xE9 ce changement.", "Der Raum hat die \xC4nderung abgelehnt.", "A sala recusou a altera\xE7\xE3o."],
934
+ unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\xFCgbar", "Indisponivel agora"],
935
+ offline: ["Connection unavailable. Try again.", "Connessione non disponibile. Riprova.", "Sin conexi\xF3n. Reintenta.", "Connexion indisponible. R\xE9essayez.", "Keine Verbindung. Erneut versuchen.", "Sem conex\xE3o. Tente novamente."],
936
+ saveFailed: ["Keep the room code. Resume could not be saved.", "Conserva il codice. Riprendi non \xE8 stato salvato.", "Guarda el c\xF3digo. No se pudo guardar el regreso.", "Gardez le code. La reprise ne peut pas \xEAtre enregistr\xE9e.", "Raumcode aufbewahren. Fortsetzen nicht gespeichert.", "Guarde o c\xF3digo. O retorno n\xE3o foi salvo."],
937
+ boards: ["Leaderboard", "Classifica", "Clasificaci\xF3n", "Classement", "Bestenliste", "Classifica\xE7\xE3o"],
938
+ board: ["Board", "Classifica", "Tabla", "Classement", "Bestenliste", "Tabela"],
939
+ daily: ["Daily", "Giornaliera", "Diaria", "Du jour", "T\xE4glich", "Di\xE1ria"],
940
+ allTime: ["All time", "Di sempre", "Hist\xF3rica", "Tous les temps", "Gesamt", "Geral"],
941
+ accounts: ["Accounts", "Account", "Cuentas", "Comptes", "Konten", "Contas"],
942
+ guests: ["Guests", "Ospiti", "Invitados", "Invit\xE9s", "G\xE4ste", "Visitantes"],
943
+ category: ["Category", "Categoria", "Categoria", "Cat\xE9gorie", "Kategorie", "Categoria"],
944
+ period: ["Period", "Periodo", "Per\xEDodo", "P\xE9riode", "Zeitraum", "Per\xEDodo"],
945
+ rank: ["Rank", "Posizione", "Puesto", "Rang", "Platz", "Posicao"],
946
+ score: ["Score", "Punteggio", "Puntos", "Score", "Punkte", "Pontos"],
947
+ verified: ["Verified", "Verificato", "Verificado", "V\xE9rifi\xE9", "Verifiziert", "Verificado"],
948
+ own: ["Your best", "Il tuo record", "Tu record", "Votre record", "Dein Rekord", "Seu recorde"],
949
+ empty: ["No scores yet", "Nessun punteggio", "A\xFAn no hay puntos", "Aucun score", "Noch keine Punkte", "Ainda sem pontos"],
950
+ saving: ["Saving score...", "Salvataggio punteggio...", "Guardando puntos...", "Enregistrement du score...", "Punkte werden gespeichert...", "Salvando pontos..."],
951
+ saved: ["Your best is on the board", "Il tuo record \xE8 in classifica", "Tu record est\xE1 en la tabla", "Votre record est au classement", "Dein Rekord ist eingetragen", "Seu recorde est\xE1 na tabela"],
952
+ bestAlready: ["Your best is already on the board", "Il tuo record era gi\xE0 in classifica", "Tu record ya estaba en la tabla", "Votre record est d\xE9j\xE0 au classement", "Dein Rekord ist bereits eingetragen", "Seu recorde j\xE1 est\xE1 na tabela"],
953
+ refresh: ["Refresh", "Aggiorna", "Actualizar", "Actualiser", "Aktualisieren", "Atualizar"],
954
+ refreshHint: ["Score not visible yet. Refresh to check.", "Punteggio non ancora visibile. Aggiorna per controllare.", "Puntos a\xFAn no visibles. Actualiza.", "Score pas encore visible. Actualisez.", "Punkte noch nicht sichtbar. Aktualisieren.", "Pontos ainda n\xE3o visiveis. Atualize."],
955
+ friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo"],
956
+ localCrew: ["Friends and party are unavailable in local preview.", "Amici e gruppo non disponibili in anteprima locale.", "Amigos y grupo no disponibles en la vista local.", "Amis et groupe indisponibles en aper\xE7u local.", "Freunde und Gruppe in lokaler Vorschau nicht verf\xFCgbar.", "Amigos e grupo indispon\xEDveis na pr\xE9via local."],
957
+ loginCrew: ["Sign in on Caisual to use friends and party.", "Accedi a Caisual per amici e gruppo.", "Inicia sesion para amigos y grupo.", "Connectez-vous pour utiliser amis et groupe.", "F\xFCr Freunde und Gruppe bei Caisual anmelden.", "Entre no Caisual para amigos e grupo."],
958
+ online: ["Online", "Online", "En linea", "En ligne", "Online", "Online"],
959
+ noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online"],
960
+ createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\xE9er un groupe", "Gruppe erstellen", "Criar grupo"],
961
+ inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo"],
962
+ leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo"],
963
+ accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar"],
964
+ decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar"],
965
+ follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se"],
966
+ voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz"],
967
+ voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz"],
968
+ voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz"],
969
+ voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar"],
970
+ voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone"],
971
+ voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\xE9sactiv\xE9e", "Sprachchat aus", "Voz desativada"],
972
+ voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz..."],
973
+ voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\xE9e", "Sprachchat verbunden", "Voz conectada"],
974
+ voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\xE9", "Stumm", "Silenciado"],
975
+ voiceMic: ["Mic on", "Microfono attivo", "Micr\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo"],
976
+ voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\xC9coute seule", "Nur zuh\xF6ren", "Somente ouvindo"],
977
+ voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando"],
978
+ voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz"],
979
+ voiceEmpty: ["No one else in voice yet.", "Nessun altro in voce per ora.", "A\xFAn no hay nadie m\xE1s en voz.", "Personne d\u2019autre en voix pour le moment.", "Noch niemand im Sprachchat.", "Ningu\xE9m mais na voz ainda."],
980
+ voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\xE4rke f\xFCr {name}", "Volume de {name}"],
981
+ voiceUnavailable: ["Join a room with voice to use these controls.", "Entra in una stanza con voce per usare questi controlli.", "Entra en una sala con voz para usar estos controles.", "Rejoignez une salle vocale pour utiliser ces commandes.", "Diese Steuerung braucht einen Raum mit Sprachchat.", "Entre em uma sala com voz para usar estes controles."],
982
+ voiceWatch: ["Voice is unavailable while watching.", "La voce non e' disponibile in osservazione.", "La voz no est\xE1 disponible al observar.", "La voix est indisponible en observation.", "Beim Zuschauen ist kein Sprachchat verf\xFCgbar.", "A voz n\xE3o est\xE1 dispon\xEDvel ao assistir."],
983
+ voiceDenied: ["Microphone permission denied. Allow it in your browser, then try again.", "Permesso microfono negato. Consenti l'accesso nel browser e riprova.", "Permiso de micr\xF3fono denegado. Act\xEDvalo en el navegador e int\xE9ntalo de nuevo.", "Acc\xE8s au micro refus\xE9. Autorisez-le dans le navigateur, puis r\xE9essayez.", "Mikrofonzugriff verweigert. Im Browser erlauben und erneut versuchen.", "Permiss\xE3o do microfone negada. Permita no navegador e tente novamente."],
984
+ voiceUnsupported: ["Voice is not supported in this browser.", "Questo browser non supporta la voce.", "Este navegador no admite voz.", "Ce navigateur ne prend pas en charge la voix.", "Dieser Browser unterst\xFCtzt keinen Sprachchat.", "Este navegador n\xE3o oferece suporte a voz."],
985
+ voiceFailed: ["Voice could not connect. Try again.", "Connessione voce non riuscita. Riprova.", "No se pudo conectar la voz. Int\xE9ntalo de nuevo.", "Connexion vocale impossible. R\xE9essayez.", "Sprachverbindung fehlgeschlagen. Erneut versuchen.", "N\xE3o foi poss\xEDvel conectar a voz. Tente novamente."],
986
+ voicePeerGone: ["This participant has left voice.", "Questo partecipante e' uscito dalla voce.", "Este participante sali\xF3 de voz.", "Ce participant a quitt\xE9 la voix.", "Diese Person hat den Sprachchat verlassen.", "Este participante saiu da voz."],
987
+ shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab"],
988
+ menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual"],
989
+ retry: ["Retry", "Riprova", "Reintentar", "R\xE9essayer", "Erneut versuchen", "Tentar novamente"]
990
+ };
991
+ var column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));
992
+ var dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5) };
993
+ function overlayLocale(raw) {
994
+ const tag = normalizeLanguage(raw);
995
+ return tag && languages.includes(tag.split("-")[0]) ? tag : "en";
996
+ }
997
+
998
+ // src/text.ts
999
+ function createTextLoader(fetcher, language, pathname = "/") {
1000
+ let pending;
1001
+ const root = pathname.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0] ?? "/";
1002
+ return () => pending ?? (pending = (async () => {
1003
+ let dictionary = {};
1004
+ try {
1005
+ const response = await fetcher(`${root}__caisual/text/${encodeURIComponent(language)}.json`);
1006
+ if (response.ok) {
1007
+ const value = await response.json();
1008
+ if (isTextDictionary(value)) dictionary = value;
1009
+ }
1010
+ } catch {
1011
+ }
1012
+ return (key, values = {}) => {
1013
+ if (!Object.hasOwn(dictionary, key)) return key;
1014
+ const text = dictionary[key];
1015
+ return text.replace(/\{([^{}]+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
1016
+ };
1017
+ })());
1018
+ }
1019
+
787
1020
  // src/errors.ts
788
1021
  function creaErrore(code, message) {
789
1022
  return Object.assign(new Error(message), { name: "CaisualError", code });
@@ -870,7 +1103,7 @@ function createSession(base, configuration = null, roomsAvailable = base.connect
870
1103
  let pending = null, pendingMode = null;
871
1104
  let waiting = null, controller = null;
872
1105
  let stops = [], disposed = false, lastState = "";
873
- let view = { inputBlocked: false, reservedRects: [] };
1106
+ let view = { inputBlocked: standard, reservedRects: [], safeArea: { top: 0, right: 0, bottom: 0, left: 0 } };
874
1107
  const listeners = /* @__PURE__ */ new Set();
875
1108
  const viewListeners = /* @__PURE__ */ new Set();
876
1109
  const stateListeners = /* @__PURE__ */ new Set();
@@ -1133,7 +1366,10 @@ function createSession(base, configuration = null, roomsAvailable = base.connect
1133
1366
  if (!standard) throw creaErrore("overlay_disabled", "This game uses its own room flow.");
1134
1367
  if (request.op === "overlay.view") {
1135
1368
  if (!validOverlayView(request.args)) throw creaErrore("invalid_request", "The overlay geometry is invalid.");
1136
- view = structuredClone(request.args);
1369
+ view = { ...structuredClone(request.args), safeArea: { top: 0, right: 0, bottom: 0, left: 0, ...request.args.safeArea } };
1370
+ if (typeof document !== "undefined") for (const [side, value] of Object.entries(view.safeArea)) {
1371
+ document.documentElement.style.setProperty(`--caisual-safe-${side}`, `${value}px`);
1372
+ }
1137
1373
  notify(viewListeners, structuredClone(view));
1138
1374
  return;
1139
1375
  }
@@ -1205,6 +1441,9 @@ function createSession(base, configuration = null, roomsAvailable = base.connect
1205
1441
  case "room.start":
1206
1442
  active().start();
1207
1443
  return;
1444
+ case "room.restart":
1445
+ active().restart();
1446
+ return;
1208
1447
  case "session.cancel":
1209
1448
  cancel();
1210
1449
  return;
@@ -1505,8 +1744,13 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
1505
1744
  if (typeof dati?.ticket !== "string" || porta === void 0) return;
1506
1745
  porta.start();
1507
1746
  const overlay = normalizeOverlayHello(dati.overlay);
1747
+ const tags = (value) => Array.isArray(value) ? value.map(normalizeLanguage).filter((tag) => tag !== null) : void 0;
1508
1748
  termina({
1509
1749
  ...overlay ? { overlay } : {},
1750
+ ...normalizeLanguage(dati.language) ? { language: normalizeLanguage(dati.language) } : {},
1751
+ uiLanguage: normalizeLanguage(dati.uiLanguage) ?? void 0,
1752
+ languagePreferences: tags(dati.languagePreferences),
1753
+ gameLanguages: tags(dati.gameLanguages),
1510
1754
  ticket: dati.ticket,
1511
1755
  live: leggiOrigine(dati.live),
1512
1756
  invite: typeof dati.invite === "string" ? dati.invite : null,
@@ -2473,8 +2717,7 @@ var GRAZIA_RICONNESSIONE = 6e4;
2473
2717
  var INTERVALLO_PING = 5e3;
2474
2718
  var RITARDO_FLUSH = 500;
2475
2719
  var ATTESA_ROSTER = 2e3;
2476
- var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
2477
- var CHIUSURE_DEFINITIVE_SPETTATORE = /* @__PURE__ */ new Set([4008, 4009]);
2720
+ var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006, 4008, 4009]);
2478
2721
  function record3(value) {
2479
2722
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2480
2723
  }
@@ -2579,10 +2822,10 @@ function creaApiLive(input) {
2579
2822
  };
2580
2823
  }
2581
2824
  var StanzaClient = class {
2582
- constructor(roomId, codice, url, input, api, segnalaStanza, spettatore = false) {
2825
+ constructor(roomId, codice, url, dipendenze, api, segnalaStanza, spettatore = false) {
2583
2826
  this.roomId = roomId;
2584
2827
  this.codice = codice;
2585
- this.input = input;
2828
+ this.dipendenze = dipendenze;
2586
2829
  this.api = api;
2587
2830
  this.segnalaStanza = segnalaStanza;
2588
2831
  this.spettatore = spettatore;
@@ -2597,6 +2840,13 @@ var StanzaClient = class {
2597
2840
  this.statoPubblico = null;
2598
2841
  this.statoSincronizzato = null;
2599
2842
  this.tickCorrente = 0;
2843
+ this.tickRateCorrente = 0;
2844
+ this.latenzaCorrente = null;
2845
+ this.ultimoInput = null;
2846
+ this.inputInviato = null;
2847
+ this.timerInput = null;
2848
+ this.ultimoInvioGioco = -Infinity;
2849
+ this.inviiGioco = [];
2600
2850
  this.seedCorrente = 0;
2601
2851
  this.statusCorrente = "lobby";
2602
2852
  this.giocatoriCorrenti = [];
@@ -2640,7 +2890,7 @@ var StanzaClient = class {
2640
2890
  this.rosterRicevuto = true;
2641
2891
  this.risolviProntaSePossibile();
2642
2892
  }
2643
- }, input, input.voce);
2893
+ }, dipendenze, dipendenze.voce);
2644
2894
  if (spettatore) this.rosterRicevuto = true;
2645
2895
  this.apri(url);
2646
2896
  }
@@ -2699,7 +2949,7 @@ var StanzaClient = class {
2699
2949
  if (this.roleRequests.size >= 8) return Promise.reject(creaErrore("rate_limited", "Too many role requests."));
2700
2950
  const r = ++this.roleId;
2701
2951
  return new Promise((resolve, reject) => {
2702
- const timer = this.input.setTimeout(() => {
2952
+ const timer = this.dipendenze.setTimeout(() => {
2703
2953
  this.roleRequests.delete(r);
2704
2954
  reject(creaErrore("timeout", "The role request timed out."));
2705
2955
  }, 5e3);
@@ -2707,7 +2957,7 @@ var StanzaClient = class {
2707
2957
  try {
2708
2958
  this.invia({ t: "request-role", r, role });
2709
2959
  } catch (error) {
2710
- this.input.clearTimeout(timer);
2960
+ this.dipendenze.clearTimeout(timer);
2711
2961
  this.roleRequests.delete(r);
2712
2962
  reject(error);
2713
2963
  }
@@ -2715,7 +2965,7 @@ var StanzaClient = class {
2715
2965
  }
2716
2966
  clearRoleRequests() {
2717
2967
  for (const request of this.roleRequests.values()) {
2718
- this.input.clearTimeout(request.timer);
2968
+ this.dipendenze.clearTimeout(request.timer);
2719
2969
  request.reject(creaErrore("offline", "The room connection ended."));
2720
2970
  }
2721
2971
  this.roleRequests.clear();
@@ -2726,10 +2976,11 @@ var StanzaClient = class {
2726
2976
  const socket = this.socket;
2727
2977
  this.socket = null;
2728
2978
  this.voice.termina();
2979
+ this.fermaInput();
2729
2980
  this.fermaPing();
2730
2981
  this.fermaRiconnessione();
2731
2982
  this.clearRoleRequests();
2732
- if (this.timerRoster !== null) this.input.clearTimeout(this.timerRoster);
2983
+ if (this.timerRoster !== null) this.dipendenze.clearTimeout(this.timerRoster);
2733
2984
  socket?.close(1e3);
2734
2985
  this.segnalaStanza(null);
2735
2986
  this.metadataChanged({ connection: "disconnected", closedCode: null });
@@ -2744,6 +2995,12 @@ var StanzaClient = class {
2744
2995
  get tick() {
2745
2996
  return this.tickCorrente;
2746
2997
  }
2998
+ get tickRate() {
2999
+ return this.tickRateCorrente;
3000
+ }
3001
+ get latency() {
3002
+ return this.latenzaCorrente;
3003
+ }
2747
3004
  get seed() {
2748
3005
  return this.seedCorrente;
2749
3006
  }
@@ -2772,7 +3029,7 @@ var StanzaClient = class {
2772
3029
  return this.promessaPronta;
2773
3030
  }
2774
3031
  invite() {
2775
- return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };
3032
+ return { code: this.codice, url: new URL(`/r/${this.codice}`, this.dipendenze.appOrigin).href };
2776
3033
  }
2777
3034
  onState(listener) {
2778
3035
  this.ascoltatoriStato.add(listener);
@@ -2799,9 +3056,63 @@ var StanzaClient = class {
2799
3056
  };
2800
3057
  }
2801
3058
  send(message) {
3059
+ if (this.statusCorrente === "finished") return;
2802
3060
  const prossimo = this.seq + 1;
2803
3061
  this.invia({ t: "msg", seq: prossimo, m: message });
2804
3062
  this.seq = prossimo;
3063
+ this.ultimoInvioGioco = this.dipendenze.ora();
3064
+ this.inviiGioco = [...this.inviiGioco.slice(-(MESSAGGI_GIOCO_AL_SECONDO - 1)), this.ultimoInvioGioco];
3065
+ }
3066
+ input(value) {
3067
+ if (this.terminata || this.lasciata || this.statusCorrente === "finished") return;
3068
+ try {
3069
+ const serializzato = JSON.stringify(value);
3070
+ if (serializzato === void 0) throw new TypeError();
3071
+ this.ultimoInput = serializzato;
3072
+ } catch {
3073
+ throw creaErrore("invalid_request", "Room input must be valid JSON.");
3074
+ }
3075
+ this.programmaInput();
3076
+ }
3077
+ pulisciInput() {
3078
+ this.fermaInput();
3079
+ this.ultimoInput = this.inputInviato = null;
3080
+ this.ultimoInvioGioco = -Infinity;
3081
+ this.inviiGioco = [];
3082
+ }
3083
+ fermaInput() {
3084
+ if (this.timerInput !== null) this.dipendenze.clearTimeout(this.timerInput);
3085
+ this.timerInput = null;
3086
+ }
3087
+ programmaInput() {
3088
+ if (this.timerInput !== null || this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3089
+ const ora = this.dipendenze.ora();
3090
+ const frequenza = this.tickRateCorrente > 0 ? Math.min(MESSAGGI_GIOCO_AL_SECONDO, this.tickRateCorrente) : MESSAGGI_GIOCO_AL_SECONDO;
3091
+ const periodo = 1e3 / frequenza;
3092
+ this.inviiGioco = this.inviiGioco.filter((at) => ora - at < 1e3);
3093
+ const spazio = this.inviiGioco.length >= MESSAGGI_GIOCO_AL_SECONDO ? this.inviiGioco[0] + 1e3 : ora;
3094
+ const prossimo = Number.isFinite(this.ultimoInvioGioco) ? this.ultimoInvioGioco + periodo : ora + periodo;
3095
+ this.timerInput = this.dipendenze.setTimeout(() => {
3096
+ this.timerInput = null;
3097
+ if (this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3098
+ const adesso = this.dipendenze.ora();
3099
+ if (adesso < this.ultimoInvioGioco + periodo || this.inviiGioco.filter((at) => adesso - at < 1e3).length >= MESSAGGI_GIOCO_AL_SECONDO) {
3100
+ this.programmaInput();
3101
+ return;
3102
+ }
3103
+ const valore = this.ultimoInput;
3104
+ try {
3105
+ this.send(JSON.parse(valore));
3106
+ this.inputInviato = valore;
3107
+ } catch {
3108
+ }
3109
+ }, Math.max(0, Math.ceil(Math.max(prossimo, spazio) - ora)));
3110
+ }
3111
+ aggiornaTickRate(value) {
3112
+ if (value === void 0 || !Number.isInteger(value) || value < 0 || value > 60 || value === this.tickRateCorrente) return;
3113
+ this.tickRateCorrente = value;
3114
+ this.fermaInput();
3115
+ this.programmaInput();
2805
3116
  }
2806
3117
  ready(ready) {
2807
3118
  this.invia({ t: "ready", ready });
@@ -2815,6 +3126,10 @@ var StanzaClient = class {
2815
3126
  start() {
2816
3127
  this.invia({ t: "start" });
2817
3128
  }
3129
+ restart() {
3130
+ if (this.statusCorrente !== "finished") throw creaErrore("rematch_unavailable", "This room is not waiting for a rematch.");
3131
+ this.invia({ t: "restart" });
3132
+ }
2818
3133
  leave() {
2819
3134
  if (this.lasciata) return;
2820
3135
  if (!this.spettatore) this.voice.leave();
@@ -2828,7 +3143,7 @@ var StanzaClient = class {
2828
3143
  this.termina(1e3);
2829
3144
  }
2830
3145
  serverTime() {
2831
- return this.input.ora() + this.scartoOrario;
3146
+ return this.dipendenze.ora() + this.scartoOrario;
2832
3147
  }
2833
3148
  copiaGiocatori() {
2834
3149
  return this.giocatoriCorrenti.map((player) => ({ ...player }));
@@ -2856,7 +3171,7 @@ var StanzaClient = class {
2856
3171
  apri(url) {
2857
3172
  let socket;
2858
3173
  try {
2859
- socket = this.input.apriSocket(url);
3174
+ socket = this.dipendenze.apriSocket(url);
2860
3175
  } catch {
2861
3176
  this.programmaRiconnessione();
2862
3177
  return;
@@ -2869,22 +3184,22 @@ var StanzaClient = class {
2869
3184
  if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);
2870
3185
  });
2871
3186
  socket.addEventListener("close", (evento) => {
2872
- if (this.socket === socket) this.chiuso(evento.code);
3187
+ if (this.socket === socket) this.chiuso(evento.code, evento.reason);
2873
3188
  });
2874
3189
  }
2875
3190
  avviaPing() {
2876
- if (this.timerPing !== null) this.input.clearInterval(this.timerPing);
2877
- this.timerPing = this.input.setInterval(() => {
3191
+ if (this.timerPing !== null) this.dipendenze.clearInterval(this.timerPing);
3192
+ this.timerPing = this.dipendenze.setInterval(() => {
2878
3193
  if (this.socket?.readyState !== APERTO) return;
2879
3194
  try {
2880
- this.invia({ t: "ping", c: this.input.ora() });
3195
+ this.invia({ t: "ping", c: this.dipendenze.ora() });
2881
3196
  } catch {
2882
3197
  }
2883
3198
  }, INTERVALLO_PING);
2884
3199
  }
2885
3200
  fermaPing() {
2886
3201
  if (this.timerPing === null) return;
2887
- this.input.clearInterval(this.timerPing);
3202
+ this.dipendenze.clearInterval(this.timerPing);
2888
3203
  this.timerPing = null;
2889
3204
  }
2890
3205
  ricevi(frame) {
@@ -2915,7 +3230,7 @@ var StanzaClient = class {
2915
3230
  } else if (dati.t === "role-result") {
2916
3231
  const request = this.roleRequests.get(dati.r);
2917
3232
  if (request) {
2918
- this.input.clearTimeout(request.timer);
3233
+ this.dipendenze.clearTimeout(request.timer);
2919
3234
  this.roleRequests.delete(dati.r);
2920
3235
  if (dati.ok) request.resolve();
2921
3236
  else request.reject(creaErrore(dati.code ?? "role_change_refused", "The role change was not accepted."));
@@ -2928,13 +3243,16 @@ var StanzaClient = class {
2928
3243
  riceviWatching(dati) {
2929
3244
  const room = dati.room;
2930
3245
  if (!this.spettatore || room.id !== this.roomId) return;
3246
+ this.aggiornaTickRate(room.tickRate);
2931
3247
  this.seedCorrente = room.seed;
2932
3248
  this.hostCorrente = room.host;
2933
3249
  this.statusCorrente = room.status;
3250
+ this.resultCorrente = copiaJson(room.result ?? null);
3251
+ if (room.status === "finished") this.pulisciInput();
2934
3252
  this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
2935
3253
  this.delaySpettatore = dati.delayMs;
2936
3254
  this.aggiornaStato(dati.state, room.tick, room.serverTime);
2937
- this.scartoOrario = room.serverTime - this.input.ora();
3255
+ this.scartoOrario = room.serverTime - this.dipendenze.ora();
2938
3256
  this.resyncRichiesto = false;
2939
3257
  this.welcomeRicevuto = true;
2940
3258
  this.ritardoIndice = 0;
@@ -2947,22 +3265,26 @@ var StanzaClient = class {
2947
3265
  room.serverTime
2948
3266
  );
2949
3267
  this.initialMetadata(room);
3268
+ this.programmaInput();
2950
3269
  this.risolviProntaSePossibile();
2951
3270
  }
2952
3271
  riceviWelcome(dati) {
2953
3272
  const room = dati.room;
2954
3273
  if (room.id !== this.roomId) return;
2955
3274
  this.youCorrente = dati.you;
3275
+ this.aggiornaTickRate(room.tickRate);
2956
3276
  this.seedCorrente = room.seed;
2957
3277
  this.hostCorrente = room.host;
2958
3278
  this.statusCorrente = room.status;
3279
+ this.resultCorrente = copiaJson(room.result ?? null);
3280
+ if (room.status === "finished") this.pulisciInput();
2959
3281
  this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
2960
3282
  this.aggiornaStato(dati.state, room.tick, room.serverTime);
2961
- this.scartoOrario = room.serverTime - this.input.ora();
3283
+ this.scartoOrario = room.serverTime - this.dipendenze.ora();
2962
3284
  this.resyncRichiesto = false;
2963
3285
  this.welcomeRicevuto = true;
2964
3286
  if (!this.rosterRicevuto && this.timerRoster === null) {
2965
- this.timerRoster = this.input.setTimeout(() => {
3287
+ this.timerRoster = this.dipendenze.setTimeout(() => {
2966
3288
  this.timerRoster = null;
2967
3289
  this.rosterRicevuto = true;
2968
3290
  this.risolviProntaSePossibile();
@@ -2980,6 +3302,7 @@ var StanzaClient = class {
2980
3302
  room.serverTime
2981
3303
  );
2982
3304
  this.initialMetadata(room);
3305
+ this.programmaInput();
2983
3306
  this.risolviProntaSePossibile();
2984
3307
  }
2985
3308
  riceviGiocatori(value, host) {
@@ -2998,6 +3321,10 @@ var StanzaClient = class {
2998
3321
  this.statusCorrente = dati.status;
2999
3322
  if (dati.host !== void 0) this.hostCorrente = dati.host;
3000
3323
  this.resultCorrente = copiaJson(dati.result);
3324
+ if (dati.status === "finished") {
3325
+ this.pulisciInput();
3326
+ this.clearRoleRequests();
3327
+ }
3001
3328
  if (dati.status === "ended") {
3002
3329
  this.terminata = true;
3003
3330
  this.clearRoleRequests();
@@ -3005,6 +3332,8 @@ var StanzaClient = class {
3005
3332
  if (!this.spettatore) this.voice.termina();
3006
3333
  this.fermaPing();
3007
3334
  this.fermaRiconnessione();
3335
+ this.fermaInput();
3336
+ this.ultimoInput = null;
3008
3337
  }
3009
3338
  this.metadataChanged({
3010
3339
  host: this.hostCorrente,
@@ -3014,6 +3343,7 @@ var StanzaClient = class {
3014
3343
  this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
3015
3344
  }
3016
3345
  riceviDiff(dati) {
3346
+ this.aggiornaTickRate(dati.tickRate);
3017
3347
  if (dati.base !== this.tickCorrente) {
3018
3348
  this.chiediResync();
3019
3349
  return;
@@ -3028,6 +3358,7 @@ var StanzaClient = class {
3028
3358
  }
3029
3359
  riceviSnapshot(dati) {
3030
3360
  if (dati.tick < this.tickCorrente) return;
3361
+ this.aggiornaTickRate(dati.tickRate);
3031
3362
  this.resyncRichiesto = false;
3032
3363
  this.aggiornaStato(dati.state, dati.tick, dati.serverTime);
3033
3364
  }
@@ -3047,15 +3378,26 @@ var StanzaClient = class {
3047
3378
  }
3048
3379
  }
3049
3380
  riceviPong(dati) {
3050
- this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;
3381
+ const ora = this.dipendenze.ora();
3382
+ if (!Number.isFinite(dati.c) || !Number.isFinite(dati.s) || dati.c > ora) return;
3383
+ const rtt = ora - dati.c;
3384
+ this.latenzaCorrente = this.latenzaCorrente === null ? rtt : this.latenzaCorrente * 0.8 + rtt * 0.2;
3385
+ this.scartoOrario = dati.s - (dati.c + ora) / 2;
3051
3386
  }
3052
- chiuso(code) {
3387
+ chiuso(code, reason) {
3053
3388
  this.socket = null;
3054
3389
  this.welcomeRicevuto = false;
3390
+ this.latenzaCorrente = null;
3391
+ this.fermaInput();
3392
+ this.inputInviato = null;
3393
+ this.ultimoInvioGioco = -Infinity;
3394
+ this.inviiGioco = [];
3055
3395
  this.fermaPing();
3056
3396
  if (this.lasciata || this.terminata) return;
3057
- if (CHIUSURE_DEFINITIVE.has(code) || this.spettatore && CHIUSURE_DEFINITIVE_SPETTATORE.has(code)) {
3058
- this.termina(code);
3397
+ if (CHIUSURE_DEFINITIVE.has(code)) {
3398
+ const errore = code === 4009 && reason === "message_too_large" ? "message_too_large" : void 0;
3399
+ if (errore) this.notifica(this.errorListeners, { code: errore, message: "The room message is too large." });
3400
+ this.termina(code, errore);
3059
3401
  return;
3060
3402
  }
3061
3403
  this.clearRoleRequests();
@@ -3073,7 +3415,7 @@ var StanzaClient = class {
3073
3415
  }
3074
3416
  this.ritardoIndice++;
3075
3417
  this.tempoRiconnessione += ritardo;
3076
- this.timerRiconnessione = this.input.setTimeout(() => {
3418
+ this.timerRiconnessione = this.dipendenze.setTimeout(() => {
3077
3419
  this.timerRiconnessione = null;
3078
3420
  void this.riconnetti();
3079
3421
  }, ritardo);
@@ -3095,15 +3437,17 @@ var StanzaClient = class {
3095
3437
  }
3096
3438
  fermaRiconnessione() {
3097
3439
  if (this.timerRiconnessione === null) return;
3098
- this.input.clearTimeout(this.timerRiconnessione);
3440
+ this.dipendenze.clearTimeout(this.timerRiconnessione);
3099
3441
  this.timerRiconnessione = null;
3100
3442
  }
3101
- termina(code) {
3443
+ termina(code, errore) {
3102
3444
  this.clearRoleRequests();
3103
3445
  this.metadataChanged({ connection: code === 1e3 ? "disconnected" : code === 4006 ? "replaced" : "closed", closedCode: typeof code === "number" ? code : null });
3104
3446
  const risultato = { closed: code };
3105
3447
  const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
3106
3448
  this.terminata = true;
3449
+ this.fermaInput();
3450
+ this.ultimoInput = null;
3107
3451
  this.segnalaStanza(null);
3108
3452
  this.statusCorrente = "ended";
3109
3453
  this.resultCorrente = risultato;
@@ -3121,14 +3465,14 @@ var StanzaClient = class {
3121
3465
  4008: "rate_limited",
3122
3466
  4009: "invalid_request"
3123
3467
  };
3124
- const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";
3468
+ const erroreCode = errore ?? (typeof code === "number" ? codici[code] ?? "offline" : "offline");
3125
3469
  this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));
3126
3470
  }
3127
3471
  }
3128
3472
  risolviProntaSePossibile() {
3129
3473
  if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;
3130
3474
  if (this.timerRoster !== null) {
3131
- this.input.clearTimeout(this.timerRoster);
3475
+ this.dipendenze.clearTimeout(this.timerRoster);
3132
3476
  this.timerRoster = null;
3133
3477
  }
3134
3478
  this.prontaRisolta = true;
@@ -3140,7 +3484,7 @@ var StanzaClient = class {
3140
3484
  richiediFlush() {
3141
3485
  this.flushRichiesto = true;
3142
3486
  if (this.flushInCorso || this.timerFlush !== null) return;
3143
- this.timerFlush = this.input.setTimeout(() => {
3487
+ this.timerFlush = this.dipendenze.setTimeout(() => {
3144
3488
  this.timerFlush = null;
3145
3489
  void this.eseguiFlush();
3146
3490
  }, RITARDO_FLUSH);
@@ -3231,6 +3575,12 @@ function creaGestoreStanze(input, invited) {
3231
3575
  get tick() {
3232
3576
  return stanza.tick;
3233
3577
  },
3578
+ get tickRate() {
3579
+ return stanza.tickRate;
3580
+ },
3581
+ get latency() {
3582
+ return stanza.latency;
3583
+ },
3234
3584
  get seed() {
3235
3585
  return stanza.seed;
3236
3586
  },
@@ -3459,7 +3809,7 @@ async function creaStandalone(input, invited = null) {
3459
3809
  return {
3460
3810
  connected: false,
3461
3811
  player: { id: "local", name: "Guest", guest: true },
3462
- daily: { day, seed, random: creaMulberry32(seed) },
3812
+ daily: { day, seed, random: creaMulberry32(seed), rng: () => creaMulberry32(seed) },
3463
3813
  time: { now: input.ora },
3464
3814
  save: creaSave(input.archivio, input.ora),
3465
3815
  board: {
@@ -3499,6 +3849,8 @@ function dipendenzeReali2() {
3499
3849
  documento: typeof document === "undefined" ? null : document,
3500
3850
  fetcher: (input, init) => globalThis.fetch(input, init),
3501
3851
  archivio: archivioReale(),
3852
+ language: typeof navigator === "undefined" ? "en" : navigator.language,
3853
+ pathname: typeof location === "undefined" ? "/" : location.pathname,
3502
3854
  hostname: typeof location === "undefined" ? "" : location.hostname,
3503
3855
  subtle: globalThis.crypto.subtle,
3504
3856
  ora: Date.now,
@@ -3569,7 +3921,7 @@ async function connetti(input) {
3569
3921
  const base = {
3570
3922
  connected: true,
3571
3923
  player: me.player,
3572
- daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },
3924
+ daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed), rng: () => creaMulberry32(me.seed) },
3573
3925
  time: { now: () => input.ora() + scartoOrario },
3574
3926
  save: {
3575
3927
  set: (key, value) => api.saveSet(key, value),
@@ -3598,10 +3950,20 @@ function installSession(base, handshake, input) {
3598
3950
  const dispose = attachKitBridge(handshake.porta, handshake.overlay, coordinator);
3599
3951
  if (coordinator.session.capabilities.overlay && typeof window !== "undefined" && input?.finestra === window) window.addEventListener("pagehide", dispose, { once: true });
3600
3952
  }
3601
- return { ...base, room: coordinator.rooms, session: coordinator.session, overlay: coordinator.overlay };
3953
+ const preferences = handshake?.languagePreferences?.length ? handshake.languagePreferences : [handshake?.language ?? input?.language ?? "en"];
3954
+ const language = resolveGameLanguage(preferences, handshake?.gameLanguages ?? (handshake?.overlay ? manifestLanguages(handshake.overlay.configuration.manifest) : void 0));
3955
+ const uiLanguage = overlayLocale(handshake?.uiLanguage ?? handshake?.language ?? input?.language);
3956
+ return {
3957
+ ...base,
3958
+ player: { ...base.player, language, uiLanguage },
3959
+ text: createTextLoader(input?.fetcher ?? globalThis.fetch, language, input?.pathname),
3960
+ room: coordinator.rooms,
3961
+ session: coordinator.session,
3962
+ overlay: coordinator.overlay
3963
+ };
3602
3964
  }
3603
3965
  async function localConnection(input) {
3604
- return installSession(await creaStandalone(input));
3966
+ return installSession(await creaStandalone(input), void 0, input);
3605
3967
  }
3606
3968
  function dispositivoSconosciuto() {
3607
3969
  return {