@caisual/cli 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.
Files changed (2) hide show
  1. package/dist/caisual.mjs +808 -1113
  2. package/package.json +11 -12
package/dist/caisual.mjs CHANGED
@@ -1,9 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/i18n.ts
4
- import { promises as fs2 } from "node:fs";
5
- import { join as join2, sep as sep2 } from "node:path";
6
-
7
3
  // ../contracts/src/slug.ts
8
4
  var NOMI_RISERVATI = [
9
5
  "www",
@@ -76,7 +72,7 @@ function isTextDictionary(value) {
76
72
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === "string");
77
73
  }
78
74
  async function loadGameTexts(language, defaultLanguage, read) {
79
- const dictionaries2 = await Promise.all(languageFallbacks(language, defaultLanguage).map(async (tag) => {
75
+ const dictionaries = await Promise.all(languageFallbacks(language, defaultLanguage).map(async (tag) => {
80
76
  try {
81
77
  const value = await read(tag);
82
78
  return isTextDictionary(value) ? value : {};
@@ -84,7 +80,7 @@ async function loadGameTexts(language, defaultLanguage, read) {
84
80
  return {};
85
81
  }
86
82
  }));
87
- return Object.assign(/* @__PURE__ */ Object.create(null), ...dictionaries2.reverse());
83
+ return Object.assign(/* @__PURE__ */ Object.create(null), ...dictionaries.reverse());
88
84
  }
89
85
 
90
86
  // ../contracts/src/manifest.ts
@@ -94,20 +90,20 @@ function risolviModalita(manifest, mode) {
94
90
  return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
95
91
  }
96
92
  function richiedeServer(manifest) {
97
- return manifest.modes.some((mode) => mode.execution === "room");
93
+ return manifest.modes.length > 0 ? manifest.modes.some((mode) => risolviModalita(manifest, mode.id).players.max > 1) : manifest.players.max > 1;
98
94
  }
99
95
  function modalitaLocale(manifest, mode) {
100
- return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
96
+ return risolviModalita(manifest, mode).players.max === 1;
101
97
  }
98
+ var SINGLE_PLAYER_RULE = "Single player runs in the browser and never touches the server; a room exists only for two or more players.";
99
+ var MODE_LOCAL_MESSAGE = "Single-player modes run in the browser and have no room.";
100
+ var AVVISO_SERVER_INUTILE = "server.js is unnecessary: all modes run in the browser.";
102
101
  var AVVISO_ISOLATED = "isolated has no effect: games run inside the portal page, which is not cross-origin isolated";
103
102
  function avvisiManifest(value) {
104
103
  return typeof value === "object" && value !== null && Object.hasOwn(value, "isolated") ? [AVVISO_ISOLATED] : [];
105
104
  }
106
105
  var TETTO_GIOCATORI = 24;
107
- var RITARDO_SPETTATORI_MS = 3e3;
108
- var MASSIMO_CLASSIFICHE = 32;
109
106
  var CAMPI = /* @__PURE__ */ new Set([
110
- "overlay",
111
107
  "manifest",
112
108
  "id",
113
109
  "name",
@@ -129,14 +125,13 @@ var CAMPI = /* @__PURE__ */ new Set([
129
125
  "players",
130
126
  "lobby",
131
127
  "persistent",
132
- "replays",
133
- "spectators",
134
- "boards",
135
128
  "roles",
136
129
  "teams",
137
130
  "voice",
138
131
  "modes"
139
132
  ]);
133
+ var CAMPI_RIMOSSI = /* @__PURE__ */ new Set(["overlay", "replays", "boards"]);
134
+ var MOTIVO_RIMOSSO = "this field no longer exists.";
140
135
  var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
141
136
  var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
142
137
  var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
@@ -146,7 +141,6 @@ var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
146
141
  var TAG = /^[a-z0-9-]+$/;
147
142
  var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
148
143
  var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
149
- var ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
150
144
  function oggetto(value) {
151
145
  if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
152
146
  return value;
@@ -183,11 +177,12 @@ function stringaDefault(dati, campo, valoreDefault, errori) {
183
177
  }
184
178
  return value;
185
179
  }
186
- function testoFacoltativo(value, key, max, path, errors) {
180
+ function testoFacoltativo(value, key, max, path, errors, sottotitolo = false) {
187
181
  if (value[key] === void 0) return void 0;
188
182
  const check2 = (text2, field2) => {
189
- if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\r\n\u0000-\u001f]/.test(text2)) {
190
- errors.push(`${field2}: must contain 1-${max} characters on one line.`);
183
+ const length = typeof text2 === "string" ? sottotitolo ? [...text2.trim()].length : text2.trim().length : 0;
184
+ if (typeof text2 !== "string" || length === 0 || length > max || /[\r\n\u0000-\u001f]/.test(text2) || sottotitolo && /[\u2028\u2029]/.test(text2)) {
185
+ errors.push(sottotitolo ? `${field2}: must be a one-line subtitle of 1-${max} characters after trimming whitespace.` : `${field2}: must contain 1-${max} characters on one line.`);
191
186
  return void 0;
192
187
  }
193
188
  return text2.trim();
@@ -213,11 +208,19 @@ function testoFacoltativo(value, key, max, path, errors) {
213
208
  return result;
214
209
  }
215
210
  function validaManifest(valore) {
211
+ return validaDocumentoManifest(valore, false);
212
+ }
213
+ function validaManifestPubblicazione(valore) {
214
+ return validaDocumentoManifest(valore, true);
215
+ }
216
+ function validaDocumentoManifest(valore, pubblicazione) {
216
217
  const errori = [];
217
218
  const dati = oggetto(valore);
218
219
  if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
219
220
  for (const campo of Object.keys(dati)) {
220
- if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
221
+ if (CAMPI_RIMOSSI.has(campo)) {
222
+ if (pubblicazione) errori.push(`${campo}: ${MOTIVO_RIMOSSO}`);
223
+ } else if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
221
224
  }
222
225
  if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
223
226
  else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
@@ -233,7 +236,7 @@ function validaManifest(valore) {
233
236
  else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
234
237
  errori.push("name: must contain 1-60 characters.");
235
238
  }
236
- const description = dati.description === "" ? "" : testoFacoltativo(dati, "description", 500, "", errori) ?? "";
239
+ const description = dati.description === "" ? "" : testoFacoltativo(dati, "description", pubblicazione ? 80 : 500, "", errori, pubblicazione) ?? "";
237
240
  const immagini = { cover: "", card: "", icon: "" };
238
241
  const usati = /* @__PURE__ */ new Set();
239
242
  for (const campo of ["cover", "card", "icon"]) {
@@ -396,80 +399,6 @@ function validaManifest(valore) {
396
399
  if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
397
400
  else persistent = dati.persistent;
398
401
  }
399
- const replays = dati.replays === true;
400
- if (dati.replays !== void 0 && typeof dati.replays !== "boolean") errori.push("replays: must be a boolean.");
401
- let spectators = { delayMs: RITARDO_SPETTATORI_MS };
402
- if (dati.spectators === false || dati.spectators === null) spectators = null;
403
- else if (dati.spectators !== void 0 && dati.spectators !== true) {
404
- const value = oggetto(dati.spectators);
405
- if (value === null) {
406
- errori.push("spectators: must be a boolean or an object with delayMs.");
407
- } else {
408
- for (const campo of Object.keys(value)) {
409
- if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);
410
- }
411
- if (!interoTra(value.delayMs, 0, 3e4)) {
412
- errori.push("spectators.delayMs: must be an integer from 0 to 30000.");
413
- } else spectators = { delayMs: value.delayMs };
414
- }
415
- }
416
- let overlay = null;
417
- if (dati.overlay !== void 0 && dati.overlay !== null) {
418
- const value = oggetto(dati.overlay);
419
- if (value === null) errori.push("overlay: must be an object or null.");
420
- else {
421
- for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);
422
- if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");
423
- if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {
424
- errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");
425
- }
426
- overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };
427
- }
428
- }
429
- const boards = {};
430
- if (dati.boards !== void 0) {
431
- const value = oggetto(dati.boards);
432
- if (value === null) errori.push("boards: must be an object of board ids.");
433
- else {
434
- if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {
435
- errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);
436
- }
437
- for (const [id2, raw] of Object.entries(value)) {
438
- let valido = true;
439
- if (!ID_CLASSIFICA.test(id2)) {
440
- errori.push(`boards.${id2}: invalid board id.`);
441
- valido = false;
442
- }
443
- const board = oggetto(raw);
444
- if (board === null) {
445
- errori.push(`boards.${id2}.source: must be "client" or "server".`);
446
- continue;
447
- }
448
- for (const campo of Object.keys(board)) {
449
- if (!["source", "label", "periods", "day"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
450
- }
451
- if (board.source !== "client" && board.source !== "server") {
452
- errori.push(`boards.${id2}.source: must be "client" or "server".`);
453
- valido = false;
454
- }
455
- if (board.day !== void 0 && board.day !== "submit" && board.day !== "start") errori.push(`boards.${id2}.day: must be "submit" or "start".`);
456
- if (board.day === "start" && board.source !== "server") errori.push(`boards.${id2}.day: start requires source "server".`);
457
- const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
458
- let periods = ["all-time"];
459
- if (board.periods !== void 0) {
460
- if (!Array.isArray(board.periods) || board.periods.length < 1 || board.periods.length > 2 || board.periods.some((period) => period !== "daily" && period !== "all-time") || new Set(board.periods).size !== board.periods.length) {
461
- errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);
462
- } else periods = [...board.periods];
463
- }
464
- if (valido) Object.defineProperty(boards, id2, { value: {
465
- source: board.source,
466
- periods,
467
- ...board.day === void 0 ? {} : { day: board.day },
468
- ...label === void 0 ? {} : { label }
469
- }, enumerable: true, configurable: true, writable: true });
470
- }
471
- }
472
- }
473
402
  const roles = [];
474
403
  if (dati.roles !== void 0) {
475
404
  if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
@@ -482,7 +411,9 @@ function validaManifest(valore) {
482
411
  continue;
483
412
  }
484
413
  for (const campo of Object.keys(value)) {
485
- if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
414
+ if (campo === "label") {
415
+ if (pubblicazione) errori.push(`roles[${indice}].label: ${MOTIVO_RIMOSSO}`);
416
+ } else if (!["id", "min", "max"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
486
417
  }
487
418
  const idRuolo = value.id;
488
419
  const min = value.min;
@@ -507,12 +438,10 @@ function validaManifest(valore) {
507
438
  errori.push(`roles[${indice}].max: must be greater than or equal to min.`);
508
439
  valido = false;
509
440
  }
510
- const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);
511
441
  if (valido) roles.push({
512
442
  id: idRuolo,
513
443
  min,
514
- ...max === void 0 ? {} : { max },
515
- ...label === void 0 ? {} : { label }
444
+ ...max === void 0 ? {} : { max }
516
445
  });
517
446
  }
518
447
  }
@@ -551,7 +480,9 @@ function validaManifest(valore) {
551
480
  continue;
552
481
  }
553
482
  for (const campo of Object.keys(value)) {
554
- if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
483
+ if (campo === "label" || campo === "instructions" || campo === "execution") {
484
+ if (pubblicazione) errori.push(`modes[${indice}].${campo}: ${MOTIVO_RIMOSSO}`);
485
+ } else if (!["id", "players", "lobby", "matchmaking"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
555
486
  }
556
487
  if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
557
488
  errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
@@ -563,15 +494,6 @@ function validaManifest(valore) {
563
494
  }
564
495
  ids.add(value.id);
565
496
  const modo = { id: value.id };
566
- for (const [key2, max] of [["label", 48], ["instructions", 160]]) {
567
- const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);
568
- if (text !== void 0) modo[key2] = text;
569
- }
570
- if (value.execution !== void 0) {
571
- if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);
572
- else modo.execution = value.execution;
573
- }
574
- if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);
575
497
  if (value.players !== void 0) {
576
498
  const campo = `modes[${indice}].players`;
577
499
  const range = oggetto(value.players);
@@ -592,11 +514,8 @@ function validaManifest(valore) {
592
514
  if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);
593
515
  else modo.lobby = value.lobby;
594
516
  }
595
- if (modo.execution === "local") {
596
- const range = modo.players ?? players;
597
- if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);
598
- if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);
599
- if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);
517
+ if (pubblicazione && (modo.players ?? players).max === 1 && value.matchmaking !== void 0) {
518
+ errori.push(`modes[${indice}].matchmaking: ${MODE_LOCAL_MESSAGE}`);
600
519
  }
601
520
  if (value.matchmaking === void 0) {
602
521
  modes.push(modo);
@@ -652,11 +571,9 @@ function validaManifest(valore) {
652
571
  }
653
572
  }
654
573
  }
655
- if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");
656
574
  if (errori.length > 0) return { ok: false, errori };
657
575
  return { ok: true, manifest: {
658
576
  manifest: 1,
659
- overlay,
660
577
  id,
661
578
  name,
662
579
  description,
@@ -676,9 +593,6 @@ function validaManifest(valore) {
676
593
  players,
677
594
  lobby,
678
595
  persistent,
679
- replays,
680
- spectators,
681
- boards,
682
596
  roles,
683
597
  teams,
684
598
  voice,
@@ -908,14 +822,8 @@ function validaServerJs(sorgente) {
908
822
  return errori.length === 0 ? { ok: true } : { ok: false, errori };
909
823
  }
910
824
 
911
- // ../contracts/src/replay.ts
912
- var REPLAY_MAX_BYTES = 10 * 1024 * 1024;
913
- var REPLAY_MAX_DURATION_MS = 30 * 60 * 1e3;
914
- var REPLAY_CHUNK_BYTES = 512 * 1024;
915
- var REPLAY_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
916
-
917
- // ../contracts/src/overlay.ts
918
- function validBoardDay(value) {
825
+ // ../contracts/src/giornata.ts
826
+ function validDay(value) {
919
827
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
920
828
  const at = Date.parse(`${value}T00:00:00Z`);
921
829
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
@@ -924,6 +832,16 @@ function validBoardDay(value) {
924
832
  // ../contracts/src/room-limits.ts
925
833
  var MASSIMO_BYTE_FRAME_STANZA = 64 * 1024;
926
834
 
835
+ // ../contracts/src/network-budget.ts
836
+ var NETWORK_BUDGET = Object.freeze({
837
+ recipientBytesPerSecond: 1e5,
838
+ roomBytesPerSecond: 2e6,
839
+ warningRatio: 0.8,
840
+ windowMs: 5e3,
841
+ blockingWindows: 3
842
+ });
843
+ var NETWORK_GUIDANCE = `Multiplayer budget: ${NETWORK_BUDGET.recipientBytesPerSecond / 1e3} kB/s per recipient, ${NETWORK_BUDGET.roomBytesPerSecond / 1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${NETWORK_BUDGET.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.`;
844
+
927
845
  // ../contracts/src/player.ts
928
846
  var GUEST_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
929
847
  function guestName(id) {
@@ -1009,6 +927,31 @@ var MASSIMO_FILE = 3e3;
1009
927
  var MASSIMO_BYTE_TOTALI = 5e8;
1010
928
  var MASSIMO_BYTE_FILE = 1e8;
1011
929
 
930
+ // src/agent-instructions.ts
931
+ function updateAgentInstructions(agents, site) {
932
+ const block = `<!-- caisual:begin -->
933
+ ${NETWORK_GUIDANCE}
934
+ ${SINGLE_PLAYER_RULE}
935
+ The game fills the window and draws everything: menu, lobby, invites, results, "play again". The platform draws nothing over it.
936
+ The kit gives functions only: player identity and language, cloud saves, the daily seed, rooms (create, join with a code, invite link, ready, rematch), matchmaking, friends and party, roles and teams, voice, and the server side of a room.
937
+ Read \`.claude/skills/caisual/SKILL.md\` before creating or publishing a Caisual game.
938
+ Use the current guides at ${site}/publish.md and ${site}/kit.md; the index of every guide is at ${site}/llms.txt.
939
+ <!-- caisual:end -->`;
940
+ if (agents.includes("<!-- caisual:begin -->") && agents.includes("<!-- caisual:end -->")) {
941
+ return agents.replace(/<!-- caisual:begin -->[\s\S]*?<!-- caisual:end -->/, block);
942
+ }
943
+ if (/^## Caisual[ \t]*\r?$/m.test(agents)) return agents.replace(/^## Caisual[ \t]*\r?$/m, `## Caisual
944
+ ${block}
945
+ `);
946
+ return `${agents}${agents === "" ? "" : "\n\n"}## Caisual
947
+ ${block}
948
+ `;
949
+ }
950
+
951
+ // src/i18n.ts
952
+ import { promises as fs2 } from "node:fs";
953
+ import { join as join2, sep as sep2 } from "node:path";
954
+
1012
955
  // src/bundle.ts
1013
956
  import { promises as fs } from "node:fs";
1014
957
  import { createHash } from "node:crypto";
@@ -1179,7 +1122,7 @@ async function checkGameTexts(clientRoot, manifest, warn = defaultWarn) {
1179
1122
  if (!entries.some((entry) => entry.isFile() && entry.name === `${defaultLanguage}.json`)) {
1180
1123
  throw new CliError(2, `client/i18n/${defaultLanguage}.json: the default language file is required when client/i18n exists.`);
1181
1124
  }
1182
- const dictionaries2 = /* @__PURE__ */ new Map();
1125
+ const dictionaries = /* @__PURE__ */ new Map();
1183
1126
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
1184
1127
  if (entry.name.startsWith(".")) continue;
1185
1128
  const language = entry.name.slice(0, -5);
@@ -1193,18 +1136,18 @@ async function checkGameTexts(clientRoot, manifest, warn = defaultWarn) {
1193
1136
  warn(`client/i18n/${entry.name}: expected a flat object with string values; this dictionary will be ignored.`);
1194
1137
  continue;
1195
1138
  }
1196
- dictionaries2.set(language, value);
1139
+ dictionaries.set(language, value);
1197
1140
  } catch {
1198
1141
  warn(`client/i18n/${entry.name}: invalid or unreadable JSON; this dictionary will be ignored.`);
1199
1142
  }
1200
1143
  }
1201
- const keys = new Set([...dictionaries2.values()].flatMap((dictionary) => Object.keys(dictionary)));
1202
- for (const [language, dictionary] of dictionaries2) {
1144
+ const keys = new Set([...dictionaries.values()].flatMap((dictionary) => Object.keys(dictionary)));
1145
+ for (const [language, dictionary] of dictionaries) {
1203
1146
  const missing = [...keys].filter((key) => !Object.hasOwn(dictionary, key)).sort();
1204
1147
  if (missing.length) warn(`client/i18n/${language}.json: missing keys: ${missing.join(", ")}.`);
1205
1148
  }
1206
1149
  for (const language of manifestLanguages(manifest)) {
1207
- if (!dictionaries2.has(language)) warn(`client/i18n/${language}.json: no usable dictionary for a declared language; the fallback will be used.`);
1150
+ if (!dictionaries.has(language)) warn(`client/i18n/${language}.json: no usable dictionary for a declared language; the fallback will be used.`);
1208
1151
  }
1209
1152
  }
1210
1153
 
@@ -1215,10 +1158,10 @@ import { tmpdir } from "node:os";
1215
1158
  import { basename as basename2, dirname as dirname3, extname as extname2, join as join4, resolve as resolve3 } from "node:path";
1216
1159
 
1217
1160
  // ../../docs/publish.md
1218
- var publish_default = '# Publish a game on Caisual\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version. It becomes current unless another version was activated after the upload opened.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\nA game published with `"overlay": { "version": 1 }` is a standard game: it runs full screen and Caisual draws the menu, the lobby, invitations, friends, matchmaking, spectators, voice, the end of a match and Play again on top of it. Write the field, the HUD and the settings; declare the rest in the manifest. See [Sessions and the standard overlay](./kit.md#sessions-and-the-standard-overlay).\n\n## Game folder\n\nUse this structure:\n\n```text\nmy-game/\n caisual.json\n server.js # optional, required only for multiplayer rooms\n client/\n index.html\n i18n/\n en.json\n it.json\n ...\n```\n\n`caisual.json` and `client/index.html` are required. Put every file used by the game under `client/`.\n\nRun `npx @caisual/cli init my-game` to create a minimal single-player folder with the standard overlay and one local mode. Run `npx @caisual/cli init --multiplayer my-game` to add a room mode with matchmaking and a `server.js`. Both templates include `client/i18n/en.json` used by the example client through `const t = await c.text()`. They are full screen and use `c.session` and `c.overlay`; neither draws a menu or a lobby of its own.\n\nThe whole CLI is:\n\n```text\ncaisual init [--multiplayer | --arcade] [folder]\ncaisual dev [folder] [--port 8790] [--day YYYY-MM-DD] [--latency ms [--jitter ms] [--loss percent]]\ncaisual check [folder] [--json]\ncaisual publish [folder]\ncaisual versions [folder|id]\ncaisual rollback [folder|id] --to <n>\ncaisual unlist [folder|id]\ncaisual relist [folder|id]\ncaisual delete [folder|id] --yes\ncaisual skill\ncaisual --help\ncaisual --version\n```\n\n`caisual init --arcade my-arena` creates a complete online action starter in English and Italian. It includes a shared fixed-step simulation, an authoritative `server.js`, numbered and acknowledged controls, local prediction with reconciliation, remote interpolation, safe HUD placement, standings and fast rematches. All `init` variants also generate `package.json` with `dev`, `test` and optional `test:browser` scripts. See [Responsive action games](./kit.md#responsive-action-games) and [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n`caisual check [folder] [--json]` runs every local check used by publish: the manifest, game texts, client files, the `server.js` bundle, the three required images, and screenshots. It needs no key and uploads nothing. It validates files without launching or playing the game in a browser. With `--json` it prints a report for tools and agents. It exits with code 2 when the report has errors.\n\n`caisual skill` writes this guide, [kit.md](./kit.md) and the index of the guides at [/docs](/docs) into `.claude/skills/caisual/SKILL.md` in the current folder and adds a `## Caisual` section to `AGENTS.md`, so an agent working in that repository reads the rules before it starts. `caisual init` does the same in the new game folder, so a fresh game already carries the skill.\n\n## caisual.json\n\nThe file must contain one JSON object. Unknown fields are rejected. This is a complete single-player example:\n\n```json\n{\n "manifest": 1,\n "id": "my-game",\n "name": "My Game",\n "description": { "en": "A short description of the game." },\n "cover": "cover.png",\n "card": "card.png",\n "icon": "icon.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "languages": ["en", "it"],\n "platform": "both",\n "overlay": { "version": 1, "accent": "#397e83" },\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "requires": { "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" },\n "players": { "min": 1, "max": 1 },\n "lobby": false,\n "persistent": false,\n "spectators": true,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": [\n { "id": "solo", "execution": "local", "label": "Solo", "instructions": "One run against the clock." }\n ]\n}\n```\n\n- `manifest` is required and must be `1`.\n- `overlay` is optional and defaults to absent. Set `{ "version": 1 }` to publish a standard game and get the whole overlay. `accent` is optional and must be a six-digit `#RRGGBB` colour; no other CSS is accepted. A game without `overlay` keeps its historical flow and draws its own menus, and nothing in this guide changes for it.\n- `id` is required. Use 3 to 32 lowercase ASCII letters or digits, with single hyphens only between groups. The ID becomes the URL slug. Choose it carefully because it cannot be renamed or reused after deletion.\n- `name` is required and must contain 1 to 60 characters.\n- `description` is optional and defaults to an empty string. It accepts a plain string or a localized object such as `{ "en": "A short description.", "it": "Una breve descrizione." }`; each translation must contain 1-500 characters on one line, with a BCP 47 key listed in `languages`. A plain empty string means no description.\n- `cover`, `card` and `icon` are required, distinct relative file paths inside `client/`. Use PNG, JPEG or WebP, at most 2 MB (2,000,000 bytes) per image. Do not include a query, fragment, empty segment or parent segment. See the exact dimensions below.\n- `screenshots` is optional and defaults to `[]`. It accepts up to 8 relative paths inside `client/`.\n- `tags` is optional and defaults to `[]`. It accepts up to 10 values. Each value uses 1 to 24 lowercase letters, digits, or hyphens.\n- `languages` is required: a non-empty array of distinct BCP 47 tags that includes `en`, such as `["it", "en", "pt-BR"]`. English is always required alongside the game\'s own languages. The first entry remains the default and may be a language other than English. Tags are normalized to canonical casing. The catalog and standard menu show the available languages.\n- `platform` is required. Use `desktop` when the game needs a keyboard, mouse, large display, or desktop performance. Use `mobile` when it is designed only for touch and small screens. Use `both` only after checking that layout, performance, and controls work on both.\n- `orientation` is optional and defaults to `landscape`. Use `landscape` or `portrait` to describe the intended mobile layout. The device may not honor an orientation request.\n- `input` is optional and defaults to `[]`. Include every supported input from `keyboard`, `mouse`, `touch`, and `gamepad`. Do not claim an input until the game is usable with it.\n- `visibility` is optional and defaults to `public`. Use `public` for catalog eligibility or `unlisted` for access by direct link only.\n- `network` is optional and defaults to `[]`. List every external host contacted or loaded by the game, without scheme, port, path, query, or fragment, for example `api.example.com`. If an external host is missing, the browser blocks the request. Keep the array empty when the game uses only its own files and Caisual services.\n- `requires` is optional and defaults to `{ "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" }`. Declare the minimum capabilities the game truly needs to run. For example, a game with a WebGPU renderer and a WebGL2 fallback declares only `webgl2`. Shared memory and threaded WebAssembly are unavailable inside the portal page; use a build without threads. `memoryMb` accepts `null` or a multiple of 256 from 512 to 32768. Use `light`, `medium`, or `heavy` for the expected performance load.\n- `players` is optional and defaults to `{ "min": 1, "max": 1 }`. Both values are integers from 1 to 24 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is optional and defaults to `false`. Use `true` when players must choose roles or teams, mark themselves ready, and wait for the host to start. With `false`, play starts when the first player enters and later players may join in progress. A room mode with resolved `players.max === 1` always starts on entry and bypasses the lobby, including an inherited `lobby: true`.\n- `persistent` is optional and defaults to `false`. Use `true` when room members must be able to return with the same code after disconnecting, including while the game is already playing. Persistent rooms expire after 30 days without activity.\n- `spectators` is optional and defaults to `{ "delayMs": 3000 }`. Use `false` to disable watching, `true` for the default three-second delay, or `{ "delayMs": N }` to choose an integer delay from 0 to 30000 milliseconds.\n- `roles` is optional and defaults to `[]`. Each entry has an `id` of 1 to 32 lowercase letters, digits, or internal hyphens, a `min` integer from 0 to 24, and an optional `max` in the same range. Rooms enforce these capacities in the lobby. `label` is optional text or a language-to-text object, 1 to 32 characters on one line per translation, and names the role in the overlay lobby; without it the overlay shows the id.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 24, with `max` at least `min`. Rooms balance players who do not choose a team.\n- `voice` is optional and defaults to `none`. Use `room` so everyone in the room can hear each other, `team` to restrict voice to teammates, or `proximity` when `server.js` sets the gain between player pairs. Use `none` to disable voice.\n- `modes` is optional and defaults to `[]`. A mode has a unique `id` using 1 to 32 lowercase letters, digits, or internal hyphens. It may have `matchmaking` with `key`, an array of 1 to 8 unique field names, and `timeoutMs`, an integer from 1,000 to 300,000. Each field name uses 1 to 32 lowercase letters, digits, or hyphens and starts with a letter or digit. A mode may also define `players: { min, max }` (both integers from 1 to 24, max at least min) and `lobby` (boolean). Each supplied field replaces its root counterpart for creation, joining and matchmaking, including filling an open room; omitted fields inherit the root value. `players` is replaced as a whole, not merged. `mode: null` uses the root configuration. Roles, teams, voice and persistence remain game-wide. Catalog labels consider the resolved modes, or the root range when there are no modes: Single player, Multiplayer, or Solo + Multiplayer.\n- A standard game declares at least one mode, and every mode of a standard game needs `execution`: `local` for a run inside the browser, `room` for a room. A `local` mode resolves to exactly one player with `lobby` false and no matchmaking; it is not a room of one, and the create and match APIs refuse it. A `room` mode requires `server.js`, checked by the CLI and again when the version is published.\n- `label` is optional text or a language-to-text object, 1 to 48 characters on one line per translation, and names the mode in the standard menu; without it the menu shows the id. `instructions` is optional text or a language-to-text object, 1 to 160 characters on one line per translation, and adds a line under the label. Both are text, never HTML, and resolve to the player\'s language with the fallback described below.\n- `matchmaking.defaults` is required when the overlay is expected to start a search on its own. It holds exactly the fields listed in `key`, with safe integers or strings of 1 to 64 characters from letters, digits, `_ . : -`. Without it a search must come from the game\'s own `c.room.match()` call.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\n`requires` is also available to the game itself through `c.device` in the kit, so the game can show its own warning or pick a lighter renderer. The portal does not gate the Play link on it.\n\n## Game translations\n\nUse this convention for every new game, including games with only one language:\n\n1. Put the supported languages in `languages`, always including `en`, with the default first.\n2. Put game UI strings in `client/i18n/<lang>.json`, with canonical filenames such as `en.json`, `it.json` and `pt-BR.json`. Dictionaries are flat objects with identical keys and string values, including placeholders such as `{n}`.\n3. Call `const t = await c.text()` after `caisual.connect()` and before `c.session.ready()`. Render with `t(\'score\', { n: 3 })`. Use `c.player.language` when formatting dates or numbers.\n4. Translate the description, mode labels and instructions in the manifest. Role labels support the same objects. `name` and `tags` are not localized fields.\n\nFor example, a mode can contain:\n\n```json\n{\n "id": "solo",\n "execution": "local",\n "label": { "en": "Solo", "it": "Da solo" },\n "instructions": { "en": "Light up three lights.", "it": "Accendi tre luci." }\n}\n```\n\nA dictionary at `client/i18n/en.json` can contain:\n\n```json\n{ "score": "Lights: {n} / 3", "done": "Complete" }\n```\n\nSee [Game language and strings](./kit.md#game-language-and-strings) for a complete manifest, two dictionaries and a working client.\n\nThe kit makes one request to the game\'s own origin. The kit first resolves the player\'s ordered preferences against declared game languages, using exact tags, parent tags, then the game\'s default. `c.player.language` is that declared game language; `c.player.uiLanguage` is the overlay\'s locale. Caisual resolves each text key from the selected game language, its parent language tags, then the manifest\'s default language, then the key itself. For `pt-BR` with English as default, that is `pt-BR`, `pt`, `en`, key. The same chain selects localized manifest text from `uiLanguage` in the overlay and descriptions from the page language in the catalogue, game page, creator profiles and invitations, including description metadata; a missing label falls back to its id and missing instructions are omitted. A string continues to appear as written. Translation objects must be non-empty, contain valid language tags and satisfy the original text limits for every value. Empty strings are allowed in game dictionaries, but not in manifest translation objects. Description translations must use languages declared in `languages`; a missing description is omitted.\n\n`caisual dev` at startup and `caisual publish` before any upload check `client/i18n/`. No folder is required for an existing game. If the folder exists, the default language file must exist as a regular file or the command fails. All other dictionary issues produce warnings: invalid JSON, non-string values, non-canonical filenames, missing dictionaries for declared languages, and differing keys. Missing-key warnings compare the union of keys across every usable file, including keys absent from the default. Invalid dictionaries are ignored at runtime. Fix the warnings before sharing the game; they do not block development or publication. Restart dev after changing the manifest to reload its language list and repeat the checks.\n\nDeclare `languages: ["it", "en"]` to keep Italian as the default. Add English game strings and translate the manifest labels and instructions too. Declaring English does not create translations. A manifest without `languages`, or without `en`, is rejected.\n\n## client/index.html\n\n`index.html` must be at the root of `client/`. Use relative URLs such as `./game.js` or `assets/sprite.png`. Do not use root-relative URLs such as `/game.js`, and do not use parent paths that leave the published `client/` tree.\n\nTo use player identity, saves, import the kit from `/__caisual/kit/v1.js` as shown in [kit.md](./kit.md). The path `/__caisual/` is reserved: do not put game files under it.\n\nA standard game fills the window: `html`, `body` and the game surface are 100% of the viewport, with no maximum width, no header, no footer and no editorial frame, and the document must not scroll at 1366x768 or at 390x844 with safe areas applied. Aim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile; a board with a fixed aspect ratio uses the geometric exception described in [kit.md](./kit.md#full-screen).\n\nCaisual draws its own controls on top: a pill in the top-right corner, about 44 pixels tall and wider when it carries an invitation, and a compact bar at the end of a match. Exit lives in that pill. The exact positions arrive in the game as `reservedRects` on `c.overlay.onChange`, in CSS pixels of the game viewport, so place the game\'s own HUD outside them rather than guessing a corner. While a panel is open `inputBlocked` is `true`: release held keys and stop reading input, but keep simulating, because a panel never pauses a room.\n\nA game published without `overlay` keeps the historical control instead: a small round Exit button over the top-right corner, 36 pixels, inside the safe area. Keep that corner free of controls.\n\nDo not register a service worker. The game runs in an iframe on its own origin inside `caisual.com`. Test it without assuming access to the parent page, parent cookies, or files outside `client/`.\n\nWhen `voice` is not `none`, the portal grants microphone access to the game iframe. The browser still asks the player for permission when the game calls `room.voice.join()`. Call it from a button click or another user gesture, not automatically when the page loads.\n\n## Multiplayer server\n\nAdd `server.js` beside `caisual.json` when the game uses rooms. It is the ESM entry point and must have an `export default`. It may import local files such as `./logic/ships.js`, including `.js`, `.ts`, and `.json` files, and npm packages installed in the game folder. The CLI bundles these imports into one file both when publishing and when starting `caisual dev`. Relative default imports of `.wasm` stay external and their files are copied separately.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n tickRate: 0,\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\n`tickRate` is required and must be an integer from 0 to 60; `defineGame` throws without it. Use `0` for a server that runs only in response to events. Every callback is optional.\n\nThe file may define the optional room callbacks documented in [kit.md](./kit.md). Server code runs without Node.js APIs or network access. Dynamic `import()`, `require()`, and CommonJS exports are not supported. Use only pure JavaScript packages, such as a noise or vector library. A package that needs an HTTP client is not suitable. The `network` field in `caisual.json` controls only requests made by the browser client.\n\nThe final bundle may only import `@caisual/kit/server` and default-import `.wasm` files, for example `import engine from \'./physics/add.wasm\'`. Paths stay inside the game folder without `..` segments. The value is an already compiled `WebAssembly.Module`; use `new WebAssembly.Instance(engine, imports)` in `onCreate` or on first use. No shared memory or threads. At most 8 files are allowed, 8,000,000 bytes per file and 16,000,000 bytes total. No manifest field is added: `requires.wasm` still describes the browser client. Use this only for existing engines. Budget for compilation on room wake, because a larger binary delays resumption; recreate instances lazily and restore their state after a wake. See [WebAssembly on the server](./kit.md#webassembly-on-the-server).\n\nThe bundled `server.js` may be at most 4,000,000 bytes. Room state must remain plain JSON and may be at most 512 KB when serialized. Game messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`. Room save values may be at most 256 KB.\n\nPublish a multiplayer game with the same `npx @caisual/cli publish` command. When imports need bundling, the CLI prints `Bundling server.js (N KB).` The uploaded file is the bundle: the CLI validates it, declares its size and SHA-256 digest, and uploads it separately from browser files. Each imported binary is declared in the optional `server.wasm` array as `{ path, bytes, sha256 }`, uploaded to its `serverWasmUploads` URL with Content-Length, and verified with SHA-256. The files stay in the private server archive and follow the version retention rules. The portal validates the stored bundle, the imported file list and the binaries again before making the new game version current.\n\nIf the portal finds an invalid `server.js`, the command prints `The multiplayer server could not be published.` followed by diagnostic hints. The failed version is kept for diagnosis but never becomes current. If the game already has a working version, players continue to receive that version. Fix the reported problem and publish again to create a new version.\n\n## Test locally\n\nRun the local preview from the game folder before publishing:\n\n```sh\nnpx @caisual/cli dev\n```\n\nYou can pass a game folder and choose another port:\n\n```sh\nnpx @caisual/cli dev ./my-game --port 8790 --day 2026-09-04\n```\n\nThe optional `--day YYYY-MM-DD` flag pins the UTC date for daily seeds. Invalid dates are usage errors; omitting the flag uses today in UTC. Saves, identities and rooms stay shared. Room daily contexts stay fixed at creation, including on restoration; new rooms follow the simulated day. Daily `expiresAt` stays on the next real UTC midnight, so it can be compared with the unchanged server clock. Reload the game after restarting dev. Real clocks and timers are unchanged.\n\nThe command prints a portal URL and a game URL. Open the portal URL. It loads the game in an iframe with the same handshake used after publishing, so `c.connected` is `true`, and it mounts the same standard overlay when the manifest declares one. Player identity, saves, daily data, invitations, and rooms all use local data. Add `?lang=` with any game language to test the manifest resolution, including regional tags such as `pt-BR`. For `?lang=ja` with Japanese declared, `c.player.language` is `ja` and `c.player.uiLanguage` is `en`: the overlay supports en, it, es, fr, de and pt. Without the parameter, the game uses the browser\'s ordered preferences. Friends and parties are marked unavailable locally. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nOpen `/__caisual/players?n=4` on the printed portal URL for independent guest frames with the full overlay. Each has Drop and Spectate controls. Use `dev --latency 120 --jitter 40 --loss 2` to delay room WebSocket messages in each direction, vary the delay and discard 2% of messages for recovery testing. Latency and jitter accept integer milliseconds from 0 to 60000, loss accepts 0 to 100 percent; jitter and loss require latency. HTTP, matchmaking and audio are unaffected. See [Local dev](/docs/local-development) for precise semantics and frame sizes.\n\nReload after client edits; restart dev after editing `caisual.json`, `server.js`, or server imports, including shared physics. Rooms restore from `.caisual-dev/`, so incompatible state changes may need a new room. There is no automatic reload. If a port is busy, dev suggests a command using a currently available port.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Without `server.js`, the game remains single player and attempts to create a room return `no_server`.\n\nPress Ctrl+C in the terminal to stop the preview. No account or publish key is required.\n\n## Limits\n\n- At most 3,000 files per version.\n- At most 100,000,000 bytes per file.\n- At most 500,000,000 bytes for all files in one version.\n- At most 4,000,000 bytes for `server.js`.\n- At most 60 versions per publishing key in any 24-hour window. Beyond that the portal answers `publish_rate_limit`.\n- Dotfiles, dot-directories, and directories named `node_modules` are ignored.\n- Symbolic links and other non-regular files are rejected.\n\nReduce or split files that exceed the per-file limit. Remove generated files that the browser does not need.\n\n## Publish\n\nUse the key supplied by the creator. Set it in the environment so it does not enter shell history as a command-line flag:\n\n```sh\nnpx @caisual/cli check\nexport CAISUAL_KEY=\'ck_...\'\nnpx @caisual/cli publish\n```\n\nRun the command from the game folder, or pass the folder path after `publish`. For local portal development only, set `CAISUAL_ORIGIN` to the local HTTP origin.\n\nThe CLI validates the folder, computes every file size and SHA-256 digest, creates a new version, uploads the files, completes the version, and prints the game URL. The stable URL is `https://caisual.com/g/<id>`.\n\nBefore contacting the portal, the CLI scans browser files for common WebGL2, WebGPU, WebAssembly, and shared-memory signatures. A possible mismatch is printed to stderr with a `Warning:` prefix and never blocks publishing. Correct an accurate warning by declaring the minimum matching `requires` field, and use a build without threads if shared memory is detected. If the signature belongs to unused code, remove that code from the published client bundle.\n\nThe first games from a new creator are reviewed before they can appear in the public catalog. Their stable links still work while review is pending.\n\n## Versions and rollback\n\nNew games start on the current version. An existing room stays on its own version for its entire life, including players arriving later through an invitation, a typed code, friends, spectators or Resume. Its client, manifest, overlay, iframe permissions and images all come from that version.\n\nEvery `publish` creates a new immutable version, even for a tiny correction. The permanent address stays `/g/<id>`. The home page sorts games by the creation date of the current version; publishing can move a game up and a rollback can move it down.\n\n## Updates while a page is open\n\nCreating a room or starting a matchmaking search from an outdated page fails with `version_outdated` and `currentVersion`. The standard overlay shows **This game was updated** and a **Reload game** button that reloads the portal page on the current version.\n\nJoining or watching an existing room from another version fails with `version_mismatch` and `roomVersion`. For a typed code or Resume, the standard overlay reloads the portal with the invitation so it can load the room\'s version. Spectators keep their watch intent. A room whose version is no longer ready, or whose game was deleted, shows **This room is no longer available**, with a link to the current game.\n\nMatchmaking keeps versions separate. A reservation already accepted before an update can finish on its original version. Existing rooms are not restarted by an update or rollback.\n\nGames with their own menus receive these errors both as rejected room operations and through `c.room.onError(listener)`. Call `c.room.reload()` after either error to load the current game or the room referenced by the failed join or watch:\n\n```js\nc.room.onError((error) => {\n if (error.code === \'version_outdated\' || error.code === \'version_mismatch\') {\n showReloadButton(() => c.room.reload());\n }\n});\n```\n\n## List and restore versions\n\nUse the same `CAISUAL_KEY` environment variable as for publishing:\n\n```sh\ncaisual versions\ncaisual versions ./my-game\ncaisual rollback --to 7\ncaisual rollback my-game --to 7\n```\n\nThe target defaults to the current folder, or accepts a folder or game ID. `versions` lists the number, date, state and size and marks the current version. The account page also marks it.\n\nRollback selects an existing ready version of that game. It copies no files, creates no new number and does not consume the 60-version daily allowance. Visibility and moderation stay unchanged. **Rollback restores code, not saved data.**\n\nIf another version was activated while a publish was uploading, the upload becomes ready but does not replace it. The CLI reports:\n\n```text\nVersion N is ready but not current: version M was activated in the meantime. Run caisual rollback --to N to activate it.\n```\n\nA manifest\'s visibility takes effect only when activation succeeds. An `unlist` or `relist` issued during an upload wins over that upload\'s manifest visibility.\n\n## Game versions and data formats\n\nSaves and `room.shared` belong to the game, not to a game version. The creator is responsible for data compatibility. A game version and a data format version are separate things.\n\nFor a compatible change, keep the same keys. For an incompatible change, use a new key such as `progress_v2`. Import from `progress` only when `progress_v2` is missing. Keep the original, identify the format inside each value and never overwrite a format you do not recognize. Use the same convention for `room.shared`. Progress written later by an old version is not automatically merged into the new key.\n\nThe daily seed does not depend on the game version. Do not change the generator or rules halfway through a UTC day without changing the board ID.\n\n## Retention and local development\n\nGood versions stay. Old ready versions are retained for rooms and rollback, without automatic age-based deletion. Failed uploads are cleaned from both client and server storage; uploads left open for more than 24 hours fail with a note and are cleaned. Version numbers are never reused. Deleting a game removes its client and server files.\n\n`caisual dev` always uses game version 1. It does not simulate publishing, version changes or rollback.\n\n## Update, unlist, or delete\n\nTo update a game, change its files without changing `id`, then run `npx @caisual/cli publish` again. This creates a new version and keeps the same stable game URL.\n\nTo remove the current game from the catalog without publishing a new version, run:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli unlist\n```\n\nRestore its public visibility with:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli relist\n```\n\nDelete it permanently only when you are certain:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli delete --yes\n```\n\nEach command reads the `id` from `caisual.json` in the current folder. You may instead pass a game folder or an ID directly, for example `npx @caisual/cli unlist ./my-game` or `npx @caisual/cli relist my-game`. The publishing key always comes from `CAISUAL_KEY`, never from a flag. Deletion has no interactive prompt, is permanent, removes the stored game files, and never frees the ID for reuse.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing or managing a game.\n- `The publish API key is not valid`: create a new key in the account dashboard if the old key expired or was revoked.\n- `game_not_found`: check that the game ID is correct and belongs to the creator represented by `CAISUAL_KEY`; deleted games return the same error.\n- `caisual.json is not valid`: read every reported field and rule, fix all of them, then retry.\n- `client/index.html: file not found`: place `index.html` directly under `client/`, not in a nested build folder.\n- `referenced file not found`: make sure `cover`, `card`, `icon` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 100 MB`: compress, reduce, or split the asset and update its references.\n- `upload failed` or a temporary portal error: keep the files unchanged and retry the same publish command. The CLI retries temporary upload failures automatically.\n- `publish_rate_limit`: this key has already created 60 versions in the last 24 hours. Wait until the oldest one leaves the window.\n- `burst_rate_limit`: too many publishing or management requests arrived at once. Wait briefly and retry.\n- `The multiplayer server could not be published`: read every diagnostic hint, fix `server.js`, and publish again. The failed version does not replace the current one.\n- An external browser request works locally but fails after publishing: add its host to `network` and publish a new version. Server code cannot make outbound network requests.\n- A threaded WebAssembly game fails to start: use a build without threads. Games embedded in the portal cannot use shared memory.\n\n## Required game images\n\nThe look of the game belongs to its creator: templates are deliberately neutral, and their placeholder images must be replaced.\n\nEvery manifest must declare three different files inside `client/`. All three are required PNG, JPEG or WebP images, at most 2 MB (2,000,000 bytes) each:\n\n| Field | Exact size | Use |\n| --- | --- | --- |\n| `cover` | 1536x1024, 3:2 | Featured home card, game page and overlay boot background, social preview, mobile invitation |\n| `card` | 1024x1024, 1:1 | Secondary home cards and square invitation artwork |\n| `icon` | 1024x1024, 1:1 | Game window favicon, overlay, friends and parties |\n\n**No text inside any image:** no title, slogan, letters or numbers. The portal displays the game name. Keep the icon simple enough to read at a small size. The files must be different, including `card` and `icon`. Screenshots keep their existing rules.\n\nThe 3:2 and 1:1 ratios match native formats of widely used image generators. Export at the exact sizes above: Caisual does not crop, stretch or accept a size range. `caisual check` and publish validate the format from the file headers, exact dimensions and weight. The portal repeats these checks for direct publication. The absence of text is an editorial requirement, not an automatic check.\n\nAll three `caisual init` variants include small, real PNG examples at these sizes. Replace them with artwork for your game before sharing it. English (`en`) is always required in `languages`; the first language remains the default, for example `["it", "en"]`.\n';
1161
+ var publish_default = '# Publish a game on Caisual\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version\'s worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version. It becomes current unless another version was activated after the upload opened.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\nCaisual draws nothing over the game: the game fills the window and draws its own menu, lobby, invitation, results and "play again" with the kit\'s functions. `caisual init` writes a working minimal menu in `client/menu.js` to copy or replace. See [The game draws everything](./kit.md#the-game-draws-everything).\n\n## Game folder\n\nUse this structure:\n\n```text\nmy-game/\n caisual.json\n server.js # optional, required only for multiplayer rooms\n client/\n index.html\n i18n/\n en.json\n it.json\n ...\n```\n\n`caisual.json` and `client/index.html` are required. Put every file used by the game under `client/`.\n\nRun `npx @caisual/cli init my-game` to create a minimal single-player folder with one local mode. Run `npx @caisual/cli init --multiplayer my-game` to add a room mode with matchmaking and a `server.js`. Both templates include `client/i18n/en.json`, used by the example client through `const t = await c.text()`, and `client/menu.js`, the game\'s own menu: solo or online, create room, copy invite, join with a code, players with ready, start, play again.\n\nThe whole CLI is:\n\n```text\ncaisual init [--multiplayer | --arcade] [folder]\ncaisual dev [folder] [--port 8790] [--day YYYY-MM-DD] [--latency ms [--jitter ms] [--loss percent]]\ncaisual check [folder] [--json]\ncaisual publish [folder]\ncaisual versions [folder|id]\ncaisual rollback [folder|id] --to <n>\ncaisual unlist [folder|id]\ncaisual relist [folder|id]\ncaisual delete [folder|id] --yes\ncaisual skill\ncaisual --help\ncaisual --version\n```\n\n`caisual init --arcade my-arena` creates a complete online action starter in English and Italian. It includes a shared fixed-step simulation, an authoritative `server.js`, numbered and acknowledged controls, local prediction with reconciliation, remote interpolation, its own menu and lobby, standings and fast rematches. All `init` variants also generate `package.json` with `dev`, `test` and optional `test:browser` scripts. See [Responsive action games](./kit.md#responsive-action-games) and [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n`caisual check [folder] [--json]` runs every local check used by publish: the manifest, game texts, client files, the `server.js` bundle, the three required images, and screenshots. It needs no key and uploads nothing. It validates files without launching or playing the game in a browser. With `--json` it prints a report for tools and agents. It exits with code 2 when the report has errors.\n\n`caisual skill` writes this guide, [kit.md](./kit.md) and the index of the guides at [/docs](/docs) into `.claude/skills/caisual/SKILL.md` in the current folder and adds a `## Caisual` section to `AGENTS.md`, so an agent working in that repository reads the rules before it starts. `caisual init` does the same in the new game folder, so a fresh game already carries the skill.\n\n## caisual.json\n\nThe file must contain one JSON object. Unknown fields are rejected. This is a complete single-player example:\n\n```json\n{\n "manifest": 1,\n "id": "my-game",\n "name": "My Game",\n "description": { "en": "Grow huge. Guard your tail. Devour light in a cosmic arena." },\n "cover": "cover.png",\n "card": "card.png",\n "icon": "icon.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "languages": ["en", "it"],\n "platform": "both",\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "requires": { "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" },\n "players": { "min": 1, "max": 1 },\n "lobby": false,\n "persistent": false,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": [\n { "id": "solo" }\n ]\n}\n```\n\n- `manifest` is required and must be `1`.\n- `id` is required. Use 3 to 32 lowercase ASCII letters or digits, with single hyphens only between groups. The ID becomes the URL slug. Choose it carefully because it cannot be renamed or reused after deletion.\n- `name` is required and must contain 1 to 60 characters.\n- `description` is an optional one-line subtitle, shown below the game name on cards. It defaults to an empty string and accepts a plain string or a localized object such as `{ "en": "Grow huge. Guard your tail. Devour light in a cosmic arena.", "it": "Diventa enorme. Proteggi la coda. Divora luce in un\'arena cosmica." }`. For new publications, every value must contain 1-80 characters after trimming whitespace, on one line, with a BCP 47 key listed in `languages`. The limit applies to every language, including translations other than the default. A plain empty string means no subtitle. Previously published versions with longer descriptions remain readable; publishing an update requires the new limit.\n- `cover`, `card` and `icon` are required, distinct relative file paths inside `client/`. Use PNG, JPEG or WebP, at most 2 MB (2,000,000 bytes) per image. Do not include a query, fragment, empty segment or parent segment. See the exact dimensions below.\n- `screenshots` is optional and defaults to `[]`. It accepts up to 8 relative paths inside `client/`.\n- `tags` is optional and defaults to `[]`. It accepts up to 10 values. Each value uses 1 to 24 lowercase letters, digits, or hyphens.\n- `languages` is required: a non-empty array of distinct BCP 47 tags that includes `en`, such as `["it", "en", "pt-BR"]`. English is always required alongside the game\'s own languages. The first entry remains the default and may be a language other than English. Tags are normalized to canonical casing. The catalog and standard menu show the available languages.\n- `platform` is required. Use `desktop` when the game needs a keyboard, mouse, large display, or desktop performance. Use `mobile` when it is designed only for touch and small screens. Use `both` only after checking that layout, performance, and controls work on both.\n- `orientation` is optional and defaults to `landscape`. Use `landscape` or `portrait` to describe the intended mobile layout. The device may not honor an orientation request.\n- `input` is optional and defaults to `[]`. Include every supported input from `keyboard`, `mouse`, `touch`, and `gamepad`. Do not claim an input until the game is usable with it.\n- `visibility` is optional and defaults to `public`. Use `public` for catalog eligibility or `unlisted` for access by direct link only.\n- `network` is optional and defaults to `[]`. List every external host contacted or loaded by the game, without scheme, port, path, query, or fragment, for example `api.example.com`. If an external host is missing, the browser blocks the request. Keep the array empty when the game uses only its own files and Caisual services.\n- `requires` is optional and defaults to `{ "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" }`. Declare the minimum capabilities the game truly needs to run. For example, a game with a WebGPU renderer and a WebGL2 fallback declares only `webgl2`. Shared memory and threaded WebAssembly are unavailable inside the portal page; use a build without threads. `memoryMb` accepts `null` or a multiple of 256 from 512 to 32768. Use `light`, `medium`, or `heavy` for the expected performance load.\n- `players` is optional and defaults to `{ "min": 1, "max": 1 }`. Both values are integers from 1 to 24 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is optional and defaults to `false`. Use `true` when players must choose roles or teams and mark themselves ready before play: the room starts on its own as soon as everyone present is ready and the minimums are met. With `false`, play starts when the first player enters and later players may join in progress. A room mode with resolved `players.max === 1` always starts on entry and bypasses the lobby, including an inherited `lobby: true`.\n- `persistent` is optional and defaults to `false`. Use `true` when room members must be able to return with the same code after disconnecting, including while the game is already playing. Persistent rooms expire after 30 days without activity.\n- `roles` is optional and defaults to `[]`. Each entry has an `id` of 1 to 32 lowercase letters, digits, or internal hyphens, a `min` integer from 0 to 24, and an optional `max` in the same range. Rooms enforce these capacities in the lobby. The name the player reads comes from the game\'s own dictionary, not from the manifest.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 24, with `max` at least `min`. Rooms balance players who do not choose a team.\n- `voice` is optional and defaults to `none`. Use `room` so everyone in the room can hear each other, `team` to restrict voice to teammates, or `proximity` when `server.js` sets the gain between player pairs. Use `none` to disable voice.\n- `modes` is optional and defaults to `[]`. A mode has a unique `id` using 1 to 32 lowercase letters, digits, or internal hyphens. It may have `matchmaking` with `key`, an array of 1 to 8 unique field names, and `timeoutMs`, an integer from 1,000 to 300,000. Each field name uses 1 to 32 lowercase letters, digits, or hyphens and starts with a letter or digit. A mode may also define `players: { min, max }` (both integers from 1 to 24, max at least min) and `lobby` (boolean). Each supplied field replaces its root counterpart for creation, joining and matchmaking, including filling an open room; omitted fields inherit the root value. `players` is replaced as a whole, not merged. `mode: null` uses the root configuration. Roles, teams, voice and persistence remain game-wide. Catalogue labels consider the resolved modes, or the root range when there are no modes: Single player, Multiplayer, or Solo + Multiplayer.\n- Single player runs in the browser and never touches the server; a room exists only for two or more players. A mode with resolved `players.max: 1` is local; room creation, joining and matchmaking reject it with `mode_local`. Modes with `players.max > 1` require `server.js`, checked by the CLI and again when the version is published. A server supplied for an entirely single-player game produces a warning because it is unnecessary. The manifest carries no player-facing text for modes or roles: the game names them in its own dictionaries.\n- `matchmaking.defaults` is optional. It holds exactly the fields listed in `key`, with safe integers or strings of 1 to 64 characters from letters, digits, `_ . : -`, so the game can start a search without composing a key.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\n`requires` is also available to the game itself through `c.device` in the kit, so the game can show its own warning or pick a lighter renderer. The portal does not gate the Play link on it.\n\n## Game translations\n\nUse this convention for every new game, including games with only one language:\n\n1. Put the supported languages in `languages`, always including `en`, with the default first.\n2. Put game UI strings in `client/i18n/<lang>.json`, with canonical filenames such as `en.json`, `it.json` and `pt-BR.json`. Dictionaries are flat objects with identical keys and string values, including placeholders such as `{n}`.\n3. Call `const t = await c.text()` after `caisual.connect()`, during setup. Render with `t(\'score\', { n: 3 })`. Use `c.player.language` when formatting dates or numbers.\n4. Translate `description` in the manifest; it is the only localized manifest field. `name` and `tags` are not localized. Mode and role names are the game\'s own text, so they live in the dictionaries with everything else.\n\nA dictionary at `client/i18n/en.json` can contain:\n\n```json\n{ "score": "Lights: {n} / 3", "done": "Complete" }\n```\n\nSee [Game language and strings](./kit.md#game-language-and-strings) for a complete manifest, two dictionaries and a working client.\n\nThe kit makes one request to the game\'s own origin. The kit first resolves the player\'s ordered preferences against declared game languages, using exact tags, parent tags, then the game\'s default. `c.player.language` is that declared game language. Caisual resolves each text key from the selected game language, its parent language tags, then the manifest\'s default language, then the key itself. For `pt-BR` with English as default, that is `pt-BR`, `pt`, `en`, key. The same chain selects the description from the page language in the catalogue, game page, creator profiles and invitations, including description metadata. A string continues to appear as written. Translation objects must be non-empty, contain valid language tags and satisfy the original text limits for every value. Empty strings are allowed in game dictionaries, but not in manifest translation objects. Description translations must use languages declared in `languages`; a missing description is omitted.\n\n`caisual dev` at startup and `caisual publish` before any upload check `client/i18n/`. No folder is required for an existing game. If the folder exists, the default language file must exist as a regular file or the command fails. All other dictionary issues produce warnings: invalid JSON, non-string values, non-canonical filenames, missing dictionaries for declared languages, and differing keys. Missing-key warnings compare the union of keys across every usable file, including keys absent from the default. Invalid dictionaries are ignored at runtime. Fix the warnings before sharing the game; they do not block development or publication. Restart dev after changing the manifest to reload its language list and repeat the checks.\n\nDeclare `languages: ["it", "en"]` to keep Italian as the default. Add English game strings and translate the description too. Declaring English does not create translations. A manifest without `languages`, or without `en`, is rejected.\n\n## client/index.html\n\n`index.html` must be at the root of `client/`. Use relative URLs such as `./game.js` or `assets/sprite.png`. Do not use root-relative URLs such as `/game.js`, and do not use parent paths that leave the published `client/` tree.\n\nTo use player identity, saves, import the kit from `/__caisual/kit/v1.js` as shown in [kit.md](./kit.md). The path `/__caisual/` is reserved: do not put game files under it.\n\nThe game fills the window: `html`, `body` and the game surface are 100% of the viewport, with no maximum width, no header, no footer and no editorial frame, and the document must not scroll at 1366x768 or at 390x844 with safe areas applied. Aim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile; a board with a fixed aspect ratio uses the geometric exception described in [kit.md](./kit.md#full-screen).\n\nCaisual draws nothing on top, so the whole surface and every corner belong to the game. Use `env(safe-area-inset-*)` for the notch and keep the menu, the HUD and the pause action inside it.\n\nDo not register a service worker. The game runs in an iframe on its own origin inside `caisual.com`. Test it without assuming access to the parent page, parent cookies, or files outside `client/`.\n\nWhen `voice` is not `none`, the portal grants microphone access to the game iframe. The browser still asks the player for permission when the game calls `room.voice.join()`. Call it from a button click or another user gesture, not automatically when the page loads.\n\n## Multiplayer server\n\nAdd `server.js` beside `caisual.json` when the game uses rooms. It is the ESM entry point and must have an `export default`. It may import local files such as `./logic/ships.js`, including `.js`, `.ts`, and `.json` files, and npm packages installed in the game folder. The CLI bundles these imports into one file both when publishing and when starting `caisual dev`. Relative default imports of `.wasm` stay external and their files are copied separately.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n tickRate: 0,\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\n`tickRate` is required and must be an integer from 0 to 60; `defineGame` throws without it. Use `0` for a server that runs only in response to events. Every callback is optional.\n\nThe file may define the optional room callbacks documented in [kit.md](./kit.md). Server code runs without Node.js APIs or network access. Dynamic `import()`, `require()`, and CommonJS exports are not supported. Use only pure JavaScript packages, such as a noise or vector library. A package that needs an HTTP client is not suitable. The `network` field in `caisual.json` controls only requests made by the browser client.\n\nThe final bundle may only import `@caisual/kit/server` and default-import `.wasm` files, for example `import engine from \'./physics/add.wasm\'`. Paths stay inside the game folder without `..` segments. The value is an already compiled `WebAssembly.Module`; use `new WebAssembly.Instance(engine, imports)` in `onCreate` or on first use. No shared memory or threads. At most 8 files are allowed, 8,000,000 bytes per file and 16,000,000 bytes total. No manifest field is added: `requires.wasm` still describes the browser client. Use this only for existing engines. Budget for compilation on room wake, because a larger binary delays resumption; recreate instances lazily and restore their state after a wake. See [WebAssembly on the server](./kit.md#webassembly-on-the-server).\n\nThe bundled `server.js` may be at most 4,000,000 bytes. Room state must remain plain JSON and may be at most 512 KB when serialized. Game messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`. Room save values may be at most 256 KB.\n\nPublish a multiplayer game with the same `npx @caisual/cli publish` command. When imports need bundling, the CLI prints `Bundling server.js (N KB).` The uploaded file is the bundle: the CLI validates it, declares its size and SHA-256 digest, and uploads it separately from browser files. Each imported binary is declared in the optional `server.wasm` array as `{ path, bytes, sha256 }`, uploaded to its `serverWasmUploads` URL with Content-Length, and verified with SHA-256. The files stay in the private server archive and follow the version retention rules. The portal validates the stored bundle, the imported file list and the binaries again before making the new game version current.\n\nIf the portal finds an invalid `server.js`, the command prints `The multiplayer server could not be published.` followed by diagnostic hints. The failed version is kept for diagnosis but never becomes current. If the game already has a working version, players continue to receive that version. Fix the reported problem and publish again to create a new version.\n\n## Test locally\n\nRun the local preview from the game folder before publishing:\n\n```sh\nnpx @caisual/cli dev\n```\n\nYou can pass a game folder and choose another port:\n\n```sh\nnpx @caisual/cli dev ./my-game --port 8790 --day 2026-09-04\n```\n\nThe optional `--day YYYY-MM-DD` flag pins the UTC date for daily seeds. Invalid dates are usage errors; omitting the flag uses today in UTC. Saves, identities and rooms stay shared. Room daily contexts stay fixed at creation, including on restoration; new rooms follow the simulated day. Daily `expiresAt` stays on the next real UTC midnight, so it can be compared with the unchanged server clock. Reload the game after restarting dev. Real clocks and timers are unchanged.\n\nThe command prints a portal URL and a game URL. Open the portal URL. It loads the game in an iframe with the same handshake used after publishing, so `c.connected` is `true`. Player identity, saves, daily data, invitations, and rooms all use local data. Add `?lang=` with any game language to test the manifest resolution, including regional tags such as `pt-BR`: for `?lang=ja` with Japanese declared, `c.player.language` is `ja`. Without the parameter, the game uses the browser\'s ordered preferences. Friends are empty locally. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nOpen `/__caisual/players?n=4` on the printed portal URL for independent guest frames. Each has a Drop control that interrupts that guest\'s room connection. Use `dev --latency 120 --jitter 40 --loss 2` to delay room WebSocket messages in each direction, vary the delay and discard 2% of messages for recovery testing. Latency and jitter accept integer milliseconds from 0 to 60000, loss accepts 0 to 100 percent; jitter and loss require latency. HTTP, matchmaking and audio are unaffected. See [Local dev](/docs/local-development) for precise semantics and frame sizes.\n\nReload after client edits; restart dev after editing `caisual.json`, `server.js`, or server imports, including shared physics. Rooms restore from `.caisual-dev/`, so incompatible state changes may need a new room. There is no automatic reload. If a port is busy, dev suggests a command using a currently available port.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Single-player modes run in the browser and reject room operations with `mode_local`; multiplayer modes require `server.js`.\n\nPress Ctrl+C in the terminal to stop the preview. No account or publish key is required.\n\n## Limits\n\n- At most 3,000 files per version.\n- At most 100,000,000 bytes per file.\n- At most 500,000,000 bytes for all files in one version.\n- At most 4,000,000 bytes for `server.js`.\n- At most 60 versions per publishing key in any 24-hour window. Beyond that the portal answers `publish_rate_limit`.\n- Dotfiles, dot-directories, and directories named `node_modules` are ignored.\n- Symbolic links and other non-regular files are rejected.\n\nReduce or split files that exceed the per-file limit. Remove generated files that the browser does not need.\n\n## Publish\n\nUse the key supplied by the creator. Set it in the environment so it does not enter shell history as a command-line flag:\n\n```sh\nnpx @caisual/cli check\nexport CAISUAL_KEY=\'ck_...\'\nnpx @caisual/cli publish\n```\n\nRun the command from the game folder, or pass the folder path after `publish`. For local portal development only, set `CAISUAL_ORIGIN` to the local HTTP origin.\n\nThe CLI validates the folder, computes every file size and SHA-256 digest, creates a new version, uploads the files, completes the version, and prints the game URL. The stable URL is `https://caisual.com/g/<id>`.\n\nBefore contacting the portal, the CLI scans browser files for common WebGL2, WebGPU, WebAssembly, and shared-memory signatures. A possible mismatch is printed to stderr with a `Warning:` prefix and never blocks publishing. Correct an accurate warning by declaring the minimum matching `requires` field, and use a build without threads if shared memory is detected. If the signature belongs to unused code, remove that code from the published client bundle.\n\nThe first games from a new creator are reviewed before they can appear in the public catalog. Their stable links still work while review is pending.\n\n## Versions and rollback\n\nNew games start on the current version. An existing room stays on its own version for its entire life, including players arriving later through an invitation, a typed code or a friend. Its client, manifest, iframe permissions and images all come from that version.\n\nEvery `publish` creates a new immutable version, even for a tiny correction. The permanent address stays `/g/<id>`. The home page sorts games by the creation date of the current version; publishing can move a game up and a rollback can move it down.\n\n## Updates while a page is open\n\nCreating a room or starting a matchmaking search from an outdated page fails with `version_outdated` and `currentVersion`. Joining an existing room from another version fails with `version_mismatch` and `roomVersion`. A room whose version is no longer ready, or whose game was deleted, shows **This room is no longer available**, with a link to the current game.\n\nMatchmaking keeps versions separate. A reservation already accepted before an update can finish on its original version. Existing rooms are not restarted by an update or rollback.\n\nThe game receives these errors both as rejected room operations and through `c.room.onError(listener)`. Show a button that calls `c.room.reload()` after either error, to load the current game or the room referenced by the failed join:\n\n```js\nc.room.onError((error) => {\n if (error.code === \'version_outdated\' || error.code === \'version_mismatch\') {\n showReloadButton(() => c.room.reload());\n }\n});\n```\n\n## List and restore versions\n\nUse the same `CAISUAL_KEY` environment variable as for publishing:\n\n```sh\ncaisual versions\ncaisual versions ./my-game\ncaisual rollback --to 7\ncaisual rollback my-game --to 7\n```\n\nThe target defaults to the current folder, or accepts a folder or game ID. `versions` lists the number, date, state and size and marks the current version. The account page also marks it.\n\nRollback selects an existing ready version of that game. It copies no files, creates no new number and does not consume the 60-version daily allowance. Visibility and moderation stay unchanged. **Rollback restores code, not saved data.**\n\nIf another version was activated while a publish was uploading, the upload becomes ready but does not replace it. The CLI reports:\n\n```text\nVersion N is ready but not current: version M was activated in the meantime. Run caisual rollback --to N to activate it.\n```\n\nA manifest\'s visibility takes effect only when activation succeeds. An `unlist` or `relist` issued during an upload wins over that upload\'s manifest visibility.\n\n## Game versions and data formats\n\nSaves belong to the game, not to a game version. The creator is responsible for data compatibility. A game version and a data format version are separate things.\n\nFor a compatible change, keep the same keys. For an incompatible change, use a new key such as `progress_v2`. Import from `progress` only when `progress_v2` is missing. Keep the original, identify the format inside each value and never overwrite a format you do not recognize. Progress written later by an old version is not automatically merged into the new key.\n\nThe daily seed does not depend on the game version. Do not change the generator or rules halfway through a UTC day without changing the board ID.\n\n## Retention and local development\n\nGood versions stay. Old ready versions are retained for rooms and rollback, without automatic age-based deletion. Failed uploads are cleaned from both client and server storage; uploads left open for more than 24 hours fail with a note and are cleaned. Version numbers are never reused. Deleting a game removes its client and server files.\n\n`caisual dev` always uses game version 1. It does not simulate publishing, version changes or rollback.\n\n## Update, unlist, or delete\n\nTo update a game, change its files without changing `id`, then run `npx @caisual/cli publish` again. This creates a new version and keeps the same stable game URL.\n\nTo remove the current game from the catalog without publishing a new version, run:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli unlist\n```\n\nRestore its public visibility with:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli relist\n```\n\nDelete it permanently only when you are certain:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli delete --yes\n```\n\nEach command reads the `id` from `caisual.json` in the current folder. You may instead pass a game folder or an ID directly, for example `npx @caisual/cli unlist ./my-game` or `npx @caisual/cli relist my-game`. The publishing key always comes from `CAISUAL_KEY`, never from a flag. Deletion has no interactive prompt, is permanent, removes the stored game files, and never frees the ID for reuse.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing or managing a game.\n- `The publish API key is not valid`: create a new key in the account dashboard if the old key expired or was revoked.\n- `game_not_found`: check that the game ID is correct and belongs to the creator represented by `CAISUAL_KEY`; deleted games return the same error.\n- `caisual.json is not valid`: read every reported field and rule, fix all of them, then retry.\n- `client/index.html: file not found`: place `index.html` directly under `client/`, not in a nested build folder.\n- `referenced file not found`: make sure `cover`, `card`, `icon` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 100 MB`: compress, reduce, or split the asset and update its references.\n- `upload failed` or a temporary portal error: keep the files unchanged and retry the same publish command. The CLI retries temporary upload failures automatically.\n- `publish_rate_limit`: this key has already created 60 versions in the last 24 hours. Wait until the oldest one leaves the window.\n- `burst_rate_limit`: too many publishing or management requests arrived at once. Wait briefly and retry.\n- `The multiplayer server could not be published`: read every diagnostic hint, fix `server.js`, and publish again. The failed version does not replace the current one.\n- An external browser request works locally but fails after publishing: add its host to `network` and publish a new version. Server code cannot make outbound network requests.\n- A threaded WebAssembly game fails to start: use a build without threads. Games embedded in the portal cannot use shared memory.\n\n## Required game images\n\nThe look of the game belongs to its creator: templates are deliberately neutral, and their placeholder images must be replaced.\n\nEvery manifest must declare three different files inside `client/`. All three are required PNG, JPEG or WebP images, at most 2 MB (2,000,000 bytes) each:\n\n| Field | Exact size | Use |\n| --- | --- | --- |\n| `cover` | 1536x1024, 3:2 | Featured home card, game page background, social preview, mobile invitation |\n| `card` | 1024x1024, 1:1 | Secondary home cards and square invitation artwork |\n| `icon` | 1024x1024, 1:1 | Game window favicon, friends and parties |\n\n**No text inside any image:** no title, slogan, letters or numbers. The portal displays the game name. Keep the icon simple enough to read at a small size. The files must be different, including `card` and `icon`. Screenshots keep their existing rules.\n\nThe 3:2 and 1:1 ratios match native formats of widely used image generators. Export at the exact sizes above: Caisual does not crop, stretch or accept a size range. `caisual check` and publish validate the format from the file headers, exact dimensions and weight. The portal repeats these checks for direct publication. The absence of text is an editorial requirement, not an automatic check.\n\nAll three `caisual init` variants include small, real PNG examples at these sizes. Replace them with artwork for your game before sharing it. English (`en`) is always required in `languages`; the first language remains the default, for example `["it", "en"]`.\n';
1219
1162
 
1220
1163
  // ../../docs/kit.md
1221
- var kit_default = "# Caisual game kit\n\nThe kit gives a published game a stable player identity, cloud saves, a daily challenge seed, and multiplayer rooms with server-owned state.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page: the game keeps its own rendering, input, and UI.\n\n## Load the kit\n\nEvery published game can import the kit from its own origin, without a bundler and without an npm install:\n\n```html\n<script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n\n const c = await caisual.connect();\n console.log(c.player.name);\n</script>\n```\n\nGames built with a bundler can install the same module from npm:\n\n```sh\nnpm install @caisual/kit\n```\n\n```js\nimport { caisual } from '@caisual/kit';\n```\n\nBoth forms expose the same API. The module also sets `globalThis.caisual` for classic scripts that load it first.\n\nThe path `/__caisual/` is reserved on every game origin. Do not put game files under it.\n\n## Connect\n\n```js\nconst c = await caisual.connect();\n```\n\n`connect()` completes when the game is running inside caisual.com and has received its player identity, or after a short timeout when it is not. Calling it again returns the same promise.\n\n- `c.connected` is `true` inside caisual.com and `false` when the game runs on its own, for example from a local folder during development or when its files are copied elsewhere.\n- `c.player` is `{ id, name, guest, language, uiLanguage }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or a stable `Guest-XXXX` name derived from the player id. The four-character suffix uses `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, excluding I, O, 0 and 1; it helps distinguish guests but is not a unique identifier. `guest` is `true` for players without an account. `language` selects game strings; `uiLanguage` is the overlay locale. On first sign-in to an account without a player identity, the browser guest is adopted with its existing id and saves. An account that already has a player identity uses that identity instead; guest data is not merged.\n- When not connected, `c.player` has `id: \"local\"`, `name: \"Guest\"`, `guest: true`, plus both language fields. If the host answered, its language information is kept; without a handshake, `language` is the normalized `navigator.language` (or `en`) and `uiLanguage` is its overlay fallback.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\n## Game language and strings\n\n`c.player.language` is the game's language; `c.player.uiLanguage` is the overlay's locale. Use the former for game strings and formatting, or the latter when intentionally aligning text with the overlay.\n\nThe kit resolves the player's explicit portal language choice, otherwise `navigator.languages` in order, against `manifest.languages`. For each preference it tries the exact tag and then its parent tags; if none of the preferences match, it uses the game's first declared language. The result is always a normalized declared tag. For example, `ja-JP` with `languages: [\"en\", \"ja\"]` selects `ja`, while `uiLanguage` is `ja-JP`. The overlay supports English, Italian, Spanish, French, German, Portuguese and Japanese; it keeps regional tags in those families, such as `pt-BR`, and falls back to `en` for other languages. Games may declare languages outside these seven.\n\nA localized portal URL counts as a language choice. The language selector remembers explicit choices, including English; without either, the browser's ordered preferences apply. The handshake keeps its legacy `language` field for existing kits, and also sends `uiLanguage`, `languagePreferences` and `gameLanguages`. The kit resolves the game language, including when player services fail after a successful handshake.\n\nWithout a handshake, no manifest is available: `language` is the raw preference from `navigator.language`, normalized as a BCP 47 tag, or `en` if invalid or unavailable. It is not restricted to declared game languages. `uiLanguage` uses the overlay fallback. In `caisual dev`, `?lang=ja` selects `ja` when the manifest declares it, with a Japanese overlay. Without `?lang=`, dev uses `navigator.languages` in order for the game.\n\nPut all game UI strings in flat JSON dictionaries named `client/i18n/<lang>.json`. Use canonical BCP 47 filenames, for example `en.json`, `it.json`, `pt.json`, `pt-BR.json`. Every value is a string; keys are identical across dictionaries. Text can contain named placeholders such as `{n}`.\n\nDeclare supported languages in `caisual.json`, always including `en`. English is required alongside the game's own languages; the first entry is the default and may be another language. This complete manifest supports a local game:\n\n```json\n{\n \"manifest\": 1,\n \"cover\": \"cover.png\",\n \"card\": \"card.png\",\n \"icon\": \"icon.png\",\n \"id\": \"three-lights\",\n \"name\": \"Three Lights\",\n \"platform\": \"both\",\n \"languages\": [\"en\", \"it\"],\n \"overlay\": { \"version\": 1 },\n \"modes\": [{\n \"id\": \"solo\",\n \"execution\": \"local\",\n \"label\": { \"en\": \"Solo\", \"it\": \"Da solo\" },\n \"instructions\": { \"en\": \"Light up three lights.\", \"it\": \"Accendi tre luci.\" }\n }]\n}\n```\n\n`client/i18n/en.json`:\n\n```json\n{ \"score\": \"Lights: {n} / 3\", \"light\": \"Light up\", \"done\": \"Complete\" }\n```\n\n`client/i18n/it.json`:\n\n```json\n{ \"score\": \"Luci: {n} / 3\", \"light\": \"Accendi\", \"done\": \"Tutte accese!\" }\n```\n\nLoad once during setup, before `c.session.ready()`. The returned function is synchronous and can be used in every draw call:\n\n```html\n<!doctype html>\n<html>\n<head><meta charset=\"utf-8\"><title>Three Lights</title></head>\n<body style=\"margin:0;min-height:100dvh;display:grid;place-content:center\">\n <p id=\"score\"></p>\n <button id=\"light\" disabled></button>\n <script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n const c = await caisual.connect();\n const t = await c.text();\n document.documentElement.lang = c.player.language;\n const score = document.querySelector('#score');\n const light = document.querySelector('#light');\n let n = 0, blocked = false, active = !c.session.capabilities.overlay;\n function draw() {\n score.textContent = n === 3 ? t('done') : t('score', { n });\n light.textContent = t('light');\n light.disabled = blocked || !active || n === 3;\n }\n c.overlay.onChange((view) => { blocked = view.inputBlocked; draw(); });\n c.session.onChange((session) => {\n if (session.kind === 'local' && session.status === 'playing') n = 0;\n active = !c.session.capabilities.overlay || (session.kind === 'local' && session.status === 'playing');\n draw();\n });\n light.onclick = () => {\n n += 1;\n if (n === 3 && c.session.current.kind === 'local') c.session.finish();\n draw();\n };\n draw();\n c.session.ready();\n </script>\n</body>\n</html>\n```\n\n`c.text(): Promise<Text>` makes one request to the game's own origin, tied to the version currently open. Caisual and `caisual dev` read the matching files and merge them per key: `pt-BR` then `pt` then the manifest's default language. Longer tags fall back through their parent tags, such as `zh-Hant-TW`, `zh-Hant`, `zh`. The default file is tried once. If no file contains a key, `t` returns that key. Empty strings are valid translations.\n\nConcurrent and later `c.text()` calls share the same promise and translator for that connection. There are no dependencies, eager downloads, or per-call network requests. Missing files, invalid dictionaries and network failures do not prevent startup. If the Caisual text service is unavailable, for example on a plain static host outside Caisual, the translator returns keys; it does not probe other URLs. Use `caisual dev` to preview the complete convention.\n\n`t('score', { n: 3 })` replaces named placeholders with strings or numbers. An omitted placeholder stays unchanged, such as `{n}`. The result is plain text, with no HTML processing, plural rules or automatic translation. Set `textContent` or draw it on the canvas; do not insert it as HTML. A new document gets the host's current language and a fresh translator.\n\n`description`, mode `label` and `instructions`, and role `label` accept a string or a language-to-text object, and resolve from `uiLanguage` in the overlay using the same fallback chain. Descriptions also resolve from the page language in the catalogue, game page, profiles, invitations and metadata. Each description translation must contain 1-500 characters on one line and use a key declared in `languages`. `name` and `tags` keep their existing forms. Existing single-string labels stay unchanged. See [manifest languages and validation](./publish.md#game-translations) for CLI checks and migration from `language`.\n\n## Sessions and the standard overlay\n\nA game that declares `overlay` in `caisual.json` is a standard game: it runs full screen and Caisual draws everything around it. The opening menu groups modes into Single player (`players.max === 1`, including rooms for one) and Multiplayer, omitting tabs for one group and the mode selector for one mode per group. The mode choice, the lobby with roles, teams and ready, invitations, friends and parties, matchmaking, spectators, voice, the end of a match and Play again belong to the platform. The game keeps the field, its own HUD and its own settings.\n\n```json\n{ \"overlay\": { \"version\": 1, \"accent\": \"#397e83\" } }\n```\n\nTwo objects appear on the connection. `c.session` says which session the game is in, `c.overlay` says when the platform is on top of it.\n\n```js\nconst c = await caisual.connect();\n\nconst stopSession = c.session.onChange((session) => {\n detachGameListeners();\n if (session.kind === 'idle') return showAttractScene();\n if (session.kind === 'local') return showLocalRun(session.mode, session.status);\n attachGameListeners(session.room, session.kind === 'watch');\n draw(session.room.state);\n});\n\nconst stopOverlay = c.overlay.onChange(({ inputBlocked, reservedRects }) => {\n clearHeldKeys();\n setInputEnabled(!inputBlocked);\n placeHudOutside(reservedRects);\n});\n\nawait loadAssetsAndChosenView();\nc.session.ready();\n```\n\n### The session\n\n`c.session.current` reads the session at once. `onChange` repeats the current value immediately to every new listener, returns a function that removes it, and then reports attaches, detaches and the end of a local run. It never fires for a move or a roster change: those stay on the room listeners.\n\n- `{ kind: 'idle' }`: no session. Show an attract scene, not a menu.\n- `{ kind: 'local', id, mode, status }`: a run of a mode declared with `\"execution\": \"local\"`. `status` is `playing` or `ended`.\n- `{ kind: 'room', id, room }`: `room` is the `Room` documented below, already attached.\n- `{ kind: 'watch', id, room }`: `room` is a `Spectate`. Draw it read only.\n\n`id` changes on every attach, so a second local run is distinguishable from the first.\n\n`c.session.ready()` says the game has loaded its assets and installed its listeners. Call it once, at the end of setup: until then the overlay waits instead of starting a session under a game that is still downloading. It is idempotent.\n\n`c.session.finish()` ends a local run and shows the compact end bar with a Play again action. It applies only to `kind: 'local'`: on a room it fails with `not_local` and on idle it does nothing. The result of an online match comes from the server, never from `finish()`.\n\n`c.session.capabilities` is `{ local, rooms, overlay, requestRole }`. Outside caisual.com `overlay` and `rooms` are `false` while `local` stays `true`, which is the signal to run the game's own offline fallback. No fake room is created.\n\nTwo front ends of the same game share one session. Switching view does not call `ready()` again and does not detach the room: the new renderer reads `c.session.current` and draws.\n\n### The overlay on top\n\n`c.overlay.onChange` repeats the current geometry immediately, then on every change:\n\n- `inputBlocked` is `true` while a panel is open. Release held keys and stop reading input, but keep simulating: opening a panel never pauses a room.\n- `reservedRects` is an array of up to eight `{ x, y, width, height }` rectangles in CSS pixels of the game viewport. Keep the game's own HUD out of them, and nothing else: never resize, move, or letterbox the field because of them. The overlay sits on top of the game and the game must not shift when a bar or a pill appears. The field under a closed overlay stays visible and clickable.\n\nThe complete `OverlayView` value is `{ inputBlocked, reservedRects, safeArea?: { top, right, bottom, left }, shortcutEnabled? }`.\n\nThe host measures `safeArea: { top, right, bottom, left }` in CSS pixels of the game viewport, accounting for the iframe's position, borders and scale. It updates after viewport changes, including rotation. Use these values for HUD margins: `env(safe-area-inset-*)` inside the iframe usually reads zero. The kit also sets `--caisual-safe-top`, `--caisual-safe-right`, `--caisual-safe-bottom` and `--caisual-safe-left` on the game document root:\n\n```css\n.hud {\n top: max(16px, var(--caisual-safe-top, 0px));\n left: max(16px, var(--caisual-safe-left, 0px));\n}\n```\n\n`safeArea` is optional for compatibility with older hosts; treat a missing value as four zeros. Older kits keep receiving their supported geometry fields. During the opening screen, `inputBlocked` is true from the first view, including before the first host measurement.\n\n`c.overlay.open(panel)` asks the platform to open one of `home`, `room`, `invite`, `friends`, `voice`. It is a request, not a permission: it creates no room and grants nothing. Outside caisual.com it does nothing.\n\nShift+Tab from the field opens the menu and Escape closes it. Text fields inside the game keep their own shortcut.\n\n### What a standard game no longer builds\n\nRemove these and let the overlay do them:\n\n- a start menu with Create, Join or a code field;\n- invitation links, copy buttons and share sheets;\n- the lobby: roster, ready, role and team pickers, the Start button;\n- a matchmaking screen with its cancel button;\n- a friends or party list;\n- voice buttons;\n- an Exit or Back to Caisual button;\n- a Play again button after a match.\n\nThe end bar recognizes optional standings and winners; the game may draw additional result details inside the field. `c.room.create`, `join`, `match` and `watch` stay available for a game that wants its own entry point: under a standard overlay the room they return becomes the current session and the standard controls follow it. Do not attach a second room controller from a second renderer.\n\n### Full screen\n\nA standard game fills the window. `html`, `body` and the game surface are 100% of the viewport: no maximum width, no header, no footer, no editorial frame, and no document scrolling at 1366x768 or 390x844, safe areas included. Only the HUD and compact controls sit over the scene.\n\nAim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile, counting only what shows or controls the game. A board with a fixed aspect ratio cannot always reach that: a square board on a 1366x768 window tops out near 56% before any HUD. That is the declared geometric exception: the board must then fill at least 90% of the largest rectangle that fits the area left free, and the HUD must have a stated ceiling, typically 48 to 64 pixels on desktop and about 160 pixels of controls on a phone.\n\n### Resume\n\nCaisual keeps one resume reference per game and per player, in a save key it owns. Leaving through the overlay with Leave for now stores the room code and detaches without giving up the seat; the standard menu then offers Resume, which rejoins from that code. Leave room removes the reference and gives up the seat, and so does a terminal room end. A `finished` room waiting for a rematch keeps its resume reference. A network drop keeps it.\n\nA game does not read or write that key, and does not build its own Resume button. A reference that is no longer valid returns the service error and the overlay explains it: it does not retry forever. Resume carries the room code, not a promise to reopen the same published version of the game.\n\n### Voice\n\nIn a standard game the overlay's voice panel carries Join, Leave, Mute, and the list of who is in the call, with the click the browser requires. A standard game does not draw its own voice buttons. The `room.voice` API below remains for games without the standard overlay and for server-side gain and proximity rules.\n\n### Known gaps\n\nThree things are deliberately not in this version, and a game should not work around them:\n\n- resolving the original game version behind a persistent Resume;\n- inviting one friend straight into a room, as opposed to a party;\n- matchmaking for a whole group at once.\n\n## Daily challenge\n\n`c.daily` describes the day selected when the connection opened. `day`, `seed` and `expiresAt` stay fixed for that connection, including across UTC midnight. `expiresAt` is the next UTC midnight in milliseconds on the server clock.\n\n```js\nc.daily.day;\nc.daily.seed;\nc.daily.expiresAt;\nconst random = c.daily.rng();\nconst stop = c.daily.onChange(({ day, seed, expiresAt }) => {\n offerNextDailyRun({ day, seed, expiresAt });\n});\n```\n\n`onChange` reports a new `{ day, seed, expiresAt }` when the current UTC day changes. It returns an unsubscribe function and does not immediately replay the initial value. A suspended browser or a connection failure can delay the notification; the kit retries and reports the latest day when it can. The event does not mutate `c.daily` or reseed either generator. `rng()` always creates a fresh generator from the connection's original seed, and `random()` keeps advancing the original shared generator. Use the event's context explicitly for a new daily run, or open a new document. Repeated `connect()` calls return the same connection.\n\n`day` is a UTC date such as `\"2026-09-04\"`; `seed` is an unsigned 32-bit integer shared by all players of that game on that day. Both generators produce values in [0, 1). `c.time.now()` is in milliseconds aligned with the portal clock. Without a connection, daily data uses the local clock and hostname, with the same listener and generator behavior.\n\nOn the server, `room.daily` is `{ day, seed, expiresAt }`, fixed at **room creation**, persisted across sleep and rematches. Its seed matches a client connection opened for that game on the creation day. A client connected yesterday can therefore have a different `c.daily` from a room created today: send the room's daily context through game state when rendering its course. To switch a persistent or rematched room to a new daily course, create a new room.\n\n`caisual dev --day YYYY-MM-DD` fixes the simulated day and seed for new connections and rooms. Clocks stay real: `expiresAt` is the next **real** UTC midnight at connection or room creation, so comparing it with `c.time.now()` or `room.time.now()` remains valid even for a simulated date. Restored rooms keep their original daily context. Restart dev and reload to change the flag; create a new room for the newly selected day.\n\n## Saves\n\nEach player has up to 64 saves per game. A save is any JSON value up to 256 KB when serialized.\n\n```js\nawait c.save.set('slot1', { level: 3, coins: 120 }); // -> { key, bytes, updatedAt }\nconst data = await c.save.get('slot1'); // -> the value, or null\nawait c.save.remove('slot1');\nconst saves = await c.save.list(); // -> [{ key, bytes, updatedAt }]\n```\n\n- Keys use 1 to 32 characters: lowercase letters, digits, `_` or `-`, starting with a letter or digit.\n- `updatedAt` is a millisecond timestamp.\n- Saves are per player and per game. Another game cannot read them.\n- When not connected, saves go to the browser's local storage on the game origin.\n\nErrors reject the promise with an `Error` whose `code` is one of `invalid_request`, `not_found`, `save_limit`, `payload_too_large`, `rate_limited`, `invalid_ticket`, `internal_error`, or `offline`.\n\n## Device\n\n`c.device` contains the browser and device report collected while `connect()` runs:\n\n```ts\ninterface DeviceReport {\n webgl2: boolean;\n webgpu: boolean;\n wasm: boolean;\n threads: boolean;\n isolated: boolean;\n gpu: 'hardware' | 'software' | 'none';\n memoryMb: number | null;\n cores: number | null;\n mobile: boolean;\n tier: 'low' | 'mid' | 'high';\n}\n```\n\n`device.isolated` measures the browser's actual `crossOriginIsolated` state. Games embedded in the portal report `false`; shared memory and threaded WebAssembly are unavailable there. This runtime probe does not enable isolation.\n\nUse capability fields to choose a renderer, then use `tier` to reduce pixel ratio and quality on smaller devices:\n\n```js\nconst renderer = c.device.webgpu\n ? createWebGpuRenderer()\n : createWebGl2Renderer();\n\nconst pixelRatio = c.device.tier === 'high' ? devicePixelRatio : 1;\nconst quality = c.device.tier === 'low' ? 'low' : 'high';\nrenderer.configure({ pixelRatio, quality });\n```\n\nThe probe takes at most 1.5 seconds. `memoryMb` and `cores` are `null` when the browser does not expose them. The report stays in the browser and is not saved or sent to Caisual.\n\n### Two front ends, one game\n\nKeep one `client/index.html`, one game ID and one server. With `platform: \"both\"`, choose separate front ends in that entry without navigating or adding another iframe:\n```js\nimport { caisual } from '/__caisual/kit/v1.js';\nconst c = await caisual.connect();\nlet preference = null;\ntry { preference = localStorage.getItem('layout'); } catch {}\nconst touch = preference === 'touch' || (preference !== 'desktop' && (c.device.mobile || matchMedia('(pointer: coarse)').matches));\nconst screen = touch ? await import('./touch/main.js') : await import('./desktop/main.js');\nscreen.mount({ c, root: document.querySelector('#app') });\n```\nOffer a manual layout choice, persist it when storage is available, and keep rules and room connections shared. Both front ends use relative asset paths inside `client/`.\n\n## Game version changes\n\nNew games use the current version. Existing rooms retain their version for their whole life, including invitations, typed codes, friends, spectators and Resume. Matchmaking never mixes versions; an accepted reservation can finish on its original version. Saves and `room.shared` remain per game, with data compatibility handled by the creator. See [Versions and rollback](./publish.md#versions-and-rollback).\n\nA room create or match operation rejects with `version_outdated` and `currentVersion` when the loaded game is no longer current. A join, watch or reconnect rejects with `version_mismatch` and `roomVersion` when the room uses another version. The standard overlay shows **This game was updated** with **Reload game** for outdated pages; a mismatched code or Resume reloads the portal with the room invitation, preserving watch intent for spectators.\n\nCustom menus can subscribe with `c.room.onError(listener)`, which returns an unsubscribe function. The error has `code`, `message`, and the applicable version number. The operation also rejects with that error. `c.room.reload()` reloads the portal on the current game after `version_outdated`, or on the last mismatched room after `version_mismatch`. Show a button calling it after either error. This works without the standard overlay.\n\n`caisual dev` always uses game version 1 and does not simulate version changes.\n\n## Rooms\n\nA room brings players into the same running game. Creating and joining require a published `server.js`; single-player games can ignore `c.room`.\n\nIn a standard game the overlay creates, joins, matches and watches on the player's behalf, and hands the game the room through `c.session`. The calls below stay available, and their result becomes the current session. Read them for what the room object offers; do not rebuild the entry screens around them. An optional [MatchResult](#recognized-match-results) in `room.end` lets the overlay display winners and standings while `room.result` keeps the original JSON.\n\n```js\nconst c = await caisual.connect();\n\nc.room.invited; // invitation code from the game page, or null\n\nconst room = await c.room.create({ mode: null });\n// Or join the invitation that opened the game:\nconst invitedRoom = await c.room.join();\n// Or enter a code supplied by the player:\nconst codedRoom = await c.room.join('ABC234');\n\nroom.code;\nroom.seed; // unsigned 32-bit integer fixed for this room\nroom.tickRate;\nroom.latency;\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nPass a mode id from the manifest to `create({ mode })`, or `null` to use the root configuration. Optional `players` and `lobby` on that mode replace the root values; joining keeps the configuration of the room being joined. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. A standard game does not need `invite()`: the overlay owns the invitation panel and the copy action.\n\n### Crew\n\nThe kit automatically reports the player's current room to the Caisual portal, so the player's friends can join with one click. The game does not need to send or handle anything for this. There is no `c.crew` API in this version. In a standard game the friends and party list is a panel of the overlay, so there is nothing to draw either.\n\n### Matchmaking\n\nUse `c.room.match()` to find players who requested the same mode and key. The key must contain exactly the fields declared by that mode's `matchmaking.key` in `caisual.json`.\n\n```js\nconst room = await c.room.match({\n mode: 'daily',\n key: { day: c.daily.day, stage: 3 },\n onWaiting({ players, min, max }) {\n showQueue(`${players}/${max} players, ${min} required`);\n },\n});\n```\n\nMatchmaking uses the selected mode's resolved `players` and `lobby`, and that mode's `matchmaking.timeoutMs`. A room opens as soon as the queue reaches the resolved `players.max`. When `matchmaking.timeoutMs` expires, it also opens if at least `players.min` players are waiting. Otherwise the promise rejects with `no_match`, and the game should offer the player another option. A new search first tries to fill a matching room that is already open and can still accept players.\n\nPass an `AbortSignal` as `signal` to let the player cancel a search. Cancellation rejects with `cancelled`. In a standard game the search screen, its Cancel button and the lobby that follows are the overlay's: declare `matchmaking.defaults` in the mode and the player can start a search from the standard menu without the game passing a key.\n\nRoom status is one of:\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: the lobby has accepted `start()` and play begins at the announced server time.\n- `playing`: the game server is running the match.\n- `finished`: the match is over and the room is waiting for a rematch, with sockets open and `room.result` available.\n- `ended`: the match or connection has ended. `room.result` contains the result last reported by the room. A definitive connection closure uses `{ closed: 4003 }` when the player was kicked, `{ closed: 4004 }` when the room ended, `{ closed: 4005 }` when the published version closed, or `{ closed: 4006 }` when the same player opened the room in another tab.\n\nThe current lobby data is available directly:\n\n```js\nroom.players; // [{ id, name, guest, role, team, ready, connected }]\nroom.you; // this player's id\nroom.host; // the current host's id, or null\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n\nif (room.you === room.host) room.start();\n```\n\nIn a standard game the overlay calls these four for the player: read `room.players` to draw the field, not to build a roster panel. `ready`, role, team, and `start()` are lobby actions. Starting requires the host, every connected player to be ready, and the player, role, and team minimums from the manifest. Calling `start()` begins a three-second countdown. A role or team change clears that player's ready state. The built-in `spectator` role is still a player slot for setups such as a shared screen with phone controllers. Use `watch()` for someone who only observes and does not occupy a player slot.\n\n### Rematch in the same room\n\nThe server opts in per match with `room.end(result, { rematch: true })`. The room becomes `finished`, keeps its code, members, state and open connections, and exposes the result through `room.result` and `onStatus('finished', result, at)`. Voice and spectator streams remain connected. `room.end(result)` or `{ rematch: false }` still ends the room permanently with status `ended` and close code 4004.\n\nWith `rematch: true` in a multiplayer room, each connected player calls `room.restart()` once to become ready for the rematch. In `finished`, `room.players[].ready` means rematch readiness. Once every connected non-spectator player is ready and the mode's `players.min` is met, the host calls `room.restart()` again to confirm. The first host call only registers readiness. A host with the built-in `spectator` role does not register readiness and can confirm once the players are ready. Repeated non-host calls do nothing. Calling outside `finished` fails with `rematch_unavailable`; an early host confirmation reports `players_not_ready` through `room.onError`.\n\nThe standard overlay handles these calls with Play again, the readiness count and names, and Start rematch for the host. Games without the overlay can call `restart()` directly. No member is removed for declining. With `rematch: true`, there is no automatic start after a departure: the current host must confirm.\n\nAt confirmation, the kit clears the result to `null` and all readiness flags, then calls optional `onRestart(room)` with status `lobby` when the mode has a lobby, or `playing` otherwise. **The kit does not reset `room.state`.** Reset match data in `onRestart`, keeping series scores or other data as needed. With a lobby, players choose their setup and get ready again before the normal countdown and `onStart`. Without a lobby, `onStart` follows `onRestart` immediately. Clients receive the new state and an `onStatus` transition with a null result. The room identity, seed and tick sequence are retained; `session.onChange` does not create a new session for a rematch. Listen to `room.onState` and `room.onStatus`.\n\n### Fast rematches and solo rooms\n\nThe existing `rematch: true` flow above is unchanged for multiplayer rooms. To shorten it, use:\n\n```js\nroom.end(result, { rematch: { keepSetup: true, autoStart: true } });\n```\n\nBoth flags default to `false`. `keepSetup` restores the previous readiness flags, keeps roles and teams, and skips the lobby: `onRestart` runs with status `countdown`, followed by the usual three-second countdown and `onStart`. The result clears before `onRestart`. Even a mode without a lobby gets this countdown. Readiness during `finished` is still consent for the next match, separate from the previous setup. Player, role and team minimums are rechecked during the countdown; if they fail, the room returns to the lobby so the setup can be repaired.\n\n`autoStart` starts the rematch when all connected non-spectator players have accepted and the mode's minimum is met, including after a departure leaves that condition satisfied. The overlay shows the readiness count and names without a host confirmation button or wait-for-host text. With `autoStart`, the host can also call `restart()` again to confirm early once at least `players.min` connected non-spectator players have accepted. Members who have not accepted remain in the room and join the next phase; they are not removed. With `autoStart` alone, the next phase is the usual lobby or immediate play; combine it with `keepSetup` to skip another ready/start cycle.\n\nA room whose resolved `players.max` is `1` is a solo room, including when it inherits `lobby: true`: it starts on entry and shows no lobby, invitation, code or wait-for-host prompt. In `finished`, one `room.restart()` immediately runs `onRestart`, then `onStart`, without consent or host confirmation or a countdown. The standard Play again button makes that one call. After a terminal end it creates a new solo room without opening or copying an invite. No additional manifest field is needed; `caisual init` without `--multiplayer` still creates a local game.\n\nThe waiting rules are:\n\n- All pending `room.schedule` handlers are cancelled when the match finishes, including handlers already due in the same batch. Scheduling during `finished` has no effect. Schedule new work in `onRestart` or `onStart`. Tick callbacks stop immediately; game input during the wait is discarded, and queued continuous input is cleared on the client.\n- `onEnd` runs once for the completed match, with status `finished` and its result. A subsequent timeout only closes the room and does not call `onEnd` again.\n- Disconnecting clears that member's readiness and transfers the host to the oldest connected member. Disconnected players do not count toward readiness or the minimum. The usual 60-second reconnection grace applies; persistent members keep their seats after it. Rejoining requires a new readiness call. Connection and departure callbacks continue during the wait.\n- New members may join by invitation during the wait, up to the resolved `players.max`, and start unready. A lobby mode therefore reopens admission while `finished`; without a lobby, admission continues as during play. Disconnected members still occupy seats until removed. Roles and teams retain their existing capacity rules.\n- `watch()` spectators do not vote or occupy seats and keep following the same delayed stream across matches. Members with role `spectator` occupy a seat but do not vote or count toward the rematch minimum.\n- The room closes with 4004 exactly two minutes after entering `finished` if no restart is confirmed, retaining the last result. Readiness, joins and pings do not extend this deadline. It also applies to persistent rooms and survives sleep or restoration; it does not depend on active ticks.\n\n`finished` is a new status, not a terminal connection state. Older room clients receive the unfamiliar status and keep their sockets open instead of taking their `ended` cleanup path; they have no `restart()` control, and older overlays may retain their previous screen. Use an updated kit for games opting into rematches, and explicitly handle `finished` in game status listeners.\n\nThe server owns room state. Read it and react to updates, but do not assign to it or mutate nested values from the browser:\n\n```js\ndraw(room.state);\n\nconst stopState = room.onState((state, tick, serverTime) => {\n draw(state);\n});\n\nconst stopPlayers = room.onPlayers((players) => updateLobby(players));\nconst stopStatus = room.onStatus((status, result, at) => showStatus(status, result, at));\n\nstopState();\nstopPlayers();\nstopStatus();\n```\n\n`room.tick` identifies the latest state. The kit applies structural updates in order for both tick-based and event-only servers. Full state is sent on entry, reconnection or resync when an update does not match the current tick; normal updates, including every hundredth tick, remain diffs. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\n`room.tickRate` is the current effective server frequency, including reductions caused by the CPU budget; zero means event-only. Updates arrive with state diffs and snapshots, including an empty diff when only the frequency changes. `room.latency` is the smoothed round-trip time in milliseconds, or `null` before the first pong and after a dropped connection until the next pong. Each pong uses 20% of the new RTT and 80% of the previous estimate, with the first sample used directly. Read the property when drawing network status; there is no `onLatency` listener. Spectators expose the same properties; their tick rate follows the delayed state stream.\n\nSend JSON input to `onMessage` in the server definition, and receive JSON sent or broadcast by the server:\n\n```js\nroom.send({ type: 'fire', target: 3 });\n\nconst stopMessages = room.onMessage((message) => {\n showEvent(message);\n});\n```\n\nThe kit numbers outgoing inputs in increasing order. It automatically reconnects temporary failures with delays of 1, 2, 4, then 8 seconds, for at most the room's 60-second grace period. Each attempt gets a fresh room token. A successful reconnect replaces local state with a full server state. `room.send` calls while reconnecting throw an error with `code: \"offline\"`.\n\nUse `room.input(value)` for continuous controls, including calls from every animation frame:\n\n```js\nroom.input({ type: 'move', x: axisX, y: axisY });\nroom.onError(({ code }) => {\n if (code === 'rate_limited') showInputWarning();\n});\n```\n\n`input` copies and keeps only the latest JSON value in one slot. It coalesces updates and sends at most 30 times per second, or at the effective `room.tickRate` when that is lower and positive. With `tickRate: 0`, it still sends at most 30/s. It also waits for budget used by `send`. Values with the same JSON serialization are not resent on the same connection. Combine independent controls into that one value; there is no channel option. On the server it is an ordinary message passed unchanged to `onMessage`, exactly like `send`, with no extra envelope.\n\nDuring reconnection, `input` accepts updates without throwing `offline`. After the new welcome it sends only the latest value, even if it was sent on the previous connection. It never replays intermediate values or old commands. Use `send` for individual actions such as firing or confirming a turn; `send` still throws `offline` during reconnection. Invalid JSON input can throw `invalid_request`. Input stops after leaving, disconnecting intentionally or ending the room.\n\nGame messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`, reported through `room.onError`; malformed frames use 4009 `bad_message`. Neither closure is retried automatically.\n\nCall `room.leave()` for an intentional departure. The kit does not reconnect after leaving, being kicked, the room ending, the published version closing, or the same player opening the room in another tab.\n\n`room.disconnect()` is the other departure: it stops the transport, the retries and voice without sending a leave, so the server keeps the seat under its own persistence and grace rules. It is not reversible on the same object; returning means entering again from the code. The overlay uses it for Leave for now, together with the resume reference.\n\nA room also exposes `room.mode`, `room.countdownAt`, `room.connection`, `room.metadata`, and the `onMetadata` and `onConnection` listeners. `connection` is one of `connecting`, `connected`, `reconnecting`, `disconnected`, `ended`, `closed`, or `replaced`, where `replaced` means the same player opened the room in another tab. Unlike `session.onChange` and `overlay.onChange`, these listeners do not repeat the current value: read the getter first.\n\n`room.onError(listener)` reports technical protocol errors of the room as `{ code, message }`; it is not the place where a game reads its own result.\n\n`await room.requestRole('scout')` asks the server for a role change during a match. It works only while the room is playing, only for a role declared in the manifest, and only when `server.js` defines `onRoleRequest(room, player, role)`; the server approves by calling `room.setRole`. Without that callback nothing changes, and the capability shows as `false` in `c.session.capabilities`. It is not a shortcut for changing roles from the browser.\n\nRoom creation, joining, and matchmaking reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `no_server`, `no_match`, `cancelled`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, `create`, `join`, and `match` reject with `offline`.\n\n- `invalid_role`: a requested role id is malformed or is not declared in the manifest. Request a declared role id.\n- `role_change_unavailable`: the room is disconnected, is not playing, or `server.js` has no `onRoleRequest`. Wait for a connected playing state and provide that callback before offering the action.\n- `role_change_refused`: `onRoleRequest` returned without assigning the requested role. Leave the current role in place, or have the server approve with `room.setRole`.\n- `version_closed`: the room connection ended because its published version closed. Reopen the current game version and enter a current room.\n\nEvery listener call on a room returns a function that removes that listener: `onState`, `onPlayers`, `onStatus`, `onMessage`, `onMetadata`, `onConnection`, and `onError`.\n\n### Responsive action games\n\n1. Start with `npx @caisual/cli init --arcade my-arena`, a complete English/Italian canvas game with shared rules and tests.\n2. Accumulate `deltaSeconds` on the server and advance shared physics at a fixed 1/60 second step.\n3. Keep positions, collision or range checks, cooldowns and scores authoritative in `server.js`.\n4. Use `room.input()` for continuous controls and `room.send()` for discrete actions such as the starter's pulse.\n5. Number commands in the game and publish each player's last **applied** `ack` in `room.state`; transport sequence numbers are separate.\n6. Because `input()` coalesces values, send a bounded batch of unacknowledged commands; deduplicate on the server and consume at most one per simulation step.\n7. Predict your own entity with the shared step, replace it with each authoritative snapshot, then replay only commands after `ack`; ease corrections in the drawing only.\n8. Buffer remote samples by the `onState` timestamp and render behind `room.serverTime()`, accounting for RTT in `room.latency`, effective `room.tickRate`, and spectator `delayMs`.\n9. Clear pending controls on reconnection or a new round; keep the HUD inside safe areas and outside `reservedRects`, and end with `standings` plus `keepSetup`/`autoStart` rematches.\n10. Run the generated browser fixture and `/__caisual/players?n=2` with `dev --latency 120 --jitter 40 --loss 2`; see [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n### Spectators\n\nIn a standard game the overlay offers watching from the menu and the session arrives as `{ kind: 'watch' }`. Use `c.room.watch(code)` to observe a room without joining it as a player:\n\n```js\nconst view = await c.room.watch('ABC234');\n\ndraw(view.state);\nview.onState((state) => draw(state));\nview.onPlayers((players) => updateRoster(players));\nview.onStatus((status, result) => showStatus(status, result));\nview.onMessage((message) => showEvent(message));\n\nview.leave();\n```\n\nThe returned `Spectate` object exposes `state`, `tick`, `seed`, `status`, `players`, `host`, `code`, `result`, `delayMs`, the four listeners shown above, `serverTime()`, and `leave()`. It receives the room's public state, snapshots and updates, player list, status, and messages broadcast by `server.js`. The kit repairs a missed update automatically and reconnects temporary failures for the same 60-second grace period used by players.\n\nPublic room events are delayed by `delayMs`, which defaults to 3000 milliseconds. A game can set `\"spectators\": { \"delayMs\": N }` in `caisual.json`, where `N` is from 0 to 30000, or set `\"spectators\": false` to disable watching.\n\nA spectator has no `you`, `invite()`, `send()`, or voice API. Watching does not add anyone to `room.players`, does not affect roles, teams, player minimums, the host, or room lifetime, and is not visible to `server.js`. `watch()` can reject with `room_not_found`, `room_ended`, `spectators_disabled`, `spectators_full`, `rate_limited`, `offline`, or `invalid_request`.\n\n### Replays\n\n`\"replays\": true` in the manifest opts room matches into recording. The default is false. A replay link at `/g/<slug>/replay/<id>` opens the recorded version in a `kind: 'watch'` session, with `room.role === 'spectator'` and `room.replay === true`. Live views have `replay === false`. During replay, `c.room` also exposes the spectator reading fields and `c.room.watch()` returns the recording. The overlay supplies play/pause, seek and 0.5/1/2/4 speed. `serverTime()` follows that playback clock; listeners update on backward seeks as well.\n\nThe finished match panel offers Watch replay and Copy link after the archive is ready. Recordings include shared state, public names and roles, status and result. Private messages, voice and raw inputs are excluded. A 10 MiB or 30-minute limit produces a partial recording. Links expire 30 days after the start; deleting a game removes its replays. See [Spectators](/docs/spectators#replays) for the renderer flow.\n\n## Voice\n\nEvery room has a `room.voice` object. Voice is disabled by default and is enabled with the manifest's `voice` field.\n\nIn a standard game the overlay's voice panel carries Join, Leave, Mute, and the list of who is in the call, with the click the browser requires. A standard game does not draw its own voice buttons. The `room.voice` API below remains for games without the standard overlay and for server-side gain and proximity rules.\n\nA game with its own controls must offer an explicit one, because `join()` must be called from a click or another user gesture so the browser can start audio and, when publishing, request microphone permission.\n\n```js\nconst micButton = document.querySelector('#mic');\nconst voiceList = document.querySelector('#voice-list');\n\nfunction renderVoice(peers = room.voice.peers) {\n voiceList.replaceChildren(...peers.map((peer) => {\n const item = document.createElement('li');\n const player = room.players.find((entry) => entry.id === peer.id);\n item.textContent = `${player?.name ?? peer.id}: ${\n peer.speaking ? 'speaking' : peer.muted ? 'muted' : 'quiet'\n }`;\n return item;\n }));\n micButton.textContent = room.voice.state === 'off'\n ? 'Join voice'\n : !room.voice.mic ? 'Listening' : room.voice.muted ? 'Unmute' : 'Mute';\n}\n\nmicButton.addEventListener('click', async () => {\n if (room.voice.state === 'off') await room.voice.join();\n else if (room.voice.mic) room.voice.mute(!room.voice.muted);\n renderVoice();\n});\n\nroom.voice.onPeers(renderVoice);\nroom.voice.onState(() => renderVoice());\nrenderVoice();\n```\n\n`room.voice.mode` is `none`, `room`, `team`, or `proximity`. In `room` mode, every participant in voice can hear every other participant. In `team` mode, players hear only their team. In `proximity` mode, the room server controls the gain between participants. Call `room.voice.join({ mic: false })` to listen without opening or publishing a microphone. Spectators join in listening mode when they call `join()` without options. A spectator that calls `join({ mic: true })` receives the `spectator` error.\n\nThe room server authorizes every voice track by team and gain. Listening that is no longer allowed is refused or closed.\n\n`room.voice.state` is `off`, `joining`, `on`, or `reconnecting`. `room.voice.mic` is `true` while the local player is publishing. `room.voice.muted` and `room.voice.speaking` describe the local microphone. `room.voice.peers` contains the other voice participants as `{ id, mic, muted, speaking, volume, gain }`. A listening participant has `mic: false`, `muted: true`, and `speaking: false`. `volume` is the local setting and `gain` is the value from the room server. Use `room.voice.setVolume(playerId, volume)` with a value from 0 to 1 to change only local playback.\n\n`room.voice.onPeers(listener)` runs when participants, microphone state, mute state, speaking state, volume, or gain changes. `room.voice.onState(listener)` reports connection state changes. Both return a function that removes the listener.\n\nCall `room.voice.leave()` to stop publishing or listening without leaving the room. `room.voice.mute()` requires an active published microphone and otherwise throws `not_publishing`. `room.leave()` and the end of the room stop voice automatically.\n\n`join()` rejects with an `Error` carrying one of these stable codes: `voice_disabled`, `permission_denied`, `unsupported`, `spectator`, `offline`, or `voice_error`. Voice can reconnect after a temporary room or media connection failure. The state becomes `reconnecting` while the kit retries.\n\n## Server\n\nPut `server.js` next to `caisual.json` and publish it with the game. See [publish.md](./publish.md#multiplayer-server) for the file rules, validation, and publishing flow.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\n\nexport default defineGame({\n tickRate: 20, // required, an integer from 0 to 60; 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onConnection(room, player, connected) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onRoleRequest(room, player, role) {}, // approve with room.setRole\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n onRestart(room) {},\n});\n```\n\n`tickRate` is the only required field: `defineGame` throws a `TypeError` when it is missing or is not an integer from 0 to 60. All callbacks are optional. A player is `{ id, name, guest, role, team, connected }`.\n\n### Callback order\n\n- `onCreate` runs once when the room is first created, before any player joins.\n- `onJoin` runs when a player first enters the room, not when that same member reconnects. Without a lobby, the first player's `onJoin` is followed by `onStart`.\n- `onStart` runs when the room changes to `playing`. Without a lobby this is the first player entry. With a lobby it is after the host starts, the three-second countdown finishes, and the room still meets its minimums.\n- `onTick` runs for each active game tick when `tickRate` is greater than zero. `onMessage` runs for accepted client game messages, and `onRoleRequest` runs for an in-match role request when that callback exists. These events are processed serially, so their relative order is the order in which the room processes them.\n- `onConnection(room, player, connected)` runs with `false` when an existing member loses their connection and with `true` when that disconnected member returns. Both `player.connected` and `room.players` are already updated. It does not run for the first entry, a socket replacement while the member is still connected, or a permanent removal. Restoring a room reconciles actual connections: members saved as connected whose sockets are gone receive `false`, and their later return receives `true`. Surviving sockets receive no extra callback.\n- `onLeave` runs only when a player is removed with reason `left`, `timeout`, or `kicked`. A dropped connection calls `onConnection` during the grace period and does not call `onLeave`.\n- `onEnd` runs after the callback that requested `room.end`, with the final result and status `ended` or `finished`. Automatic room endings also use it, except closure of an already `finished` match, which must not run it twice.\n- `onRestart` runs when a rematch starts, after clearing the result and selecting the next status. Readiness is reset by default or restored with `keepSetup`. The fast-rematch and solo rules above override the default host-confirmed flow. With a lobby it prepares `lobby`; without one it prepares `playing` and is immediately followed by `onStart`. It is optional; `room.state` is preserved unless the game changes it.\n\nThere is no `onResume` callback. A sleeping room restores its saved state without calling one. When a scheduled time arrives, the room invokes the method named by `room.schedule`.\n\nFor a turn-based game, store the active player's id and pause that turn when the player disconnects. This also works with `tickRate: 0`, because callback state changes are published immediately:\n\n```js\nonConnection(room, player, connected) {\n if (room.state.turnPlayerId === player.id) {\n room.state.turnPaused = !connected;\n }\n},\nonMessage(room, player, message) {\n if (room.state.turnPaused || player.id !== room.state.turnPlayerId) return;\n applyTurn(room, player, message);\n},\n```\n\nIf turns have deadlines, save the remaining time when pausing and calculate a new deadline on return. Scheduled handlers must check whether the turn is still paused or current. Decide separately in `onLeave` how to handle a permanent departure. Secret redelivery remains a client responsibility through `room.onConnection`; see [Hidden information](#hidden-information).\n\nThe room object provides:\n\n```js\nroom.id;\nroom.seed;\nroom.mode;\nroom.status;\nroom.tick;\nroom.tickRate;\nroom.result;\nroom.state;\nroom.players;\nroom.host;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.setRole(playerOrId, role);\nroom.setTeam(playerOrId, team);\nroom.end(result);\nroom.end(result, { rematch: true });\n\nawait room.save('round', value);\nawait room.load('round');\nawait room.shared.get('ship_abc');\nawait room.shared.set('ship_abc', value);\nawait room.shared.delete('ship_abc');\nawait room.shared.list('ship_');\nawait room.shared.increment('visits', 1);\nroom.schedule(milliseconds, 'methodName', payload);\n\nroom.daily.day;\nroom.daily.seed;\nroom.daily.expiresAt;\nroom.time.now();\n\nroom.voice.mode;\nroom.voice.setGain(listener, speaker, 0.25);\nroom.voice.setProximity(playerA, playerB, 0.5);\n```\n\nSet `room.state` in `onCreate`, then mutate it only in server callbacks. It must remain plain JSON and may be at most 512 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and closes the room unless rematch is enabled with `true` or an options object. See [Rematch in the same room](#rematch-in-the-same-room) for readiness, callback order, timer cancellation and the waiting deadline. Room saves use keys with the same format as player save keys and values up to 256 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes.\n\n### Recognized match results\n\n`room.end(result)` still accepts any JSON. The optional `MatchResult` type is exported by the contracts and by `@caisual/kit` and `@caisual/kit/server`:\n\n```ts\ntype MatchResult = {\n standings: Array<{ playerId: string; score?: number; rank?: number }>;\n winners?: string[];\n draw?: boolean;\n unit?: 'points' | 'time' | 'distance' | string;\n data?: JsonValue;\n} & Record<string, JsonValue>;\n```\n\nOrder `standings` from first place onward. Scores must be finite numbers; ranks are positive safe integers. The overlay uses the supplied order, displays player names and optional scores, and uses `rank` when present. `draw: true` takes precedence; otherwise `winners` identifies the winners. Without `winners`, the first row wins, together with rows sharing its explicit rank. Equal scores alone do not imply a draw. An explicit empty `winners` list means nobody won.\n\nThe end bar shows You won, You lost or Draw only for a participating player; spectators and players missing from the standings see Match finished. Outcome labels and the built-in units are translated in six languages. Custom units are shown as plain text; `time` and `distance` do not convert values or imply a measurement scale.\n\nReading is tolerant: unknown fields are ignored by the overlay, unknown or duplicate players are discarded, invalid scores and ranks are omitted, and winners must occur in the retained standings. With no usable standings the generic end bar remains. **`room.result` keeps the original JSON without normalization**, including `data` and any other game fields. Results are public to room members and spectators, so keep secrets elsewhere.\n\n```js\nroom.end({\n standings: [{ playerId: winner.id, score: 12, rank: 1 }, { playerId: other.id, score: 9, rank: 2 }],\n winners: [winner.id], unit: 'points', data: { rounds: 3 },\n}, { rematch: true });\n```\n\n### Hidden information\n\nEverything in `room.state` reaches every player and every spectator. Never store cards in hand, secret roles, fog of war, or any other private value there.\n\nKeep secrets in room saves through `room.save` and `room.load`, which are server-only, or in module-level variables in `server.js`, keyed by room when needed. Deliver a secret to one player with `room.send(player, { type: 'hand', cards })`. `onJoin` runs only on the player's first entry, not on reconnection, so the client requests its secrets for the current connection and every later reconnection:\n\n```js\nif (room.connection === 'connected') room.send({ type: 'hand?' });\nroom.onConnection((state) => {\n if (state === 'connected') room.send({ type: 'hand?' });\n});\n```\n\nThe server answers from `onMessage` with `room.send(player, { type: 'hand', cards })`. The three-second delay of `c.room.watch` does not protect secrets. It only stops a player from watching an opponent's live screen in another tab.\n\nThe browser can change its role or team only while the room is in `lobby`. During a match, the server decides when a player changes role or team with `room.setRole` and `room.setTeam`. Both methods accept a player object or id and immediately update `room.players` for every client.\n\n```js\nonMessage(room, player, message) {\n if (message?.swap === 'captain') {\n room.setRole(player, 'captain');\n }\n},\n```\n\n`room.daily.seed` is fixed at room creation and shared by rooms created for that game on the same UTC day. `room.seed` is fixed for one room and is identical on the server and clients, so rooms created on the same day can generate different maps.\n\n### WebAssembly on the server\n\nUse WebAssembly only to bring an existing engine, such as physics, pathfinding or a Rust simulation. For new game logic, start with JavaScript.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\nimport engine from './physics/add.wasm';\n\nconst engines = new WeakMap();\nfunction instance(room) {\n if (!engines.has(room)) engines.set(room, new WebAssembly.Instance(engine, {}));\n return engines.get(room);\n}\n\nexport default defineGame({\n tickRate: 0,\n onCreate(room) {\n room.state = { sum: instance(room).exports.add(19, 23) };\n },\n onMessage(room) {\n room.state.sum = instance(room).exports.add(room.state.sum, 1);\n },\n});\n```\n\nA default import such as `import engine from './physics/add.wasm'` returns an already compiled `WebAssembly.Module`. Instantiate it in `onCreate` or on first use with `new WebAssembly.Instance(engine, imports)`. Paths must start with `./`, stay inside the game folder and contain no `..` segments. Named, namespace and dynamic imports of `.wasm` are not supported. Shared memory and threads are not supported.\n\nThe room server accepts at most **8 `.wasm` files, 8,000,000 bytes per file and 16,000,000 bytes in total**, in addition to the 4,000,000-byte `server.js` limit. The CLI discovers them from the bundle and uploads them privately alongside the server, checking size and SHA-256. There is no manifest change; `requires.wasm` describes the browser client only. `caisual check` and publish enforce these limits, and `caisual dev` compiles the same files locally. Restart dev after changing a binary.\n\nBudget for compilation when the room wakes: a large binary makes resumption slower. The platform may reuse compiled code for the same game version, but reuse is not guaranteed. Instances and their memory are temporary, so recreate an instance on first use after a wake and restore any engine state from room JSON state or room saves. `onCreate` does not run again after a wake. Never put a module, instance or binary memory in `room.state`.\n\n### Shared game store\n\n`room.shared` is a server-only JSON key/value store shared by every room of the same game. It is useful when one room must leave data for another room, while `room.save` remains private to one room.\n\nThe following server leaves a ship when a room ends, then loads every previously left ship when another room is created. The room id suffix is used because shared-store keys follow the save-key format.\n\n```js\nexport default defineGame({\n tickRate: 0,\n\n async onCreate(room) {\n const keys = await room.shared.list('ship_');\n room.state = {\n ships: await Promise.all(keys.map((key) => room.shared.get(key))),\n };\n },\n\n async onEnd(room) {\n const roomSuffix = room.id.split('.')[1];\n await room.shared.set('ship_' + roomSuffix, {\n position: room.state.position,\n cargo: room.state.cargo,\n });\n },\n});\n```\n\nThe five methods are asynchronous:\n\n```js\nconst value = await room.shared.get(key); // JSON value, or null\nawait room.shared.set(key, value); // last writer wins\nawait room.shared.delete(key);\nconst keys = await room.shared.list(prefix); // sorted, up to 4096\nconst total = await room.shared.increment(key, 1); // atomic, defaults to 1\n```\n\nKeys contain 1 to 32 lowercase letters, numbers, underscores, or hyphens. Values may be up to 256 KB when serialized, and each game may keep up to 4096 keys. Each room may perform up to 120 shared-store operations per minute. `increment` treats a missing key as zero and rejects unless the existing value, amount, and result are safe integers.\n\nUse the store in `onCreate`, `onStart`, `onEnd`, `onMessage`, or a `schedule` handler. Do not call it on every tick: each call waits for a remote operation, and the CPU budget uses elapsed wall-clock time. Browser clients cannot access this store. Send only the data they need with `room.broadcast` or `room.send`.\n\nFailures reject with an `Error` carrying `store_invalid_key`, `store_too_large`, `store_full`, `store_not_integer`, `store_unavailable`, or `store_rate_limited` in `code`.\n\n`room.voice.setGain(listener, speaker, gain)` controls how much one listener hears one speaker. It is directional, limited to the range from 0 to 1, and rounded to two decimal places. For example, the following setup lets the captain hear everyone while each crew member hears only the captain:\n\n```js\nconst captain = room.players.find((player) => player.role === 'captain');\nconst crew = room.players.filter((player) => player.id !== captain.id);\n\nfor (const speaker of room.players) {\n room.voice.setGain(captain, speaker, 1);\n}\nfor (const listener of crew) {\n for (const speaker of room.players) {\n room.voice.setGain(listener, speaker, speaker.id === captain.id ? 1 : 0);\n }\n}\n```\n\n`room.voice.setProximity(a, b, gain)` is the symmetric shortcut for setting both directions. Both methods work in `room`, `team`, and `proximity` modes, and do nothing in `none`. In `team` mode, gains remain inside the team and cannot make a player hear another team.\n\nFor position-based audio, update the symmetric gain between players from server-owned positions:\n\n```js\nexport default defineGame({\n tickRate: 20,\n onTick(room) {\n for (const a of room.players) {\n for (const b of room.players) {\n if (a.id >= b.id) continue;\n const pa = room.state.positions[a.id];\n const pb = room.state.positions[b.id];\n const distance = Math.hypot(pa.x - pb.x, pa.y - pb.y);\n room.voice.setProximity(a, b, Math.max(0, 1 - distance / 20));\n }\n }\n },\n});\n```\n\n### Sleeping and cost\n\nPrefer `tickRate: 0` for turn based and party games. A room with a tick loop sleeps automatically after 30 seconds without player input or state changes and wakes on the next game message or player joining. Automatic ping and resync messages do not count as player input. A match with no player input for 10 minutes ends with `{ error: 'idle' }`. Timers set with `schedule` and the countdown keep working while the room sleeps.\n\n### CPU budget\n\nEvery `onTick` and `onMessage` call is measured. Twenty consecutive calls above 100 ms end the room with `{ error: 'cpu_budget' }`. If the average over 50 ticks is above 20 ms, the effective `tickRate` is halved, down to a minimum of 5, and clients receive an `error` message with code `tick_rate_reduced`. The optional `tickRate` field in `state` and `snapshot` protocol messages updates client `room.tickRate`; older clients ignore the added field. A frequency change sends a state diff even when its patch is empty.\n\n`room.tickRate` starts at the definition's `tickRate` and always reports the current effective frequency. `deltaSeconds` follows that frequency, so a fixed-step simulation must accumulate `deltaSeconds` instead of counting ticks. Measurement uses elapsed wall-clock time, so a slow `await` inside a callback also counts. `room.result` is `null` during a match, contains its result in `finished` or `ended` and inside `onEnd`, and returns to `null` before `onRestart`.\n\n### Persistent rooms\n\nSet `\"persistent\": true` in `caisual.json` for a room that must survive long breaks. It does not use the normal inactivity ending rule and does not end when every player disconnects. Players remain members until they call `room.leave()` or the server removes them with `room.kick()`. They can use the same room code to return while the game is already playing. The code remains valid while the room lives, and absent members remain in `room.players` with `connected: false`.\n\nA persistent room ends when the server calls `room.end(result)` without rematch, when its two-minute rematch wait expires, after 30 days without player input, entry, or a state change with `{ error: 'expired' }`, or after five minutes without any members. The standard overlay stores the resume reference itself. Only games without it need to store the client `room.code` with `c.save.set()` and offer Resume. A persistent room incurs cost only while it is awake.\n\n## Limits\n\n- 120 requests per minute per player. Beyond that the kit rejects with `rate_limited`; wait and retry.\n- Saves: 64 keys per player per game, 256 KB per value.\n- Room state: 512 KB of plain JSON.\n- Game messages: 64 KB each and 30/s per connection; excess messages are dropped with at most one `rate_limited` error per second. Service messages have a separate 30/s budget. More than 150 attempts/s in either budget for three consecutive one-second windows closes with 4008. Oversized frames close with 4009 `message_too_large`.\n- Spectators: 100 per room, with a configured delay from 0 to 30 seconds.\n- Voice supports audio only and one voice channel per room.\n- Voice control messages: 64 KB each and 30 operations per 10 seconds per connection. Voice signaling also uses the separate service-message budget; audio traffic does not consume either message budget.\n- Room save values: 256 KB each.\n- Shared game store: 256 KB per JSON value, 4096 keys per game, and 120 operations per minute per room.\n\n## Development\n\nRun `npx @caisual/cli dev` from the game folder, then open the printed portal URL. The preview supplies the normal handshake, so `c.connected` is `true` and the game receives a local guest identity. It also mounts the same standard overlay as the portal. `?lang=` chooses the game preference, resolved against the manifest; `c.player.uiLanguage` follows the overlay fallback. For example, `?lang=ja` gives `c.player.language === \"ja\"` when declared, with the overlay in English. Friends and parties are marked unavailable locally; everything else, including saves, daily data, invitations, and rooms, works on local data. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nUse `npx @caisual/cli dev --day 2026-09-04` to pin the UTC day used by client and room daily seeds. The flag accepts only a real date in `YYYY-MM-DD` format; without it, dev uses today's UTC date. Real clocks and room timers keep running normally. Saves, identities and rooms are shared across these dates. Existing rooms retain their creation context; new rooms follow the selected day. `expiresAt` follows the real clock even with `--day`. A changed flag takes effect after restarting dev and reloading the game.\n\nOpen the printed `/__caisual/players?n=4` URL for 1 to 8 independent guest frames, each including the game and standard overlay. Use the overlay to create a room and join its code in the other frames. Each frame has **Drop** (1 to 60 seconds, default 3) and **Spectate**, which opens a new guest watching that frame's room. Phone frames are 390 x 844; the desktop preset is 960 x 640. Add `&lang=it` to test Italian.\n\n`dev --latency 120 --jitter 40 --loss 2` delays room WebSocket messages in both directions for players and spectators. Latency and jitter are integer milliseconds from 0 to 60000; loss is a percentage from 0 to 100 and may be fractional. Jitter and loss require `--latency`, which may be zero. Jitter varies delay uniformly within plus/minus the supplied value, clamped at zero, and preserves message order. Loss discards whole application messages, including protocol messages, to exercise recovery; it is not a model of TCP packet retransmission. HTTP, matchmaking and audio are unaffected. Drop closes the guest's room sockets and prevents successful reconnects for the selected duration; the kit's retry schedule can make the return later. The spectator stream also retains its configured game delay.\n\nClient files are read on each request: reload the portal or frame after editing, or rebuild into `client/` first if using a bundler. There is no automatic browser reload. Restart dev after changing `caisual.json`, `server.js`, or any server import (including shared client physics). Rooms restore from `.caisual-dev/`; changing the shape of their state may require creating a fresh room. A busy port error suggests a command with a currently available port.\n\nEvery `init` variant generates Node test and optional Playwright browser scripts. Playwright is a development dependency of the generated game, never of the CLI. See [Local dev](/docs/local-development#testing-with-a-browser) for installation and the full browser workflow.\n\nWhen building the client with a bundler, remember that `client/` is served as-is. Configure Vite, esbuild, or another bundler to write into that folder, for example `vite build --outDir client`, and use relative paths such as `base: './'`.\n\nKeep loading the kit from the `<script type=\"module\">` shown at the beginning of this guide, using `/__caisual/kit/v1.js`, when publishing on Caisual. That URL exists only in `caisual dev` and in the published game.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. If it has no `server.js`, room creation rejects with `no_server` and the single-player APIs still work.\n\nTo run from any other static server, install `@caisual/kit` from npm and import it with a bundler as `import { caisual } from '@caisual/kit'`. In that build standalone mode applies: `c.connected` is `false`, saves use local storage, the daily seed is local, and room creation and joining reject with `offline`. The rest of the game logic does not need a different code path.\n\nAfter publishing with `npx @caisual/cli publish`, open the game from its caisual.com page: `c.connected` becomes `true` and every call goes to the portal.\n\n## Manifest\n\nDeclare `\"overlay\": { \"version\": 1 }` to get the standard overlay, with an optional `accent` colour. A standard game must declare at least one mode, and every mode needs `execution`, either `local` for a single-player run of exactly one player or `room` for a room backed by `server.js`. `label` names the mode in the standard menu and `instructions` adds one line under it. `roles[].label` names roles in the same UI. A mode with matchmaking adds `matchmaking.defaults`, one value for every field of its `key`, so the overlay can start a search on its own.\n\n```json\n{\n \"overlay\": { \"version\": 1, \"accent\": \"#397e83\" },\n \"players\": { \"min\": 2, \"max\": 4 },\n \"lobby\": true,\n \"modes\": [\n { \"id\": \"practice\", \"execution\": \"local\", \"label\": \"Practice\",\n \"instructions\": \"One run against the clock.\",\n \"players\": { \"min\": 1, \"max\": 1 }, \"lobby\": false },\n { \"id\": \"duel\", \"execution\": \"room\", \"label\": \"Online\",\n \"matchmaking\": { \"key\": [\"pool\"], \"defaults\": { \"pool\": \"v1\" }, \"timeoutMs\": 12000 } }\n ]\n}\n```\n\nA game without `overlay` keeps its historical flow and draws its own menus. Nothing else changes for it.\n\nNo manifest field is required for identity, saves, or the daily challenge. A mode may override only `players: { min, max }` and `lobby`; omitted fields inherit the root configuration, and `mode: null` uses the root values. Matchmaking thresholds and room admission use this same resolution. For rooms, set `players` to the supported range and use `lobby`, `persistent`, `spectators`, `roles`, `teams`, and `modes` to describe the setup and lifetime. Set `voice` to `room`, `team`, or `proximity` to enable the corresponding voice mode, or omit it for `none`. A single-player game can keep `players` at `{ \"min\": 1, \"max\": 1 }`, `lobby` at `false`, and omit `server.js`. See [publish.md](./publish.md#caisualjson) for every field and the publishing steps.\n\n## Required game images\n\nEnglish (`en`) is required in `languages`; three distinct files inside `client/` with no text inside are also required: cover 1536x1024 (3:2), card 1024x1024 and icon 1024x1024, each PNG, JPEG or WebP and at most 2 MB. See [Manifest](https://caisual.com/docs/manifest#required-game-images).\n";
1164
+ var kit_default = "# Caisual game kit\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version's worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nThe kit gives a published game a stable player identity, cloud saves, a daily challenge seed, multiplayer rooms with server-owned state, and the player's friends.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page and never draws anything: the game fills the window and draws its own menu, lobby, results and HUD.\n\n## Load the kit\n\nEvery published game can import the kit from its own origin, without a bundler and without an npm install:\n\n```html\n<script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n\n const c = await caisual.connect();\n console.log(c.player.name);\n</script>\n```\n\nGames built with a bundler can install the same module from npm:\n\n```sh\nnpm install @caisual/kit\n```\n\n```js\nimport { caisual } from '@caisual/kit';\n```\n\nBoth forms expose the same API. The module also sets `globalThis.caisual` for classic scripts that load it first.\n\nThe path `/__caisual/` is reserved on every game origin. Do not put game files under it.\n\n## Connect\n\n```js\nconst c = await caisual.connect();\n```\n\n`connect()` completes when the game is running inside caisual.com and has received its player identity, or after a short timeout when it is not. Calling it again returns the same promise.\n\n- `c.connected` is `true` inside caisual.com and `false` when the game runs on its own, for example from a local folder during development or when its files are copied elsewhere.\n- `c.player` is `{ id, name, guest, language }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or a stable `Guest-XXXX` name derived from the player id. The four-character suffix uses `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, excluding I, O, 0 and 1; it helps distinguish guests but is not a unique identifier. `guest` is `true` for players without an account. `language` selects game strings. On first sign-in to an account without a player identity, the browser guest is adopted with its existing id and saves. An account that already has a player identity uses that identity instead; guest data is not merged.\n- When not connected, `c.player` has `id: \"local\"`, `name: \"Guest\"`, `guest: true` and a `language`. If the host answered, its language information is kept; without a handshake, `language` is the normalized `navigator.language`, or `en`.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\n## Game language and strings\n\n`c.player.language` is the game's language, chosen by the site. Use it for game strings and formatting.\n\nThe kit resolves the player's explicit portal language choice, otherwise `navigator.languages` in order, against `manifest.languages`. For each preference it tries the exact tag and then its parent tags; if none of the preferences match, it uses the game's first declared language. The result is always a normalized declared tag. For example, `ja-JP` with `languages: [\"en\", \"ja\"]` selects `ja`. The site itself speaks English, Italian, Spanish, French, German, Portuguese and Japanese; a game may declare any language.\n\nA localized portal URL counts as a language choice. The language selector remembers explicit choices, including English; without either, the browser's ordered preferences apply. The handshake sends `language`, `languagePreferences` and `gameLanguages`. The kit resolves the game language, including when player services fail after a successful handshake.\n\nWithout a handshake, no declared language list is available: `language` is the raw preference from `navigator.language`, normalized as a BCP 47 tag, or `en` if invalid or unavailable. In `caisual dev`, `?lang=ja` selects `ja` when the manifest declares it. Without `?lang=`, dev uses `navigator.languages` in order.\n\nPut all game UI strings in flat JSON dictionaries named `client/i18n/<lang>.json`. Use canonical BCP 47 filenames, for example `en.json`, `it.json`, `pt.json`, `pt-BR.json`. Every value is a string; keys are identical across dictionaries. Text can contain named placeholders such as `{n}`.\n\nDeclare supported languages in `caisual.json`, always including `en`. English is required alongside the game's own languages; the first entry is the default and may be another language. This complete manifest supports a local game:\n\n```json\n{\n \"manifest\": 1,\n \"cover\": \"cover.png\",\n \"card\": \"card.png\",\n \"icon\": \"icon.png\",\n \"id\": \"three-lights\",\n \"name\": \"Three Lights\",\n \"platform\": \"both\",\n \"languages\": [\"en\", \"it\"],\n \"modes\": [{ \"id\": \"solo\" }]\n}\n```\n\n`client/i18n/en.json`:\n\n```json\n{ \"score\": \"Lights: {n} / 3\", \"light\": \"Light up\", \"done\": \"Complete\" }\n```\n\n`client/i18n/it.json`:\n\n```json\n{ \"score\": \"Luci: {n} / 3\", \"light\": \"Accendi\", \"done\": \"Tutte accese!\" }\n```\n\nLoad the dictionary once during setup. The returned function is synchronous and can be used in every draw call:\n\n```html\n<!doctype html>\n<html>\n<head><meta charset=\"utf-8\"><title>Three Lights</title></head>\n<body style=\"margin:0;min-height:100dvh;display:grid;place-content:center\">\n <p id=\"score\"></p>\n <button id=\"light\" disabled></button>\n <script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n const c = await caisual.connect();\n const t = await c.text();\n document.documentElement.lang = c.player.language;\n const score = document.querySelector('#score');\n const light = document.querySelector('#light');\n let n = 0;\n function draw() {\n score.textContent = n === 3 ? t('done') : t('score', { n });\n light.textContent = t('light');\n light.disabled = n === 3;\n }\n light.onclick = () => { n += 1; draw(); };\n draw();\n </script>\n</body>\n</html>\n```\n\n`c.text(): Promise<Text>` makes one request to the game's own origin, tied to the version currently open. Caisual and `caisual dev` read the matching files and merge them per key: `pt-BR` then `pt` then the manifest's default language. Longer tags fall back through their parent tags, such as `zh-Hant-TW`, `zh-Hant`, `zh`. The default file is tried once. If no file contains a key, `t` returns that key. Empty strings are valid translations.\n\nConcurrent and later `c.text()` calls share the same promise and translator for that connection. There are no dependencies, eager downloads, or per-call network requests. Missing files, invalid dictionaries and network failures do not prevent startup. If the Caisual text service is unavailable, for example on a plain static host outside Caisual, the translator returns keys; it does not probe other URLs. Use `caisual dev` to preview the complete convention.\n\n`t('score', { n: 3 })` replaces named placeholders with strings or numbers. An omitted placeholder stays unchanged, such as `{n}`. The result is plain text, with no HTML processing, plural rules or automatic translation. Set `textContent` or draw it on the canvas; do not insert it as HTML. A new document gets the host's current language and a fresh translator.\n\n`description` accepts a string or a language-to-text object, and resolves from the page language in the catalogue, profiles, invitations and metadata. `description` is an optional one-line subtitle, at most 80 characters after trimming whitespace in every language for new publications, for example `{ \"en\": \"Grow huge. Guard your tail. Devour light in a cosmic arena.\" }`. Each translation must be non-empty and use a key declared in `languages`; an absent field or a plain empty string omits the subtitle. Previously published versions with longer descriptions remain readable. `name` and `tags` keep their existing forms. See [manifest languages and validation](./publish.md#game-translations) for CLI checks and migration from `language`.\n\n## The game draws everything\n\nCaisual draws nothing over the game. The game gets the whole window and builds its own menu, lobby, invitation, result and \"play again\" from the calls below. There is no platform overlay, no menu, no pill, no reserved rectangles, no keyboard shortcut and no end-of-match screen. `env(safe-area-inset-*)` inside the game document is the real safe area.\n\n`caisual init` writes that minimal menu in `client/menu.js`: solo or online, create room, copy invite, join with a code, the player list with ready, start, and play again. It is about a hundred lines with no dependencies. Copy it, recolour it, or delete it and draw the same actions in your own style.\n\n```js\nconst c = await caisual.connect();\n\n// Solo: the state belongs to the game.\nstartLocalRun();\n\n// Online: the state belongs to the server.\nconst room = await c.room.create({ mode: 'duel' });\nroom.onPlayers((players) => drawLobby(players));\nroom.onStatus((status, result) => {\n if (status === 'playing') hideMenu();\n if (status === 'finished') drawResult(result); // then room.restart() for a rematch\n});\nroom.ready(true);\n```\n\nNothing has to be announced at startup: there is no handshake call, no session object and no capability flag. Draw your menu when the assets are ready. `c.connected` is `false` when the game runs outside caisual.com: rooms and friends are unavailable, everything else works on local data.\n\n### Full screen\n\nThe game fills the window. `html`, `body` and the game surface are 100% of the viewport: no maximum width, no header, no footer, no editorial frame, and no document scrolling at 1366x768 or 390x844, safe areas included. Only the HUD, the menu and compact controls sit over the scene.\n\nAim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile, counting only what shows or controls the game. A board with a fixed aspect ratio cannot always reach that: a square board on a 1366x768 window tops out near 56% before any HUD. That is the declared geometric exception: the board must then fill at least 90% of the largest rectangle that fits the area left free, and the HUD must have a stated ceiling, typically 48 to 64 pixels on desktop and about 160 pixels of controls on a phone.\n\n## Friends and party\n\n`c.crew` mirrors the player's Caisual friends inside the game, so the game can draw its own friends list and its own invitations. The platform owns the relationships; the game reads them and asks for the few actions it needs.\n\n```js\nc.crew.available; // false in a copy of the game running outside caisual.com\nc.crew.connected; // the friends channel is live\nc.crew.you; // { id, name } or null\nc.crew.friends; // [{ id, name, online, game: { slug, name, iconUrl } | null, room: { code } | null }]\nc.crew.party; // { id, leader, members: [...] } or null\nc.crew.invites; // [{ party, from: { id, name }, at }]\n\nconst stop = c.crew.onChange((crew) => drawFriends(crew));\n\nc.crew.createParty();\nc.crew.invite('player-id');\nc.crew.accept('party-id');\nc.crew.decline('party-id');\nc.crew.kick('player-id');\nc.crew.leave();\n\nconst room = await c.crew.join('player-id'); // enter the friend's room, in this game\nc.crew.follow('player-id'); // the site opens the friend's game, even another one\n```\n\n`onChange` repeats the current value immediately and returns a function that removes the listener. `join()` rejects with `no_room` when that player is not in a room, `other_game` when the friend is playing something else, which is what `follow()` is for, and `friend_not_found` for an unknown id. `follow()` hands navigation to the site, so the page changes. Outside caisual.com the lists stay empty, the actions do nothing, and `join()` rejects with `offline`.\n\nThe kit reports the player's current room to the site by itself, so friends can also join from the site with one click.\n\n## Daily challenge\n\n`c.daily` describes the day selected when the connection opened. `day`, `seed` and `expiresAt` stay fixed for that connection, including across UTC midnight. `expiresAt` is the next UTC midnight in milliseconds on the server clock.\n\n```js\nc.daily.day;\nc.daily.seed;\nc.daily.expiresAt;\nconst random = c.daily.rng();\nconst stop = c.daily.onChange(({ day, seed, expiresAt }) => {\n offerNextDailyRun({ day, seed, expiresAt });\n});\n```\n\n`onChange` reports a new `{ day, seed, expiresAt }` when the current UTC day changes. It returns an unsubscribe function and does not immediately replay the initial value. A suspended browser or a connection failure can delay the notification; the kit retries and reports the latest day when it can. The event does not mutate `c.daily` or reseed either generator. `rng()` always creates a fresh generator from the connection's original seed, and `random()` keeps advancing the original shared generator. Use the event's context explicitly for a new daily run, or open a new document. Repeated `connect()` calls return the same connection.\n\n`day` is a UTC date such as `\"2026-09-04\"`; `seed` is an unsigned 32-bit integer shared by all players of that game on that day. Both generators produce values in [0, 1). `c.time.now()` is in milliseconds aligned with the portal clock. Without a connection, daily data uses the local clock and hostname, with the same listener and generator behavior.\n\nOn the server, `room.daily` is `{ day, seed, expiresAt }`, fixed at **room creation**, persisted across sleep and rematches. Its seed matches a client connection opened for that game on the creation day. A client connected yesterday can therefore have a different `c.daily` from a room created today: send the room's daily context through game state when rendering its course. To switch a persistent or rematched room to a new daily course, create a new room.\n\n`caisual dev --day YYYY-MM-DD` fixes the simulated day and seed for new connections and rooms. Clocks stay real: `expiresAt` is the next **real** UTC midnight at connection or room creation, so comparing it with `c.time.now()` or `room.time.now()` remains valid even for a simulated date. Restored rooms keep their original daily context. Restart dev and reload to change the flag; create a new room for the newly selected day.\n\n## Saves\n\nEach player has up to 64 saves per game. A save is any JSON value up to 256 KB when serialized.\n\n```js\nawait c.save.set('slot1', { level: 3, coins: 120 }); // -> { key, bytes, updatedAt }\nconst data = await c.save.get('slot1'); // -> the value, or null\nawait c.save.remove('slot1');\nconst saves = await c.save.list(); // -> [{ key, bytes, updatedAt }]\n```\n\n- Keys use 1 to 32 characters: lowercase letters, digits, `_` or `-`, starting with a letter or digit.\n- `updatedAt` is a millisecond timestamp.\n- Saves are per player and per game. Another game cannot read them.\n- When not connected, saves go to the browser's local storage on the game origin.\n\nErrors reject the promise with an `Error` whose `code` is one of `invalid_request`, `not_found`, `save_limit`, `payload_too_large`, `rate_limited`, `invalid_ticket`, `internal_error`, or `offline`.\n\n## Device\n\n`c.device` contains the browser and device report collected while `connect()` runs:\n\n```ts\ninterface DeviceReport {\n webgl2: boolean;\n webgpu: boolean;\n wasm: boolean;\n threads: boolean;\n isolated: boolean;\n gpu: 'hardware' | 'software' | 'none';\n memoryMb: number | null;\n cores: number | null;\n mobile: boolean;\n tier: 'low' | 'mid' | 'high';\n}\n```\n\n`device.isolated` measures the browser's actual `crossOriginIsolated` state. Games embedded in the portal report `false`; shared memory and threaded WebAssembly are unavailable there. This runtime probe does not enable isolation.\n\nUse capability fields to choose a renderer, then use `tier` to reduce pixel ratio and quality on smaller devices:\n\n```js\nconst renderer = c.device.webgpu\n ? createWebGpuRenderer()\n : createWebGl2Renderer();\n\nconst pixelRatio = c.device.tier === 'high' ? devicePixelRatio : 1;\nconst quality = c.device.tier === 'low' ? 'low' : 'high';\nrenderer.configure({ pixelRatio, quality });\n```\n\nThe probe takes at most 1.5 seconds. `memoryMb` and `cores` are `null` when the browser does not expose them. The report stays in the browser and is not saved or sent to Caisual.\n\n### Two front ends, one game\n\nKeep one `client/index.html`, one game ID and one server. With `platform: \"both\"`, choose separate front ends in that entry without navigating or adding another iframe:\n```js\nimport { caisual } from '/__caisual/kit/v1.js';\nconst c = await caisual.connect();\nlet preference = null;\ntry { preference = localStorage.getItem('layout'); } catch {}\nconst touch = preference === 'touch' || (preference !== 'desktop' && (c.device.mobile || matchMedia('(pointer: coarse)').matches));\nconst screen = touch ? await import('./touch/main.js') : await import('./desktop/main.js');\nscreen.mount({ c, root: document.querySelector('#app') });\n```\nOffer a manual layout choice, persist it when storage is available, and keep rules and room connections shared. Both front ends use relative asset paths inside `client/`.\n\n## Game version changes\n\nNew games use the current version. Existing rooms retain their version for their whole life, including invitations, typed codes and friends. Matchmaking never mixes versions; an accepted reservation can finish on its original version. Saves remain per game, with data compatibility handled by the creator. See [Versions and rollback](./publish.md#versions-and-rollback).\n\nA room create or match operation rejects with `version_outdated` and `currentVersion` when the loaded game is no longer current. A join or reconnect rejects with `version_mismatch` and `roomVersion` when the room uses another version.\n\nSubscribe with `c.room.onError(listener)`, which returns an unsubscribe function. The error has `code`, `message`, and the applicable version number. The operation also rejects with that error. `c.room.reload()` reloads the page on the current game after `version_outdated`, or on the last mismatched room after `version_mismatch`. Show a button calling it after either error: it is the only way out of both.\n\n`caisual dev` always uses game version 1 and does not simulate version changes.\n\n## Rooms\n\nA room brings players into the same running game. Single player runs in the browser and never touches the server; a room exists only for two or more players. Creating and joining require a published `server.js` and a mode with `players.max > 1`. A local mode rejects room operations with `mode_local`.\n\nAn optional [MatchResult](#recognized-match-results) in `room.end` gives the game a ready shape for winners and standings, while `room.result` keeps the original JSON.\n\n```js\nconst c = await caisual.connect();\n\nc.room.invited; // invitation code from the game page, or null\n\nconst room = await c.room.create({ mode: null });\n// Or join the invitation that opened the game:\nconst invitedRoom = await c.room.join();\n// Or enter a code supplied by the player:\nconst codedRoom = await c.room.join('ABC234');\n\nroom.code;\nroom.seed; // unsigned 32-bit integer fixed for this room\nroom.tickRate;\nroom.latency;\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nA room you create always waits in its lobby, regardless of the mode\u2019s `lobby` flag.\nOnly matchmaking can drop players into a running match, when the mode declares `lobby: false`.\nRead `room.metadata.configuration.lobby` for the room\u2019s effective setting; during play, a created room only admits returning members.\n\nPass a mode id from the manifest to `create({ mode })`, or `null` to use the root configuration. Optional `players` on that mode replaces the root range. The mode\u2019s `lobby` override applies to matchmaking; joining keeps the effective configuration of the room being joined. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. `invite()` returns the code and the link to copy.\n\n### Friends in a room\n\nThe kit reports the player's current room to the site by itself, so friends can see where the player is and join. See [Friends and party](#friends-and-party) for the data and the calls.\n\n### Matchmaking\n\nUse `c.room.match()` to find players who requested the same mode and key. The key must contain exactly the fields declared by that mode's `matchmaking.key` in `caisual.json`.\n\n```js\nconst room = await c.room.match({\n mode: 'daily',\n key: { day: c.daily.day, stage: 3 },\n onWaiting({ players, min, max }) {\n showQueue(`${players}/${max} players, ${min} required`);\n },\n});\n```\n\nMatchmaking uses the selected mode's resolved `players` and `lobby`, and that mode's `matchmaking.timeoutMs`. A room opens as soon as the queue reaches the resolved `players.max`. When `matchmaking.timeoutMs` expires, it also opens if at least `players.min` players are waiting. Otherwise the promise rejects with `no_match`, and the game should offer the player another option. A new search first tries to fill a matching room that is already open and can still accept players.\n\nPass an `AbortSignal` as `signal` to let the player cancel a search. Cancellation rejects with `cancelled`. Declare `matchmaking.defaults` in the mode to give the game a complete key to start a search with.\n\nRoom status is one of:\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: everyone present is ready and play begins at the announced server time.\n- `playing`: the game server is running the match.\n- `finished`: the match is over and the room is waiting for a rematch, with sockets open and `room.result` available.\n- `ended`: the match or connection has ended. `room.result` contains the result last reported by the room. A definitive connection closure uses `{ closed: 4003 }` when the player was kicked, `{ closed: 4004 }` when the room ended, `{ closed: 4005 }` when the published version closed, or `{ closed: 4006 }` when the same player opened the room in another tab.\n\nThe current lobby data is available directly:\n\n```js\nroom.players; // [{ id, name, guest, role, team, ready, connected }]\nroom.you; // this player's id\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n```\n\n`ready`, role and team are the lobby actions: draw the roster from `room.players` and call them from your own lobby. **Nobody hosts and nobody presses start.** As soon as every connected player is ready and the player, role and team minimums from the manifest are met, the room begins a three-second countdown on its own. If someone joins during the countdown, which they may, or takes back their readiness, or a minimum stops being met, the room returns to the lobby. A role or team change in the lobby clears that player's ready state. Every room member is a player. If all declared roles are full, entry fails with `room_full` before adding a member, even below `players.max`. Roles must be declared in the manifest; assigning an undeclared role fails with `invalid_role`.\n\n### Rematch in the same room\n\nThe server opts in per match with `room.end(result, { rematch: true })`. The room becomes `finished`, keeps its code, members, state and open connections, and exposes the result through `room.result` and `onStatus('finished', result, at)`. Voice stays connected. `room.end(result)` or `{ rematch: false }` still ends the room permanently with status `ended` and close code 4004.\n\nWith `rematch: true` in a multiplayer room, each connected player calls `room.restart()` once to accept the rematch. In `finished`, `room.players[].ready` means rematch readiness. The rematch starts by itself as soon as every connected player has accepted and the mode's `players.min` is met, including when a departure leaves that condition satisfied. Repeated calls do nothing. Calling outside `finished` fails with `rematch_unavailable`.\n\nDraw \"Play again\" with the readiness count. No member is removed for declining.\n\nAt the start, the kit clears the result to `null` and all readiness flags, then calls optional `onRestart(room)` with status `lobby` when the room has a lobby, or `playing` otherwise. **The kit does not reset `room.state`.** Reset match data in `onRestart`, keeping series scores or other data as needed. With a lobby, players choose their setup and get ready again before the normal countdown and `onStart`. Without a lobby, `onStart` follows `onRestart` immediately. Clients receive the new state and an `onStatus` transition with a null result. The room identity, seed and tick sequence are retained, so the same room object stays valid. Listen to `room.onState` and `room.onStatus`.\n\n### Fast rematches\n\nThe existing `rematch: true` flow above is unchanged for multiplayer rooms. To shorten it, use:\n\n```js\nroom.end(result, { rematch: { keepSetup: true } });\n```\n\n`keepSetup` defaults to `false`. It restores the previous readiness flags, keeps roles and teams, and skips the lobby: `onRestart` runs with status `countdown`, followed by the usual three-second countdown and `onStart`. The result clears before `onRestart`. Even a mode without a lobby gets this countdown. Readiness during `finished` is still consent for the next match, separate from the previous setup. Player, role and team minimums are rechecked during the countdown; if they fail, the room returns to the lobby so the setup can be repaired.\n\nMembers who have not accepted remain in the room and join the next phase; they are not removed. Without `keepSetup`, the next phase is the usual lobby or immediate play.\n\n\nThe waiting rules are:\n\n- All pending `room.schedule` handlers are cancelled when the match finishes, including handlers already due in the same batch. Scheduling during `finished` has no effect. Schedule new work in `onRestart` or `onStart`. Tick callbacks stop immediately; game input during the wait is discarded, and queued continuous input is cleared on the client.\n- `onEnd` runs once for the completed match, with status `finished` and its result. A subsequent timeout only closes the room and does not call `onEnd` again.\n- Disconnecting clears that member's readiness. Disconnected players do not count toward readiness or the minimum, so a departure can be what starts the rematch. The usual 60-second reconnection grace applies; persistent members keep their seats after it. Rejoining requires a new readiness call. Connection and departure callbacks continue during the wait.\n- New members may join by invitation during the wait, up to the resolved `players.max`, and start unready. A lobby mode therefore reopens admission while `finished`; without a lobby, admission continues as during play. Disconnected members still occupy seats until removed. Roles and teams retain their existing capacity rules.\n- The room closes with 4004 exactly two minutes after entering `finished` if no restart is confirmed, retaining the last result. Readiness, joins and pings do not extend this deadline. It also applies to persistent rooms and survives sleep or restoration; it does not depend on active ticks.\n\n`finished` is a status, not a terminal connection state: the sockets stay open. Handle it explicitly in the game's status listener, and draw the result and the rematch action there.\n\nThe server owns room state. Read it and react to updates, but do not assign to it or mutate nested values from the browser:\n\n```js\ndraw(room.state);\n\nconst stopState = room.onState((state, tick, serverTime) => {\n draw(state);\n});\n\nconst stopPlayers = room.onPlayers((players) => updateLobby(players));\nconst stopStatus = room.onStatus((status, result, at) => showStatus(status, result, at));\n\nstopState();\nstopPlayers();\nstopStatus();\n```\n\n`room.tick` identifies the latest state. The kit applies structural updates in order for both tick-based and event-only servers. Full state is sent on entry, reconnection or resync when an update does not match the current tick; normal updates, including every hundredth tick, remain diffs. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\n`room.tickRate` is the current effective server frequency, including reductions caused by the CPU budget; zero means event-only. Updates arrive with state diffs and snapshots, including an empty diff when only the frequency changes. `room.latency` is the smoothed round-trip time in milliseconds, or `null` before the first pong and after a dropped connection until the next pong. Each pong uses 20% of the new RTT and 80% of the previous estimate, with the first sample used directly. Read the property when drawing network status; there is no `onLatency` listener.\n\nSend JSON input to `onMessage` in the server definition, and receive JSON sent or broadcast by the server:\n\n```js\nroom.send({ type: 'fire', target: 3 });\n\nconst stopMessages = room.onMessage((message) => {\n showEvent(message);\n});\n```\n\nThe kit numbers outgoing inputs in increasing order. It automatically reconnects temporary failures with delays of 1, 2, 4, then 8 seconds, for at most the room's 60-second grace period. Each attempt gets a fresh room token. A successful reconnect replaces local state with a full server state. `room.send` calls while reconnecting throw an error with `code: \"offline\"`.\n\nUse `room.input(value)` for continuous controls, including calls from every animation frame:\n\n```js\nroom.input({ type: 'move', x: axisX, y: axisY });\nroom.onError(({ code }) => {\n if (code === 'rate_limited') showInputWarning();\n});\n```\n\n`input` copies and keeps only the latest JSON value in one slot. It coalesces updates and sends at most 30 times per second, or at the effective `room.tickRate` when that is lower and positive. With `tickRate: 0`, it still sends at most 30/s. It also waits for budget used by `send`. Values with the same JSON serialization are not resent on the same connection. Combine independent controls into that one value; there is no channel option. On the server it is an ordinary message passed unchanged to `onMessage`, exactly like `send`, with no extra envelope.\n\nDuring reconnection, `input` accepts updates without throwing `offline`. After the new welcome it sends only the latest value, even if it was sent on the previous connection. It never replays intermediate values or old commands. Use `send` for individual actions such as firing or confirming a turn; `send` still throws `offline` during reconnection. Invalid JSON input can throw `invalid_request`. Input stops after leaving, disconnecting intentionally or ending the room.\n\nGame messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`, reported through `room.onError`; malformed frames use 4009 `bad_message`. Neither closure is retried automatically.\n\nCall `room.leave()` for an intentional departure. The kit does not reconnect after leaving, being kicked, the room ending, the published version closing, or the same player opening the room in another tab.\n\n`room.disconnect()` is the other departure: it stops the transport, the retries and voice without sending a leave, so the server keeps the seat under its own persistence and grace rules. It is not reversible on the same object; returning means entering again from the code, which is how a \"leave for now\" action works.\n\nA room also exposes `room.mode`, `room.countdownAt`, `room.connection`, `room.metadata`, and the `onMetadata` and `onConnection` listeners. `connection` is one of `connecting`, `connected`, `reconnecting`, `disconnected`, `ended`, `closed`, or `replaced`, where `replaced` means the same player opened the room in another tab. These listeners do not repeat the current value: read the getter first.\n\n`room.onError(listener)` reports technical protocol errors of the room as `{ code, message }`; it is not the place where a game reads its own result.\n\n`await room.requestRole('scout')` asks the server for a role change during a match. It works only while the room is playing, only for a role declared in the manifest, and only when `server.js` defines `onRoleRequest(room, player, role)`; the server approves by calling `room.setRole`. Without that callback nothing changes. It is not a shortcut for changing roles from the browser.\n\nRoom creation, joining, and matchmaking reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `mode_local`, `no_server`, `no_match`, `cancelled`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `mode_local` means \"Single-player modes run in the browser and have no room.\" `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, `create`, `join`, and `match` reject with `offline`.\n\n- `invalid_role`: a requested role id is malformed or is not declared in the manifest. Request a declared role id.\n- `role_change_unavailable`: the room is disconnected, is not playing, or `server.js` has no `onRoleRequest`. Wait for a connected playing state and provide that callback before offering the action.\n- `role_change_refused`: `onRoleRequest` returned without assigning the requested role. Leave the current role in place, or have the server approve with `room.setRole`.\n- `version_closed`: the room connection ended because its published version closed. Reopen the current game version and enter a current room.\n\nEvery listener call on a room returns a function that removes that listener: `onState`, `onPlayers`, `onStatus`, `onMessage`, `onMetadata`, `onConnection`, and `onError`.\n\n### Responsive action games\n\n1. Start with `npx @caisual/cli init --arcade my-arena`, a complete English/Italian canvas game with shared rules and tests.\n2. Accumulate `deltaSeconds` on the server and advance shared physics at a fixed 1/60 second step.\n3. Keep positions, collision or range checks, cooldowns and scores authoritative in `server.js`.\n4. Use `room.input()` for continuous controls and `room.send()` for discrete actions such as the starter's pulse.\n5. Number commands in the game and publish each player's last **applied** `ack` in `room.state`; transport sequence numbers are separate.\n6. Because `input()` coalesces values, send a bounded batch of unacknowledged commands; deduplicate on the server and consume at most one per simulation step.\n7. Predict your own entity with the shared step, replace it with each authoritative snapshot, then replay only commands after `ack`; ease corrections in the drawing only.\n8. Buffer remote samples by the `onState` timestamp and render behind `room.serverTime()`, accounting for RTT in `room.latency` and the effective `room.tickRate`.\n9. Clear pending controls on reconnection or a new round; keep the HUD inside the safe areas, and end with `standings` plus a `keepSetup` rematch.\n10. Run the generated browser fixture and `/__caisual/players?n=2` with `dev --latency 120 --jitter 40 --loss 2`; see [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n## Voice\n\nEvery room has a `room.voice` object. Voice is disabled by default and is enabled with the manifest's `voice` field.\n\nThe game draws the voice controls, and must offer an explicit one: `join()` has to be called from a click or another user gesture so the browser can start audio and, when publishing, request microphone permission.\n\n```js\nconst micButton = document.querySelector('#mic');\nconst voiceList = document.querySelector('#voice-list');\n\nfunction renderVoice(peers = room.voice.peers) {\n voiceList.replaceChildren(...peers.map((peer) => {\n const item = document.createElement('li');\n const player = room.players.find((entry) => entry.id === peer.id);\n item.textContent = `${player?.name ?? peer.id}: ${\n peer.speaking ? 'speaking' : peer.muted ? 'muted' : 'quiet'\n }`;\n return item;\n }));\n micButton.textContent = room.voice.state === 'off'\n ? 'Join voice'\n : !room.voice.mic ? 'Listening' : room.voice.muted ? 'Unmute' : 'Mute';\n}\n\nmicButton.addEventListener('click', async () => {\n if (room.voice.state === 'off') await room.voice.join();\n else if (room.voice.mic) room.voice.mute(!room.voice.muted);\n renderVoice();\n});\n\nroom.voice.onPeers(renderVoice);\nroom.voice.onState(() => renderVoice());\nrenderVoice();\n```\n\n`room.voice.mode` is `none`, `room`, `team`, or `proximity`. In `room` mode, every participant in voice can hear every other participant. In `team` mode, players hear only their team. In `proximity` mode, the room server controls the gain between participants. Call `room.voice.join({ mic: false })` to listen without opening or publishing a microphone.\n\nThe room server authorizes every voice track by team and gain. Listening that is no longer allowed is refused or closed.\n\n`room.voice.state` is `off`, `joining`, `on`, or `reconnecting`. `room.voice.mic` is `true` while the local player is publishing. `room.voice.muted` and `room.voice.speaking` describe the local microphone. `room.voice.peers` contains the other voice participants as `{ id, mic, muted, speaking, volume, gain }`. A listening participant has `mic: false`, `muted: true`, and `speaking: false`. `volume` is the local setting and `gain` is the value from the room server. Use `room.voice.setVolume(playerId, volume)` with a value from 0 to 1 to change only local playback.\n\n`room.voice.onPeers(listener)` runs when participants, microphone state, mute state, speaking state, volume, or gain changes. `room.voice.onState(listener)` reports connection state changes. Both return a function that removes the listener.\n\nCall `room.voice.leave()` to stop publishing or listening without leaving the room. `room.voice.mute()` requires an active published microphone and otherwise throws `not_publishing`. `room.leave()` and the end of the room stop voice automatically.\n\n`join()` rejects with an `Error` carrying one of these stable codes: `voice_disabled`, `permission_denied`, `unsupported`, `offline`, or `voice_error`. Voice can reconnect after a temporary room or media connection failure. The state becomes `reconnecting` while the kit retries.\n\n## Server\n\nPut `server.js` next to `caisual.json` and publish it with the game. See [publish.md](./publish.md#multiplayer-server) for the file rules, validation, and publishing flow.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\n\nexport default defineGame({\n tickRate: 20, // required, an integer from 0 to 60; 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onConnection(room, player, connected) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onRoleRequest(room, player, role) {}, // approve with room.setRole\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n onRestart(room) {},\n});\n```\n\n`tickRate` is the only required field: `defineGame` throws a `TypeError` when it is missing or is not an integer from 0 to 60. All callbacks are optional. A player is `{ id, name, guest, role, team, connected }`.\n\n### Callback order\n\n- `onCreate` runs once when the room is first created, before any player joins.\n- `onJoin` runs when a player first enters the room, not when that same member reconnects. Without a lobby, the first player's `onJoin` is followed by `onStart`.\n- `onStart` runs when the room changes to `playing`. Without a lobby this is the first player entry. With a lobby it is after everyone present is ready, the three-second countdown finishes, and the room still meets its minimums.\n- `onTick` runs for each active game tick when `tickRate` is greater than zero. `onMessage` runs for accepted client game messages, and `onRoleRequest` runs for an in-match role request when that callback exists. These events are processed serially, so their relative order is the order in which the room processes them.\n- `onConnection(room, player, connected)` runs with `false` when an existing member loses their connection and with `true` when that disconnected member returns. Both `player.connected` and `room.players` are already updated. It does not run for the first entry, a socket replacement while the member is still connected, or a permanent removal. Restoring a room reconciles actual connections: members saved as connected whose sockets are gone receive `false`, and their later return receives `true`. Surviving sockets receive no extra callback.\n- `onLeave` runs only when a player is removed with reason `left`, `timeout`, or `kicked`. A dropped connection calls `onConnection` during the grace period and does not call `onLeave`.\n- `onEnd` runs after the callback that requested `room.end`, with the final result and status `ended` or `finished`. Automatic room endings also use it, except closure of an already `finished` match, which must not run it twice.\n- `onRestart` runs when a rematch starts, after clearing the result and selecting the next status. Readiness is reset by default or restored with `keepSetup`. The `keepSetup` and solo matchmaking rules above override the default next status. With a lobby it prepares `lobby`; without one it prepares `playing` and is immediately followed by `onStart`. It is optional; `room.state` is preserved unless the game changes it.\n\nThere is no `onResume` callback. A sleeping room restores its saved state without calling one. When a scheduled time arrives, the room invokes the method named by `room.schedule`.\n\nFor a turn-based game, store the active player's id and pause that turn when the player disconnects. This also works with `tickRate: 0`, because callback state changes are published immediately:\n\n```js\nonConnection(room, player, connected) {\n if (room.state.turnPlayerId === player.id) {\n room.state.turnPaused = !connected;\n }\n},\nonMessage(room, player, message) {\n if (room.state.turnPaused || player.id !== room.state.turnPlayerId) return;\n applyTurn(room, player, message);\n},\n```\n\nIf turns have deadlines, save the remaining time when pausing and calculate a new deadline on return. Scheduled handlers must check whether the turn is still paused or current. Decide separately in `onLeave` how to handle a permanent departure. Secret redelivery remains a client responsibility through `room.onConnection`; see [Hidden information](#hidden-information).\n\nThe room object provides:\n\n```js\nroom.id;\nroom.seed;\nroom.mode;\nroom.status;\nroom.tick;\nroom.tickRate;\nroom.result;\nroom.state;\nroom.players;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.setRole(playerOrId, role);\nroom.setTeam(playerOrId, team);\nroom.end(result);\nroom.end(result, { rematch: true });\n\nawait room.save('round', value);\nawait room.load('round');\nroom.schedule(milliseconds, 'methodName', payload);\n\nroom.daily.day;\nroom.daily.seed;\nroom.daily.expiresAt;\nroom.time.now();\n\nroom.voice.mode;\nroom.voice.setGain(listener, speaker, 0.25);\nroom.voice.setProximity(playerA, playerB, 0.5);\n```\n\nSet `room.state` in `onCreate`, then mutate it only in server callbacks. It must remain plain JSON and may be at most 512 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and closes the room unless rematch is enabled with `true` or an options object. See [Rematch in the same room](#rematch-in-the-same-room) for readiness, callback order, timer cancellation and the waiting deadline. Room saves use keys with the same format as player save keys and values up to 256 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes.\n\n### Recognized match results\n\n`room.end(result)` still accepts any JSON. The optional `MatchResult` type is exported by the contracts and by `@caisual/kit` and `@caisual/kit/server`:\n\n```ts\ntype MatchResult = {\n standings: Array<{ playerId: string; score?: number; rank?: number }>;\n winners?: string[];\n draw?: boolean;\n unit?: 'points' | 'time' | 'distance' | string;\n data?: JsonValue;\n} & Record<string, JsonValue>;\n```\n\nOrder `standings` from first place onward. Scores must be finite numbers; ranks are positive safe integers. `draw: true` takes precedence; otherwise `winners` identifies the winners. Without `winners`, the first row wins, together with rows sharing its explicit rank. Equal scores alone do not imply a draw. An explicit empty `winners` list means nobody won.\n\nThis shape is a convention, not a screen: the game reads `room.result` and draws its own result. `time` and `distance` in `unit` do not convert values or imply a measurement scale. **`room.result` keeps the original JSON without normalization**, including `data` and any other game fields. Results are public to every room member, so keep secrets elsewhere.\n\n```js\nroom.end({\n standings: [{ playerId: winner.id, score: 12, rank: 1 }, { playerId: other.id, score: 9, rank: 2 }],\n winners: [winner.id], unit: 'points', data: { rounds: 3 },\n}, { rematch: true });\n```\n\n### Hidden information\n\nEverything in `room.state` reaches every player in the room. Never store cards in hand, secret roles, fog of war, or any other private value there.\n\nKeep secrets in room saves through `room.save` and `room.load`, which are server-only, or in module-level variables in `server.js`, keyed by room when needed. Deliver a secret to one player with `room.send(player, { type: 'hand', cards })`. `onJoin` runs only on the player's first entry, not on reconnection, so the client requests its secrets for the current connection and every later reconnection:\n\n```js\nif (room.connection === 'connected') room.send({ type: 'hand?' });\nroom.onConnection((state) => {\n if (state === 'connected') room.send({ type: 'hand?' });\n});\n```\n\nThe server answers from `onMessage` with `room.send(player, { type: 'hand', cards })`.\n\nThe browser can change its role or team only while the room is in `lobby`. During a match, the server decides when a player changes role or team with `room.setRole` and `room.setTeam`. Both methods accept a player object or id and immediately update `room.players` for every client.\n\n```js\nonMessage(room, player, message) {\n if (message?.swap === 'captain') {\n room.setRole(player, 'captain');\n }\n},\n```\n\n`room.daily.seed` is fixed at room creation and shared by rooms created for that game on the same UTC day. `room.seed` is fixed for one room and is identical on the server and clients, so rooms created on the same day can generate different maps.\n\n### WebAssembly on the server\n\nUse WebAssembly only to bring an existing engine, such as physics, pathfinding or a Rust simulation. For new game logic, start with JavaScript.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\nimport engine from './physics/add.wasm';\n\nconst engines = new WeakMap();\nfunction instance(room) {\n if (!engines.has(room)) engines.set(room, new WebAssembly.Instance(engine, {}));\n return engines.get(room);\n}\n\nexport default defineGame({\n tickRate: 0,\n onCreate(room) {\n room.state = { sum: instance(room).exports.add(19, 23) };\n },\n onMessage(room) {\n room.state.sum = instance(room).exports.add(room.state.sum, 1);\n },\n});\n```\n\nA default import such as `import engine from './physics/add.wasm'` returns an already compiled `WebAssembly.Module`. Instantiate it in `onCreate` or on first use with `new WebAssembly.Instance(engine, imports)`. Paths must start with `./`, stay inside the game folder and contain no `..` segments. Named, namespace and dynamic imports of `.wasm` are not supported. Shared memory and threads are not supported.\n\nThe room server accepts at most **8 `.wasm` files, 8,000,000 bytes per file and 16,000,000 bytes in total**, in addition to the 4,000,000-byte `server.js` limit. The CLI discovers them from the bundle and uploads them privately alongside the server, checking size and SHA-256. There is no manifest change; `requires.wasm` describes the browser client only. `caisual check` and publish enforce these limits, and `caisual dev` compiles the same files locally. Restart dev after changing a binary.\n\nBudget for compilation when the room wakes: a large binary makes resumption slower. The platform may reuse compiled code for the same game version, but reuse is not guaranteed. Instances and their memory are temporary, so recreate an instance on first use after a wake and restore any engine state from room JSON state or room saves. `onCreate` does not run again after a wake. Never put a module, instance or binary memory in `room.state`.\n\n`room.voice.setGain(listener, speaker, gain)` controls how much one listener hears one speaker. It is directional, limited to the range from 0 to 1, and rounded to two decimal places. For example, the following setup lets the captain hear everyone while each crew member hears only the captain:\n\n```js\nconst captain = room.players.find((player) => player.role === 'captain');\nconst crew = room.players.filter((player) => player.id !== captain.id);\n\nfor (const speaker of room.players) {\n room.voice.setGain(captain, speaker, 1);\n}\nfor (const listener of crew) {\n for (const speaker of room.players) {\n room.voice.setGain(listener, speaker, speaker.id === captain.id ? 1 : 0);\n }\n}\n```\n\n`room.voice.setProximity(a, b, gain)` is the symmetric shortcut for setting both directions. Both methods work in `room`, `team`, and `proximity` modes, and do nothing in `none`. In `team` mode, gains remain inside the team and cannot make a player hear another team.\n\nFor position-based audio, update the symmetric gain between players from server-owned positions:\n\n```js\nexport default defineGame({\n tickRate: 20,\n onTick(room) {\n for (const a of room.players) {\n for (const b of room.players) {\n if (a.id >= b.id) continue;\n const pa = room.state.positions[a.id];\n const pb = room.state.positions[b.id];\n const distance = Math.hypot(pa.x - pb.x, pa.y - pb.y);\n room.voice.setProximity(a, b, Math.max(0, 1 - distance / 20));\n }\n }\n },\n});\n```\n\n### Sleeping and cost\n\nPrefer `tickRate: 0` for turn based and party games. A room with a tick loop sleeps automatically after 30 seconds without player input or state changes and wakes on the next game message or player joining. Automatic ping and resync messages do not count as player input. A match with no player input for 10 minutes ends with `{ error: 'idle' }`. Timers set with `schedule` and the countdown keep working while the room sleeps.\n\n### CPU budget\n\nEvery `onTick` and `onMessage` call is measured. Twenty consecutive calls above 100 ms end the room with `{ error: 'cpu_budget' }`. If the average over 50 ticks is above 20 ms, the effective `tickRate` is halved, down to a minimum of 5, and clients receive an `error` message with code `tick_rate_reduced`. The optional `tickRate` field in `state` and `snapshot` protocol messages updates client `room.tickRate`; older clients ignore the added field. A frequency change sends a state diff even when its patch is empty.\n\n`room.tickRate` starts at the definition's `tickRate` and always reports the current effective frequency. `deltaSeconds` follows that frequency, so a fixed-step simulation must accumulate `deltaSeconds` instead of counting ticks. Measurement uses elapsed wall-clock time, so a slow `await` inside a callback also counts. `room.result` is `null` during a match, contains its result in `finished` or `ended` and inside `onEnd`, and returns to `null` before `onRestart`.\n\n### Persistent rooms\n\nSet `\"persistent\": true` in `caisual.json` for a room that must survive long breaks. It does not use the normal inactivity ending rule and does not end when every player disconnects. Players remain members until they call `room.leave()` or the server removes them with `room.kick()`. They can use the same room code to return while the game is already playing. The code remains valid while the room lives, and absent members remain in `room.players` with `connected: false`.\n\nA persistent room ends when the server calls `room.end(result)` without rematch, when its two-minute rematch wait expires, after 30 days without player input, entry, or a state change with `{ error: 'expired' }`, or after five minutes without any members. To offer a \"come back\" action, store `room.code` with `c.save.set()` and call `c.room.join(code)` later. A persistent room incurs cost only while it is awake.\n\n## Limits\n\n- 120 requests per minute per player. Beyond that the kit rejects with `rate_limited`; wait and retry.\n- Saves: 64 keys per player per game, 256 KB per value.\n- Room state: 512 KB of plain JSON.\n- Game messages: 64 KB each and 30/s per connection; excess messages are dropped with at most one `rate_limited` error per second. Service messages have a separate 30/s budget. More than 150 attempts/s in either budget for three consecutive one-second windows closes with 4008. Oversized frames close with 4009 `message_too_large`.\n- Voice supports audio only and one voice channel per room.\n- Voice control messages: 64 KB each and 30 operations per 10 seconds per connection. Voice signaling also uses the separate service-message budget; audio traffic does not consume either message budget.\n- Room save values: 256 KB each.\n\n## Development\n\nRun `npx @caisual/cli dev` from the game folder, then open the printed portal URL. The preview supplies the same handshake as the site, so `c.connected` is `true` and the game receives a local guest identity. `?lang=` chooses the language preference, resolved against the manifest: `?lang=ja` gives `c.player.language === \"ja\"` when declared. Friends are empty locally, so `c.crew.friends` is `[]`; everything else, including saves, daily data, invitations and rooms, works on local data. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nUse `npx @caisual/cli dev --day 2026-09-04` to pin the UTC day used by client and room daily seeds. The flag accepts only a real date in `YYYY-MM-DD` format; without it, dev uses today's UTC date. Real clocks and room timers keep running normally. Saves, identities and rooms are shared across these dates. Existing rooms retain their creation context; new rooms follow the selected day. `expiresAt` follows the real clock even with `--day`. A changed flag takes effect after restarting dev and reloading the game.\n\nOpen the printed `/__caisual/players?n=4` URL for 1 to 8 independent guest frames. Use the game's own menu to create a room in one frame and join its code in the others. Each frame has **Drop** (1 to 60 seconds, default 3) to interrupt that guest's room connection. Phone frames are 390 x 844; the desktop preset is 960 x 640. Add `&lang=it` to test Italian.\n\n`dev --latency 120 --jitter 40 --loss 2` delays room WebSocket messages in both directions. Latency and jitter are integer milliseconds from 0 to 60000; loss is a percentage from 0 to 100 and may be fractional. Jitter and loss require `--latency`, which may be zero. Jitter varies delay uniformly within plus/minus the supplied value, clamped at zero, and preserves message order. Loss discards whole application messages, including protocol messages, to exercise recovery; it is not a model of TCP packet retransmission. HTTP, matchmaking and audio are unaffected. Drop closes the guest's room sockets and prevents successful reconnects for the selected duration; the kit's retry schedule can make the return later.\n\nClient files are read on each request: reload the portal or frame after editing, or rebuild into `client/` first if using a bundler. There is no automatic browser reload. Restart dev after changing `caisual.json`, `server.js`, or any server import (including shared client physics). Rooms restore from `.caisual-dev/`; changing the shape of their state may require creating a fresh room. A busy port error suggests a command with a currently available port.\n\nEvery `init` variant generates Node test and optional Playwright browser scripts. Playwright is a development dependency of the generated game, never of the CLI. See [Local dev](/docs/local-development#testing-with-a-browser) for installation and the full browser workflow.\n\nWhen building the client with a bundler, remember that `client/` is served as-is. Configure Vite, esbuild, or another bundler to write into that folder, for example `vite build --outDir client`, and use relative paths such as `base: './'`.\n\nKeep loading the kit from the `<script type=\"module\">` shown at the beginning of this guide, using `/__caisual/kit/v1.js`, when publishing on Caisual. That URL exists only in `caisual dev` and in the published game.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. Single-player modes reject room operations with `mode_local`. Multiplayer modes require `server.js`.\n\nTo run from any other static server, install `@caisual/kit` from npm and import it with a bundler as `import { caisual } from '@caisual/kit'`. In that build standalone mode applies: `c.connected` is `false`, saves use local storage, the daily seed is local, and room creation and joining reject with `offline`. The rest of the game logic does not need a different code path.\n\nAfter publishing with `npx @caisual/cli publish`, open the game from its caisual.com page: `c.connected` becomes `true` and every call goes to the portal.\n\n## Manifest\n\nSingle player runs in the browser and never touches the server; a room exists only for two or more players. A mode is local when its resolved `players.max` is 1. Modes with `players.max > 1` require `server.js`. The manifest carries no text for the platform to draw: the names the player reads live in the game's own dictionaries. A mode with matchmaking adds `matchmaking.defaults`, one value for every field of its `key`, so the game can start a search without composing one.\n\n```json\n{\n \"players\": { \"min\": 2, \"max\": 4 },\n \"lobby\": true,\n \"modes\": [\n { \"id\": \"practice\", \"players\": { \"min\": 1, \"max\": 1 }, \"lobby\": false },\n { \"id\": \"duel\",\n \"matchmaking\": { \"key\": [\"pool\"], \"defaults\": { \"pool\": \"v1\" }, \"timeoutMs\": 12000 } }\n ]\n}\n```\n\nNo manifest field is required for identity, saves, or the daily challenge. A mode may override only `players: { min, max }` and `lobby`; omitted fields inherit the root configuration, and `mode: null` uses the root values. Matchmaking thresholds and room admission use this same resolution, with lobby forced on for player-created rooms. For rooms, set `players` to the supported range and use `lobby`, `persistent`, `roles`, `teams`, and `modes` to describe the setup and lifetime. Set `voice` to `room`, `team`, or `proximity` to enable the corresponding voice mode, or omit it for `none`. A single-player game keeps `players` at `{ \"min\": 1, \"max\": 1 }`, `lobby` at `false`, and needs no `server.js`. See [publish.md](./publish.md#caisualjson) for every field and the publishing steps.\n\n## Required game images\n\nEnglish (`en`) is required in `languages`; three distinct files inside `client/` with no text inside are also required: cover 1536x1024 (3:2), card 1024x1024 and icon 1024x1024, each PNG, JPEG or WebP and at most 2 MB. See [Manifest](https://caisual.com/docs/manifest#required-game-images).\n";
1222
1165
 
1223
1166
  // src/dev.ts
1224
1167
  import { createHash as createHash3, createHmac, randomBytes, randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
@@ -1272,15 +1215,10 @@ function risolviModalita2(manifest, mode) {
1272
1215
  return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
1273
1216
  }
1274
1217
  function modalitaLocale2(manifest, mode) {
1275
- return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
1276
- }
1277
- var MASSIMO_SPETTATORI = 100;
1278
- var RITARDO_SPETTATORI_MS2 = 3e3;
1279
- var REPLAY_MAX_BYTES2 = 10 * 1024 * 1024;
1280
- var REPLAY_MAX_DURATION_MS2 = 30 * 60 * 1e3;
1281
- var REPLAY_CHUNK_BYTES2 = 512 * 1024;
1282
- var REPLAY_RETENTION_MS2 = 30 * 24 * 60 * 60 * 1e3;
1283
- function validBoardDay2(value) {
1218
+ return risolviModalita2(manifest, mode).players.max === 1;
1219
+ }
1220
+ var MODE_LOCAL_MESSAGE2 = "Single-player modes run in the browser and have no room.";
1221
+ function validDay2(value) {
1284
1222
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
1285
1223
  const at = Date.parse(`${value}T00:00:00Z`);
1286
1224
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
@@ -1325,6 +1263,81 @@ var LimiteMessaggiStanza = class {
1325
1263
  };
1326
1264
  }
1327
1265
  };
1266
+ var NETWORK_BUDGET2 = Object.freeze({
1267
+ recipientBytesPerSecond: 1e5,
1268
+ roomBytesPerSecond: 2e6,
1269
+ warningRatio: 0.8,
1270
+ windowMs: 5e3,
1271
+ blockingWindows: 3
1272
+ });
1273
+ var NETWORK_GUIDANCE2 = `Multiplayer budget: ${NETWORK_BUDGET2.recipientBytesPerSecond / 1e3} kB/s per recipient, ${NETWORK_BUDGET2.roomBytesPerSecond / 1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${NETWORK_BUDGET2.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.`;
1274
+ function networkLevel(measurement) {
1275
+ const ratio = Math.max(
1276
+ measurement.recipientBytesPerSecond / NETWORK_BUDGET2.recipientBytesPerSecond,
1277
+ measurement.roomBytesPerSecond / NETWORK_BUDGET2.roomBytesPerSecond
1278
+ );
1279
+ return ratio > 1 ? "exceeded" : ratio >= NETWORK_BUDGET2.warningRatio ? "warning" : "ok";
1280
+ }
1281
+ function networkMessage(measurement) {
1282
+ return `Network ${networkLevel(measurement)}: ${measurement.recipientBytesPerSecond} B/s per recipient (limit ${NETWORK_BUDGET2.recipientBytesPerSecond}), ${measurement.roomBytesPerSecond} B/s per room (limit ${NETWORK_BUDGET2.roomBytesPerSecond}), before compression over 5 seconds. Send compact changes; keep visual trails and animation on the client. At 20 updates/s, budget ${NETWORK_BUDGET2.recipientBytesPerSecond / 2e4} kB per update.`;
1283
+ }
1284
+ var NetworkMeter = class {
1285
+ events = [];
1286
+ head = 0;
1287
+ recipients = /* @__PURE__ */ new Map();
1288
+ total = 0;
1289
+ peak = { recipientBytesPerSecond: 0, roomBytesPerSecond: 0 };
1290
+ checkAt = null;
1291
+ violations = 0;
1292
+ blocked = false;
1293
+ encoder = new TextEncoder();
1294
+ record(recipient, text, now = Date.now()) {
1295
+ this.advance(now);
1296
+ const bytes = this.encoder.encode(text).byteLength;
1297
+ this.events.push({ at: now, recipient, bytes });
1298
+ const recipientBytes = (this.recipients.get(recipient) ?? 0) + bytes;
1299
+ this.recipients.set(recipient, recipientBytes);
1300
+ this.total += bytes;
1301
+ this.peak.recipientBytesPerSecond = Math.max(this.peak.recipientBytesPerSecond, this.rate(recipientBytes));
1302
+ this.peak.roomBytesPerSecond = Math.max(this.peak.roomBytesPerSecond, this.rate(this.total));
1303
+ }
1304
+ sample(now = Date.now()) {
1305
+ this.advance(now);
1306
+ return { current: this.current(), peak: { ...this.peak }, consecutiveViolations: this.violations, blocked: this.blocked };
1307
+ }
1308
+ rate(bytes) {
1309
+ return Math.ceil(bytes * 1e3 / NETWORK_BUDGET2.windowMs);
1310
+ }
1311
+ current() {
1312
+ let maximum = 0;
1313
+ for (const bytes of this.recipients.values()) maximum = Math.max(maximum, bytes);
1314
+ return { recipientBytesPerSecond: this.rate(maximum), roomBytesPerSecond: this.rate(this.total) };
1315
+ }
1316
+ advance(now) {
1317
+ this.checkAt ??= now;
1318
+ this.expire(now - NETWORK_BUDGET2.windowMs, false);
1319
+ if (now - this.checkAt >= NETWORK_BUDGET2.windowMs) {
1320
+ if (now - this.checkAt >= NETWORK_BUDGET2.windowMs * 2) this.violations = 0;
1321
+ this.violations = networkLevel(this.current()) === "exceeded" ? this.violations + 1 : 0;
1322
+ this.blocked ||= this.violations >= NETWORK_BUDGET2.blockingWindows;
1323
+ this.checkAt = now;
1324
+ }
1325
+ this.expire(now - NETWORK_BUDGET2.windowMs, true);
1326
+ if (this.head > 1024) {
1327
+ this.events = this.events.slice(this.head);
1328
+ this.head = 0;
1329
+ }
1330
+ }
1331
+ expire(cutoff, inclusive) {
1332
+ while (this.head < this.events.length && (inclusive ? this.events[this.head].at <= cutoff : this.events[this.head].at < cutoff)) {
1333
+ const event = this.events[this.head++];
1334
+ this.total -= event.bytes;
1335
+ const remaining = this.recipients.get(event.recipient) - event.bytes;
1336
+ if (remaining === 0) this.recipients.delete(event.recipient);
1337
+ else this.recipients.set(event.recipient, remaining);
1338
+ }
1339
+ }
1340
+ };
1328
1341
  function prossimaMezzanotteUtc(ora) {
1329
1342
  return (Math.floor(ora / 864e5) + 1) * 864e5;
1330
1343
  }
@@ -1559,8 +1572,6 @@ var PREFISSO_SAVE = "save:";
1559
1572
  var LIMITE_FRAME = MASSIMO_BYTE_FRAME_STANZA2;
1560
1573
  var LIMITE_STATO = 512 * 1024;
1561
1574
  var LIMITE_SAVE = 256 * 1024;
1562
- var LIMITE_DEPOSITO = 256 * 1024;
1563
- var LIMITE_OPERAZIONI_DEPOSITO = 120;
1564
1575
  var GRAZIA_MS = 6e4;
1565
1576
  var STANZA_VUOTA_MS = 5 * 6e4;
1566
1577
  var ATTESA_RIVINCITA_MS = 2 * 6e4;
@@ -1573,16 +1584,7 @@ function scadenzaInattivita(ultimoEvento, durata) {
1573
1584
  return Math.ceil((ultimoEvento + durata) / BLOCCO_INATTIVITA_MS) * BLOCCO_INATTIVITA_MS;
1574
1585
  }
1575
1586
  var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
1576
- var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
1577
1587
  var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
1578
- var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
1579
- "store_invalid_key",
1580
- "store_too_large",
1581
- "store_full",
1582
- "store_not_integer",
1583
- "store_unavailable",
1584
- "store_rate_limited"
1585
- ]);
1586
1588
  function record(value) {
1587
1589
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1588
1590
  }
@@ -1620,7 +1622,6 @@ var NucleoStanza = class _NucleoStanza {
1620
1622
  this.adattatore = adattatore;
1621
1623
  this.dati = null;
1622
1624
  this.frequenza = new LimiteMessaggiStanza();
1623
- this.frequenzaDeposito = [];
1624
1625
  this.kickRichiesti = /* @__PURE__ */ new Set();
1625
1626
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
1626
1627
  this.fineRichiesta = null;
@@ -1671,11 +1672,6 @@ var NucleoStanza = class _NucleoStanza {
1671
1672
  get players() {
1672
1673
  return nucleo.richiediDati().giocatori.map(copiaGiocatore);
1673
1674
  },
1674
- get host() {
1675
- const dati = nucleo.richiediDati();
1676
- const host = dati.giocatori.find((player) => player.id === dati.hostId);
1677
- return host === void 0 ? null : copiaGiocatore(host);
1678
- },
1679
1675
  broadcast(message) {
1680
1676
  nucleo.broadcastCreatore(message);
1681
1677
  },
@@ -1700,23 +1696,6 @@ var NucleoStanza = class _NucleoStanza {
1700
1696
  load(key) {
1701
1697
  return nucleo.caricaSave(key);
1702
1698
  },
1703
- shared: {
1704
- get(key) {
1705
- return nucleo.leggiDeposito(key);
1706
- },
1707
- set(key, value) {
1708
- return nucleo.scriviDeposito(key, value);
1709
- },
1710
- delete(key) {
1711
- return nucleo.eliminaDeposito(key);
1712
- },
1713
- list(prefix) {
1714
- return nucleo.elencaDeposito(prefix);
1715
- },
1716
- increment(key, amount = 1) {
1717
- return nucleo.incrementaDeposito(key, amount);
1718
- }
1719
- },
1720
1699
  schedule(milliseconds, handler, payload) {
1721
1700
  nucleo.pianifica(milliseconds, handler, payload);
1722
1701
  },
@@ -1746,9 +1725,11 @@ var NucleoStanza = class _NucleoStanza {
1746
1725
  const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
1747
1726
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
1748
1727
  if (salvato !== void 0) {
1728
+ if (modalitaLocale2(manifest, salvato.mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE2), { code: "mode_local" });
1749
1729
  nucleo.dati = salvato;
1750
1730
  nucleo.tickRateSincronizzato = salvato.tickRate;
1751
- const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0;
1731
+ const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0 || salvato.origin === void 0;
1732
+ salvato.origin ??= "player";
1752
1733
  salvato.daily ??= nucleo.contestoGiornaliero();
1753
1734
  salvato.ultimoInputAt ??= adattatore.ora();
1754
1735
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
@@ -1774,13 +1755,13 @@ var NucleoStanza = class _NucleoStanza {
1774
1755
  get esiste() {
1775
1756
  return this.dati !== null;
1776
1757
  }
1777
- async crea(id, mode, _creator) {
1758
+ async crea(id, mode, _creator, origin = "player") {
1778
1759
  if (this.dati !== null) return false;
1779
- risolviModalita2(this.manifest, mode);
1780
- if (modalitaLocale2(this.manifest, mode)) throw new Error("Local modes cannot create rooms.");
1760
+ if (modalitaLocale2(this.manifest, mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE2), { code: "mode_local" });
1781
1761
  const ora = this.adattatore.ora();
1782
1762
  this.dati = {
1783
1763
  versione: 1,
1764
+ origin,
1784
1765
  daily: this.contestoGiornaliero(ora),
1785
1766
  id,
1786
1767
  mode,
@@ -1791,13 +1772,11 @@ var NucleoStanza = class _NucleoStanza {
1791
1772
  ultimoCambioStatoAt: ora,
1792
1773
  state: {},
1793
1774
  giocatori: [],
1794
- hostId: null,
1795
1775
  result: null,
1796
1776
  resultAt: null,
1797
1777
  countdownAt: null,
1798
1778
  timer: [],
1799
1779
  prossimoTimerId: 1,
1800
- punteggi: [],
1801
1780
  fineInCoda: null,
1802
1781
  vuotaDa: ora,
1803
1782
  cancellaDopoFlush: false,
@@ -1825,12 +1804,14 @@ var NucleoStanza = class _NucleoStanza {
1825
1804
  }
1826
1805
  get configurazione() {
1827
1806
  const mode = risolviModalita2(this.manifest, this.dati?.mode ?? null);
1828
- return mode.players.max === 1 ? { ...mode, lobby: false } : mode;
1807
+ return this.dati?.origin === "matchmaking" ? mode : { ...mode, lobby: true };
1829
1808
  }
1830
1809
  info(playerId) {
1831
1810
  if (this.dati === null) return null;
1832
1811
  return {
1833
1812
  roomId: this.dati.id,
1813
+ origin: this.dati.origin,
1814
+ lobby: this.configurazione.lobby,
1834
1815
  status: this.dati.status,
1835
1816
  players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
1836
1817
  (player) => player.connected || player.graziaFinoA !== null
@@ -1864,7 +1845,7 @@ var NucleoStanza = class _NucleoStanza {
1864
1845
  if (ascoltatore === void 0 || speaker === void 0 || listener === speakerId) {
1865
1846
  return { ok: false, reason: "unknown" };
1866
1847
  }
1867
- if (mode === "team" && ascoltatore.role !== "spectator" && ascoltatore.team !== speaker.team) {
1848
+ if (mode === "team" && ascoltatore.team !== speaker.team) {
1868
1849
  return { ok: false, reason: "team" };
1869
1850
  }
1870
1851
  if ((dati.voceGuadagni?.[listener]?.[speakerId] ?? 1) <= 0) {
@@ -1878,12 +1859,15 @@ var NucleoStanza = class _NucleoStanza {
1878
1859
  if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
1879
1860
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
1880
1861
  if (esistente !== void 0) return { ok: true };
1881
- if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
1862
+ if (this.configurazione.lobby && !["lobby", "countdown", "finished"].includes(this.dati.status)) {
1882
1863
  return { ok: false, code: "room_playing" };
1883
1864
  }
1884
1865
  if (this.dati.giocatori.length >= this.configurazione.players.max) {
1885
1866
  return { ok: false, code: "room_full" };
1886
1867
  }
1868
+ if (this.manifest.roles.length > 0 && this.ruoloAutomatico() === null) {
1869
+ return { ok: false, code: "room_full" };
1870
+ }
1887
1871
  return { ok: true };
1888
1872
  }
1889
1873
  async entra(identity, connessione) {
@@ -1923,7 +1907,6 @@ var NucleoStanza = class _NucleoStanza {
1923
1907
  player.connessione = connessione;
1924
1908
  player.seq = 0;
1925
1909
  }
1926
- dati.hostId ??= player.id;
1927
1910
  dati.vuotaDa = null;
1928
1911
  dati.ultimoInputAt = ora;
1929
1912
  const primaConnessione = !this.configurazione.lobby && dati.status === "lobby";
@@ -1940,7 +1923,6 @@ var NucleoStanza = class _NucleoStanza {
1940
1923
  }
1941
1924
  if (primaConnessione) {
1942
1925
  await this.chiama(this.definizione.onStart, this.room);
1943
- this.iniziaReplay();
1944
1926
  this.inviaStatus(ora);
1945
1927
  }
1946
1928
  await this.concludiEvento();
@@ -1948,6 +1930,7 @@ var NucleoStanza = class _NucleoStanza {
1948
1930
  this.inviaWelcome(player);
1949
1931
  this.inviaSnapshotTutti();
1950
1932
  this.inviaGiocatori();
1933
+ this.rivalutaAvvio();
1951
1934
  }
1952
1935
  await this.persistiEProgramma();
1953
1936
  return { ok: true };
@@ -1961,10 +1944,9 @@ var NucleoStanza = class _NucleoStanza {
1961
1944
  player.connected = false;
1962
1945
  player.connessione = null;
1963
1946
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
1964
- if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
1947
+ if (this.dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(this.dati.status)) player.ready = false;
1965
1948
  this.frequenza.delete(connessione);
1966
- if (this.dati.hostId === player.id) this.assegnaHost();
1967
- this.verificaCountdown();
1949
+ this.rivalutaAvvio();
1968
1950
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
1969
1951
  await this.concludiEvento();
1970
1952
  this.inviaGiocatori();
@@ -2031,6 +2013,7 @@ var NucleoStanza = class _NucleoStanza {
2031
2013
  this.dati.ultimoInputAt = ora;
2032
2014
  player.ready = message.ready;
2033
2015
  this.inviaGiocatori();
2016
+ this.rivalutaAvvio();
2034
2017
  await this.persistiEProgramma();
2035
2018
  return;
2036
2019
  }
@@ -2072,12 +2055,6 @@ var NucleoStanza = class _NucleoStanza {
2072
2055
  await this.persistiEProgramma();
2073
2056
  return;
2074
2057
  }
2075
- if (message.t === "start") {
2076
- if (!this.inLobby(player)) return;
2077
- this.dati.ultimoInputAt = ora;
2078
- await this.avviaCountdown(player);
2079
- return;
2080
- }
2081
2058
  if (message.t === "msg") {
2082
2059
  if (!Number.isSafeInteger(message.seq) || message.seq < 1) {
2083
2060
  await this.messaggioErrato(player);
@@ -2091,11 +2068,6 @@ var NucleoStanza = class _NucleoStanza {
2091
2068
  return;
2092
2069
  }
2093
2070
  player.seq = seq;
2094
- if (player.role === "spectator") {
2095
- this.inviaErrore(player, "spectator", "Spectators cannot send game input.");
2096
- await this.persistiEProgramma();
2097
- return;
2098
- }
2099
2071
  if (this.dati.status === "finished") return;
2100
2072
  this.dati.ultimoInputAt = ora;
2101
2073
  await this.chiama(
@@ -2160,7 +2132,6 @@ var NucleoStanza = class _NucleoStanza {
2160
2132
  this.dati.ultimoInputAt = ora;
2161
2133
  this.dati.countdownAt = null;
2162
2134
  await this.chiama(this.definizione.onStart, this.room);
2163
- this.iniziaReplay();
2164
2135
  this.inviaStatus(ora);
2165
2136
  }
2166
2137
  }
@@ -2189,9 +2160,8 @@ var NucleoStanza = class _NucleoStanza {
2189
2160
  await this.persistiEProgramma();
2190
2161
  return dati.flushInAttesa;
2191
2162
  }
2192
- if (dati.punteggi.length === 0 && dati.fineInCoda === null) return null;
2193
- dati.flushInAttesa = { id: crypto.randomUUID(), scores: dati.punteggi, ended: dati.fineInCoda };
2194
- dati.punteggi = [];
2163
+ if (dati.fineInCoda === null) return null;
2164
+ dati.flushInAttesa = { id: crypto.randomUUID(), ended: dati.fineInCoda };
2195
2165
  dati.fineInCoda = null;
2196
2166
  await this.persistiEProgramma();
2197
2167
  return dati.flushInAttesa;
@@ -2205,10 +2175,8 @@ var NucleoStanza = class _NucleoStanza {
2205
2175
  async flush() {
2206
2176
  const dati = this.richiediDati();
2207
2177
  const esito = {
2208
- scores: dati.punteggi.map((score) => ({ ...score })),
2209
2178
  ended: dati.fineInCoda === null ? null : { result: dati.fineInCoda.result, at: dati.fineInCoda.at }
2210
2179
  };
2211
- dati.punteggi = [];
2212
2180
  dati.fineInCoda = null;
2213
2181
  if (dati.cancellaDopoFlush && dati.status === "ended") {
2214
2182
  const chiavi = await this.adattatore.storage.list();
@@ -2233,13 +2201,12 @@ var NucleoStanza = class _NucleoStanza {
2233
2201
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
2234
2202
  player.connessione = null;
2235
2203
  player.graziaFinoA = ora + GRAZIA_MS;
2236
- if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
2204
+ if (dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(dati.status)) player.ready = false;
2237
2205
  disconnessi.push(player);
2238
2206
  }
2239
2207
  }
2240
2208
  if (disconnessi.length > 0) {
2241
- this.assegnaHost();
2242
- this.verificaCountdown();
2209
+ this.rivalutaAvvio();
2243
2210
  for (const player of disconnessi) {
2244
2211
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
2245
2212
  }
@@ -2262,7 +2229,7 @@ var NucleoStanza = class _NucleoStanza {
2262
2229
  const mancaB = countB < b.min ? 0 : 1;
2263
2230
  return mancaA - mancaB || countA - countB;
2264
2231
  });
2265
- return candidati[0]?.id ?? "spectator";
2232
+ return candidati[0]?.id ?? null;
2266
2233
  }
2267
2234
  squadraAutomatica() {
2268
2235
  if (this.manifest.teams === null) return null;
@@ -2285,39 +2252,37 @@ var NucleoStanza = class _NucleoStanza {
2285
2252
  }
2286
2253
  cambiaRuolo(player, roleId) {
2287
2254
  const ruolo = this.manifest.roles.find((item) => item.id === roleId);
2288
- if (ruolo === void 0 && roleId !== "spectator") {
2255
+ if (ruolo === void 0) {
2289
2256
  return { code: "invalid_role", message: "This role does not exist." };
2290
2257
  }
2291
2258
  const occupati = this.richiediDati().giocatori.filter(
2292
2259
  (item) => item.id !== player.id && item.role === roleId
2293
2260
  ).length;
2294
- if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
2261
+ if (ruolo.max !== void 0 && occupati >= ruolo.max) {
2295
2262
  return { code: "role_full", message: "This role is full." };
2296
2263
  }
2297
2264
  const ruoloPrecedente = player.role;
2298
2265
  const squadraPrecedente = player.team;
2299
2266
  player.role = roleId;
2300
- if (roleId === "spectator") player.team = null;
2301
- else if (player.team === null) player.team = this.squadraAutomatica();
2267
+ if (player.team === null) player.team = this.squadraAutomatica();
2302
2268
  if (this.richiediDati().status === "lobby") player.ready = false;
2303
2269
  if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
2304
2270
  this.rivediVoce();
2305
2271
  }
2306
2272
  this.inviaGiocatori();
2273
+ this.rivalutaAvvio();
2307
2274
  return null;
2308
2275
  }
2309
2276
  cambiaSquadra(player, team) {
2310
2277
  if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
2311
2278
  return { code: "invalid_team", message: "This team does not exist." };
2312
2279
  }
2313
- if (player.role === "spectator") {
2314
- return { code: "spectator", message: "Spectators cannot join a team." };
2315
- }
2316
2280
  const squadraPrecedente = player.team;
2317
2281
  player.team = team;
2318
2282
  if (this.richiediDati().status === "lobby") player.ready = false;
2319
2283
  if (player.team !== squadraPrecedente) this.rivediVoce();
2320
2284
  this.inviaGiocatori();
2285
+ this.rivalutaAvvio();
2321
2286
  return null;
2322
2287
  }
2323
2288
  impostaRuoloDalServer(playerId, roleId) {
@@ -2339,21 +2304,20 @@ var NucleoStanza = class _NucleoStanza {
2339
2304
  }
2340
2305
  erroreMinimi(saltaPronti = false) {
2341
2306
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
2342
- const attivi = connessi.filter((player) => player.role !== "spectator");
2343
- if (attivi.length < this.configurazione.players.min) {
2307
+ if (connessi.length < this.configurazione.players.min) {
2344
2308
  return { code: "not_enough_players", message: "The room does not have enough players." };
2345
2309
  }
2346
2310
  if (!saltaPronti && connessi.some((player) => !player.ready)) {
2347
2311
  return { code: "players_not_ready", message: "Every connected player must be ready." };
2348
2312
  }
2349
2313
  for (const role of this.manifest.roles) {
2350
- if (attivi.filter((player) => player.role === role.id).length < role.min) {
2314
+ if (connessi.filter((player) => player.role === role.id).length < role.min) {
2351
2315
  return { code: "role_minimum", message: `Role ${role.id} does not meet its minimum.` };
2352
2316
  }
2353
2317
  }
2354
2318
  if (this.manifest.teams !== null) {
2355
- const squadre = new Set(attivi.map((player) => player.team).filter((team) => team !== null));
2356
- if (attivi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
2319
+ const squadre = new Set(connessi.map((player) => player.team).filter((team) => team !== null));
2320
+ if (connessi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
2357
2321
  return { code: "team_minimum", message: "The room does not have enough teams." };
2358
2322
  }
2359
2323
  }
@@ -2365,32 +2329,20 @@ var NucleoStanza = class _NucleoStanza {
2365
2329
  this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
2366
2330
  return;
2367
2331
  }
2368
- if (this.configurazione.players.max === 1) {
2369
- await this.avviaRivincita();
2370
- return;
2371
- }
2372
- if (player.role !== "spectator" && !player.ready) {
2373
- player.ready = true;
2374
- this.inviaGiocatori();
2375
- if (dati.rivincita?.autoStart && this.prontiRivincita()) await this.avviaRivincita();
2376
- else await this.persistiEProgramma();
2377
- return;
2378
- }
2379
- if (dati.hostId !== player.id) return;
2380
- if (!this.prontiRivincita(dati.rivincita?.autoStart === true)) {
2381
- this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
2382
- return;
2383
- }
2384
- await this.avviaRivincita();
2332
+ if (player.ready) return;
2333
+ player.ready = true;
2334
+ this.inviaGiocatori();
2335
+ if (this.prontiRivincita()) await this.avviaRivincita();
2336
+ else await this.persistiEProgramma();
2385
2337
  }
2386
- prontiRivincita(anticipata = false) {
2387
- const attivi = this.richiediDati().giocatori.filter((item) => item.connected && item.role !== "spectator");
2388
- return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && (anticipata || attivi.every((item) => item.ready));
2338
+ prontiRivincita() {
2339
+ const attivi = this.richiediDati().giocatori.filter((item) => item.connected);
2340
+ return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && attivi.every((item) => item.ready);
2389
2341
  }
2390
2342
  async avviaRivincita() {
2391
- const dati = this.richiediDati(), solo = this.configurazione.players.max === 1;
2392
- const keepSetup = dati.rivincita?.keepSetup === true && !solo;
2393
- dati.status = solo ? "playing" : keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
2343
+ const dati = this.richiediDati();
2344
+ const keepSetup = dati.rivincita?.keepSetup === true;
2345
+ dati.status = keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
2394
2346
  dati.countdownRivincita = keepSetup;
2395
2347
  dati.countdownAt = keepSetup ? this.adattatore.ora() + COUNTDOWN_MS : null;
2396
2348
  dati.rivincitaFinoA = null;
@@ -2404,7 +2356,6 @@ var NucleoStanza = class _NucleoStanza {
2404
2356
  await this.applicaAzioni();
2405
2357
  if (dati.status === "playing") {
2406
2358
  await this.chiama(this.definizione.onStart, this.room);
2407
- this.iniziaReplay();
2408
2359
  }
2409
2360
  await this.concludiEvento();
2410
2361
  if (dati.status === "lobby" || dati.status === "playing" || dati.status === "countdown") {
@@ -2414,29 +2365,25 @@ var NucleoStanza = class _NucleoStanza {
2414
2365
  }
2415
2366
  await this.persistiEProgramma();
2416
2367
  }
2417
- async avviaCountdown(player) {
2368
+ /**
2369
+ * Nessuno ospita e nessuno preme "inizia": appena tutti i connessi sono pronti e i
2370
+ * minimi di giocatori, ruoli e squadre sono rispettati parte il countdown; se la
2371
+ * condizione cade durante il countdown si torna in lobby.
2372
+ */
2373
+ rivalutaAvvio() {
2418
2374
  const dati = this.richiediDati();
2419
- if (dati.hostId !== player.id) {
2420
- this.inviaErrore(player, "not_host", "Only the host can start the game.");
2421
- return;
2422
- }
2423
- const errore = this.erroreMinimi();
2424
- if (errore !== null) {
2425
- this.inviaErrore(player, errore.code, errore.message);
2375
+ if (dati.status === "countdown") {
2376
+ if (this.erroreMinimi(dati.countdownRivincita) === null) return;
2377
+ dati.status = "lobby";
2378
+ dati.countdownAt = null;
2379
+ this.inviaStatus(this.adattatore.ora());
2426
2380
  return;
2427
2381
  }
2382
+ if (dati.status !== "lobby" || this.erroreMinimi() !== null) return;
2428
2383
  dati.status = "countdown";
2429
2384
  dati.countdownRivincita = false;
2430
2385
  dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
2431
2386
  this.inviaStatus(dati.countdownAt);
2432
- await this.persistiEProgramma();
2433
- }
2434
- verificaCountdown() {
2435
- const dati = this.richiediDati();
2436
- if (dati.status !== "countdown" || this.erroreMinimi(dati.countdownRivincita) === null) return;
2437
- dati.status = "lobby";
2438
- dati.countdownAt = null;
2439
- this.inviaStatus(this.adattatore.ora());
2440
2387
  }
2441
2388
  async messaggioErrato(player) {
2442
2389
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -2454,7 +2401,6 @@ var NucleoStanza = class _NucleoStanza {
2454
2401
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
2455
2402
  this.rivediVoce();
2456
2403
  this.pulisciGuadagni(player.id);
2457
- if (dati.hostId === player.id) this.assegnaHost();
2458
2404
  if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
2459
2405
  await this.chiama(
2460
2406
  this.definizione.onLeave,
@@ -2462,12 +2408,7 @@ var NucleoStanza = class _NucleoStanza {
2462
2408
  copiaGiocatore({ ...player, connected: false, connessione: null }),
2463
2409
  reason
2464
2410
  );
2465
- this.verificaCountdown();
2466
- }
2467
- assegnaHost() {
2468
- const dati = this.richiediDati();
2469
- const host = dati.giocatori.filter((player) => player.connected).sort((a, b) => a.entratoAt - b.entratoAt)[0];
2470
- dati.hostId = host?.id ?? null;
2411
+ this.rivalutaAvvio();
2471
2412
  }
2472
2413
  async eseguiTimer(timer) {
2473
2414
  const value = this.definizione[timer.handler];
@@ -2533,91 +2474,6 @@ var NucleoStanza = class _NucleoStanza {
2533
2474
  if (!json.ok) throw new Error("The saved value is invalid.");
2534
2475
  return json.valore;
2535
2476
  }
2536
- verificaChiaveDeposito(key) {
2537
- if (typeof key !== "string" || !CHIAVE.test(key)) {
2538
- throw erroreConCodice(
2539
- "store_invalid_key",
2540
- "Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
2541
- );
2542
- }
2543
- }
2544
- verificaPrefissoDeposito(prefix) {
2545
- if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
2546
- throw erroreConCodice(
2547
- "store_invalid_key",
2548
- "Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
2549
- );
2550
- }
2551
- }
2552
- contaOperazioneDeposito() {
2553
- const ora = this.adattatore.ora();
2554
- this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
2555
- if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
2556
- throw erroreConCodice(
2557
- "store_rate_limited",
2558
- "The shared store allows at most 120 operations per minute for each room."
2559
- );
2560
- }
2561
- this.frequenzaDeposito.push(ora);
2562
- }
2563
- async usaDeposito(operazione) {
2564
- this.contaOperazioneDeposito();
2565
- const deposito = this.adattatore.deposito;
2566
- if (deposito === null) {
2567
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
2568
- }
2569
- try {
2570
- return await operazione(deposito);
2571
- } catch (cause) {
2572
- const code = cause instanceof Error ? cause.code : void 0;
2573
- if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
2574
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
2575
- }
2576
- }
2577
- async leggiDeposito(key) {
2578
- this.verificaChiaveDeposito(key);
2579
- const value = await this.usaDeposito((deposito) => deposito.get(key));
2580
- if (value === null) return null;
2581
- try {
2582
- return JSON.parse(JSON.stringify(value));
2583
- } catch {
2584
- throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
2585
- }
2586
- }
2587
- async scriviDeposito(key, value) {
2588
- this.verificaChiaveDeposito(key);
2589
- const json = analizzaJson(value);
2590
- if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
2591
- throw erroreConCodice(
2592
- "store_too_large",
2593
- "Shared store values must be valid JSON of at most 262144 bytes."
2594
- );
2595
- }
2596
- await this.usaDeposito((deposito) => deposito.set(key, json.valore));
2597
- }
2598
- async eliminaDeposito(key) {
2599
- this.verificaChiaveDeposito(key);
2600
- await this.usaDeposito((deposito) => deposito.delete(key));
2601
- }
2602
- async elencaDeposito(prefix) {
2603
- this.verificaPrefissoDeposito(prefix);
2604
- const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
2605
- if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
2606
- throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
2607
- }
2608
- return [...keys].sort().slice(0, 4096);
2609
- }
2610
- async incrementaDeposito(key, amount) {
2611
- this.verificaChiaveDeposito(key);
2612
- if (!Number.isSafeInteger(amount)) {
2613
- throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
2614
- }
2615
- const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
2616
- if (!Number.isSafeInteger(value)) {
2617
- throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
2618
- }
2619
- return value;
2620
- }
2621
2477
  messaggioCreatore(message) {
2622
2478
  const json = analizzaJson(message);
2623
2479
  if (!json.ok) throw new TypeError("Messages must be valid JSON.");
@@ -2644,7 +2500,6 @@ var NucleoStanza = class _NucleoStanza {
2644
2500
  this.adattatore.invia(player.connessione, message);
2645
2501
  }
2646
2502
  }
2647
- if (message.t !== "flush") this.adattatore.pubblica(message);
2648
2503
  }
2649
2504
  inviaErrore(player, code, message) {
2650
2505
  if (player.connected && player.connessione !== null) {
@@ -2689,7 +2544,6 @@ var NucleoStanza = class _NucleoStanza {
2689
2544
  tick: dati.tick,
2690
2545
  tickRate: dati.tickRate,
2691
2546
  serverTime: this.adattatore.ora(),
2692
- host: dati.hostId,
2693
2547
  countdownAt: dati.countdownAt,
2694
2548
  configuration: {
2695
2549
  players: { ...this.configurazione.players },
@@ -2700,7 +2554,7 @@ var NucleoStanza = class _NucleoStanza {
2700
2554
  };
2701
2555
  }
2702
2556
  inviaGiocatori() {
2703
- this.broadcast({ t: "players", players: this.giocatoriProtocollo(), host: this.richiediDati().hostId });
2557
+ this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
2704
2558
  }
2705
2559
  inviaStatus(at) {
2706
2560
  const dati = this.richiediDati();
@@ -2708,7 +2562,6 @@ var NucleoStanza = class _NucleoStanza {
2708
2562
  t: "status",
2709
2563
  rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
2710
2564
  status: dati.status,
2711
- host: dati.hostId,
2712
2565
  countdownAt: dati.countdownAt,
2713
2566
  at,
2714
2567
  result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
@@ -2730,13 +2583,6 @@ var NucleoStanza = class _NucleoStanza {
2730
2583
  dati.statoSincronizzato = copiaJson(dati.state);
2731
2584
  dati.tickSincronizzato = dati.tick;
2732
2585
  }
2733
- iniziaReplay() {
2734
- if (!this.manifest.replays || !this.adattatore.inizioReplay) return;
2735
- const json = analizzaJson(this.richiediDati().state);
2736
- if (!json.ok || json.bytes > LIMITE_STATO) return;
2737
- this.inviaSnapshotTutti();
2738
- this.adattatore.inizioReplay(this.fotografia());
2739
- }
2740
2586
  inviaSnapshotTutti() {
2741
2587
  const dati = this.richiediDati();
2742
2588
  const stato = analizzaJson(dati.state);
@@ -2786,7 +2632,7 @@ var NucleoStanza = class _NucleoStanza {
2786
2632
  async concludiEvento() {
2787
2633
  await this.applicaAzioni();
2788
2634
  if (this.dati === null || this.dati.status === "ended") return;
2789
- if (this.dati.status === "finished" && this.dati.rivincita?.autoStart && this.prontiRivincita()) {
2635
+ if (this.dati.status === "finished" && this.dati.rivincita !== null && this.prontiRivincita()) {
2790
2636
  await this.avviaRivincita();
2791
2637
  return;
2792
2638
  }
@@ -2885,10 +2731,7 @@ var NucleoStanza = class _NucleoStanza {
2885
2731
  if (dati.status === "ended") return;
2886
2732
  const giaFinita = dati.status === "finished";
2887
2733
  dati.status = rematch ? "finished" : "ended";
2888
- dati.rivincita = rematch ? {
2889
- keepSetup: typeof rematch === "object" && rematch.keepSetup === true,
2890
- autoStart: typeof rematch === "object" && rematch.autoStart === true
2891
- } : null;
2734
+ dati.rivincita = rematch ? { keepSetup: typeof rematch === "object" && rematch.keepSetup === true } : null;
2892
2735
  dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
2893
2736
  dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
2894
2737
  dati.timer = [];
@@ -3275,14 +3118,10 @@ var ArchivioNode = class _ArchivioNode {
3275
3118
  }
3276
3119
  };
3277
3120
  var AdattatoreNode = class {
3278
- constructor(storage, deposito, ritardoSpettatori, dailyDay) {
3121
+ constructor(storage, dailyDay) {
3279
3122
  this.storage = storage;
3280
- this.deposito = deposito;
3281
- this.ritardoSpettatori = ritardoSpettatori;
3282
3123
  this.dailyDay = dailyDay;
3283
3124
  this.connessioni = /* @__PURE__ */ new Map();
3284
- this.spettatori = /* @__PURE__ */ new Map();
3285
- this.timerSpettatori = /* @__PURE__ */ new Set();
3286
3125
  this.tickTimer = null;
3287
3126
  this.tickIntervallo = null;
3288
3127
  this.tickGenerazione = 0;
@@ -3290,6 +3129,8 @@ var AdattatoreNode = class {
3290
3129
  this.svegliaAt = null;
3291
3130
  this.eseguiTick = async () => void 0;
3292
3131
  this.eseguiSveglia = async () => void 0;
3132
+ this.network = new NetworkMeter();
3133
+ this.networkWarning = "ok";
3293
3134
  }
3294
3135
  collega(input) {
3295
3136
  this.eseguiTick = input.tick;
@@ -3301,65 +3142,21 @@ var AdattatoreNode = class {
3301
3142
  rimuovi(id) {
3302
3143
  this.connessioni.delete(id);
3303
3144
  }
3304
- aggiungiSpettatore(id, socket) {
3305
- this.spettatori.set(id, socket);
3306
- }
3307
- rimuoviSpettatore(id) {
3308
- this.spettatori.delete(id);
3309
- }
3310
- numeroSpettatori() {
3311
- return this.spettatori.size;
3312
- }
3313
- elencoSpettatori() {
3314
- return [...this.spettatori];
3315
- }
3316
3145
  elencoConnessioni() {
3317
3146
  return [...this.connessioni];
3318
3147
  }
3319
- invia(connessione, messaggio) {
3320
- this.connessioni.get(connessione)?.send(JSON.stringify(messaggio));
3321
- }
3322
- pubblica(messaggio) {
3323
- const testo = JSON.stringify(messaggio);
3324
- for (const [connessione] of this.spettatori) {
3325
- this.inviaSpettatore(connessione, testo);
3326
- if (messaggio.t === "status" && messaggio.status === "ended") {
3327
- this.chiudiSpettatoreRitardato(connessione);
3328
- }
3329
- }
3330
- }
3331
- inviaSpettatore(connessione, testo) {
3332
- this.accodaSpettatore(connessione, (socket) => {
3333
- socket.send(testo);
3334
- });
3335
- }
3336
- inviaSpettatoreSubito(connessione, testo) {
3337
- this.spettatori.get(connessione)?.send(testo);
3338
- }
3339
- chiudiSpettatore(connessione, codice, motivo) {
3340
- const socket = this.spettatori.get(connessione);
3341
- this.spettatori.delete(connessione);
3342
- socket?.close(codice, motivo);
3343
- }
3344
- chiudiSpettatoreRitardato(connessione) {
3345
- this.accodaSpettatore(connessione, (socket) => {
3346
- this.spettatori.delete(connessione);
3347
- socket.close(4004, "room_ended");
3348
- });
3148
+ sendMeasured(socket, connection, text) {
3149
+ if (!socket) return;
3150
+ socket.send(text);
3151
+ this.network.record(connection, text);
3152
+ const report = this.network.sample();
3153
+ const warning = networkLevel(report.current);
3154
+ if (warning !== "ok" && warning !== this.networkWarning) process.stderr.write(`${networkMessage(report.current)}
3155
+ `);
3156
+ this.networkWarning = warning;
3349
3157
  }
3350
- accodaSpettatore(connessione, azione) {
3351
- if (this.ritardoSpettatori === 0) {
3352
- const socket = this.spettatori.get(connessione);
3353
- if (socket !== void 0) azione(socket);
3354
- return;
3355
- }
3356
- const timer = setTimeout(() => {
3357
- this.timerSpettatori.delete(timer);
3358
- const socket = this.spettatori.get(connessione);
3359
- if (socket !== void 0) azione(socket);
3360
- }, this.ritardoSpettatori ?? RITARDO_SPETTATORI_MS2);
3361
- this.timerSpettatori.add(timer);
3362
- timer.unref();
3158
+ invia(connessione, messaggio) {
3159
+ this.sendMeasured(this.connessioni.get(connessione), connessione, JSON.stringify(messaggio));
3363
3160
  }
3364
3161
  chiudi(connessione, codice, motivo) {
3365
3162
  this.connessioni.get(connessione)?.close(codice, motivo);
@@ -3399,8 +3196,6 @@ var AdattatoreNode = class {
3399
3196
  this.tickGenerazione += 1;
3400
3197
  if (this.tickTimer !== null) clearTimeout(this.tickTimer);
3401
3198
  if (this.svegliaTimer !== null) clearTimeout(this.svegliaTimer);
3402
- for (const timer of this.timerSpettatori) clearTimeout(timer);
3403
- this.timerSpettatori.clear();
3404
3199
  this.tickTimer = null;
3405
3200
  this.svegliaTimer = null;
3406
3201
  }
@@ -3450,8 +3245,11 @@ var StanzaNode = class {
3450
3245
  sveglia: () => this.serializza(() => nucleo.sveglia())
3451
3246
  });
3452
3247
  }
3453
- create(roomId, mode, creator) {
3454
- return this.serializza(() => this.nucleo.crea(roomId, mode, creator));
3248
+ network() {
3249
+ return this.adattatore.network.sample();
3250
+ }
3251
+ create(roomId, mode, creator, origin = "player") {
3252
+ return this.serializza(() => this.nucleo.crea(roomId, mode, creator, origin));
3455
3253
  }
3456
3254
  info() {
3457
3255
  return this.serializza(() => Promise.resolve(this.nucleo.info()));
@@ -3459,9 +3257,6 @@ var StanzaNode = class {
3459
3257
  canJoin(identity) {
3460
3258
  return this.serializza(() => Promise.resolve(this.nucleo.puoEntrare(identity)));
3461
3259
  }
3462
- canWatch() {
3463
- return this.serializza(() => Promise.resolve(this.permessoSpettatore()));
3464
- }
3465
3260
  async connect(socket, identity) {
3466
3261
  const connessione = randomUUID();
3467
3262
  this.adattatore.aggiungi(connessione, socket);
@@ -3492,28 +3287,6 @@ var StanzaNode = class {
3492
3287
  throw cause;
3493
3288
  }
3494
3289
  }
3495
- watch(socket, _identity) {
3496
- return this.serializza(async () => {
3497
- const permesso = this.permessoSpettatore();
3498
- if (!permesso.ok) return permesso;
3499
- const connessione = randomUUID();
3500
- this.adattatore.aggiungiSpettatore(connessione, socket);
3501
- socket.on("message", (message) => {
3502
- void this.serializza(() => this.riceviSpettatore(connessione, message));
3503
- });
3504
- socket.on("close", () => {
3505
- this.adattatore.rimuoviSpettatore(connessione);
3506
- this.frameFrequenza.delete(connessione);
3507
- });
3508
- const fotografia = this.nucleo.fotografia();
3509
- if (fotografia === null) {
3510
- this.adattatore.rimuoviSpettatore(connessione);
3511
- return { ok: false, code: "room_not_found" };
3512
- }
3513
- this.inviaWatching(connessione, fotografia);
3514
- return { ok: true };
3515
- });
3516
- }
3517
3290
  flush() {
3518
3291
  return this.serializza(() => this.nucleo.flush());
3519
3292
  }
@@ -3528,11 +3301,6 @@ var StanzaNode = class {
3528
3301
  socket.close(1001, "server_shutdown");
3529
3302
  await this.serializza(() => this.nucleo.disconnetti(connessione));
3530
3303
  }
3531
- for (const [connessione, socket] of this.adattatore.elencoSpettatori()) {
3532
- this.adattatore.rimuoviSpettatore(connessione);
3533
- this.frameFrequenza.delete(connessione);
3534
- socket.close(1001, "server_shutdown");
3535
- }
3536
3304
  }
3537
3305
  serializza(operazione) {
3538
3306
  const risultato = this.coda.then(operazione);
@@ -3576,74 +3344,9 @@ var StanzaNode = class {
3576
3344
  this.riconciliaRoster();
3577
3345
  return;
3578
3346
  }
3579
- await this.riceviVoce(connessione, player.id, player.role, message);
3347
+ await this.riceviVoce(connessione, player.id, message);
3580
3348
  }
3581
- permessoSpettatore() {
3582
- const info = this.nucleo.info();
3583
- if (info === null) return { ok: false, code: "room_not_found" };
3584
- if (info.status === "ended") return { ok: false, code: "room_ended" };
3585
- if (this.manifest.spectators === null) {
3586
- return { ok: false, code: "spectators_disabled" };
3587
- }
3588
- if (this.adattatore.numeroSpettatori() >= MASSIMO_SPETTATORI) {
3589
- return { ok: false, code: "spectators_full" };
3590
- }
3591
- return { ok: true };
3592
- }
3593
- inviaWatching(connessione, fotografia) {
3594
- this.adattatore.inviaSpettatore(connessione, JSON.stringify({
3595
- t: "watching",
3596
- ...fotografia,
3597
- delayMs: this.manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS2
3598
- }));
3599
- }
3600
- async riceviSpettatore(connessione, frame) {
3601
- if (Buffer.byteLength(frame, "utf8") > MASSIMO_BYTE_FRAME_STANZA2) {
3602
- this.adattatore.chiudiSpettatore(connessione, 4009, "message_too_large");
3603
- this.frameFrequenza.delete(connessione);
3604
- return;
3605
- }
3606
- const ora = Date.now();
3607
- const limite = this.frameFrequenza.controlla(connessione, false, ora);
3608
- if (!limite.accetta) {
3609
- if (limite.avvisa) this.adattatore.inviaSpettatoreSubito(connessione, JSON.stringify({
3610
- t: "error",
3611
- code: "rate_limited",
3612
- message: "Too many room messages. Excess messages are dropped."
3613
- }));
3614
- if (limite.chiudi) {
3615
- this.adattatore.chiudiSpettatore(connessione, 4008, "rate_limited");
3616
- this.frameFrequenza.delete(connessione);
3617
- }
3618
- return;
3619
- }
3620
- let message = null;
3621
- try {
3622
- const value = JSON.parse(frame);
3623
- message = typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
3624
- } catch {
3625
- }
3626
- if (message?.t === "ping" && typeof message.c === "number" && Number.isFinite(message.c)) {
3627
- this.adattatore.inviaSpettatoreSubito(
3628
- connessione,
3629
- JSON.stringify({ t: "pong", c: message.c, s: ora })
3630
- );
3631
- return;
3632
- }
3633
- if (message?.t === "resync") {
3634
- const fotografia = this.nucleo.fotografia();
3635
- if (fotografia !== null) this.inviaWatching(connessione, fotografia);
3636
- return;
3637
- }
3638
- if (message?.t === "leave") {
3639
- this.adattatore.chiudiSpettatore(connessione, 1e3, "left");
3640
- this.frameFrequenza.delete(connessione);
3641
- return;
3642
- }
3643
- this.adattatore.chiudiSpettatore(connessione, 4009, "bad_message");
3644
- this.frameFrequenza.delete(connessione);
3645
- }
3646
- async riceviVoce(connessione, playerId, role, value) {
3349
+ async riceviVoce(connessione, playerId, value) {
3647
3350
  const richiesta = this.richiestaVoce(value);
3648
3351
  if (richiesta === null) {
3649
3352
  this.inviaErroreVoce(connessione, value, "invalid_request", "The voice request is invalid.");
@@ -3691,10 +3394,6 @@ var StanzaNode = class {
3691
3394
  }
3692
3395
  if (richiesta.op === "publish") {
3693
3396
  const mic = richiesta.mic !== false;
3694
- if (role === "spectator" && mic) {
3695
- this.inviaErroreVoce(connessione, richiesta, "spectator", "Spectators cannot join voice.");
3696
- return;
3697
- }
3698
3397
  if (mic) {
3699
3398
  this.voceListeners.delete(playerId);
3700
3399
  this.voceRoster.set(playerId, {
@@ -3809,7 +3508,7 @@ var StanzaNode = class {
3809
3508
  let cambiato = false;
3810
3509
  for (const [playerId, peer] of this.voceRoster) {
3811
3510
  const player = this.nucleo.giocatoreConnesso(peer.connessione);
3812
- if (player?.id === playerId && player.role !== "spectator") continue;
3511
+ if (player?.id === playerId) continue;
3813
3512
  this.voceRoster.delete(playerId);
3814
3513
  cambiato = true;
3815
3514
  }
@@ -3845,195 +3544,13 @@ var StanzaNode = class {
3845
3544
  }
3846
3545
  };
3847
3546
  async function createNodeRoom(definition, manifest, options = {}) {
3848
- if (options.dailyDay !== void 0 && !validBoardDay2(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
3547
+ if (options.dailyDay !== void 0 && !validDay2(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
3849
3548
  const storage = await ArchivioNode.apri(options.storageFile ?? null);
3850
- const ritardoSpettatori = manifest.spectators === null ? null : manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS2;
3851
- const adattatore = new AdattatoreNode(storage, options.deposito ?? null, ritardoSpettatori, options.dailyDay);
3549
+ const adattatore = new AdattatoreNode(storage, options.dailyDay);
3852
3550
  const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
3853
3551
  return new StanzaNode(nucleo, adattatore, manifest);
3854
3552
  }
3855
3553
 
3856
- // ../kit/dist/overlay.js
3857
- var NOMI_RISERVATI3 = [
3858
- "www",
3859
- "api",
3860
- "app",
3861
- "play",
3862
- "live",
3863
- "multi",
3864
- "cdn",
3865
- "assets",
3866
- "static",
3867
- "mail",
3868
- "mx",
3869
- "ns1",
3870
- "ns2",
3871
- "autodiscover",
3872
- "_dmarc",
3873
- "admin",
3874
- "login",
3875
- "account",
3876
- "auth",
3877
- "pay",
3878
- "secure",
3879
- "support",
3880
- "help",
3881
- "blog",
3882
- "status",
3883
- "dev",
3884
- "staging",
3885
- "test",
3886
- "caisual",
3887
- "shipz"
3888
- ];
3889
- var RISERVATI3 = new Set(NOMI_RISERVATI3);
3890
- var REPLAY_MAX_BYTES3 = 10 * 1024 * 1024;
3891
- var REPLAY_MAX_DURATION_MS3 = 30 * 60 * 1e3;
3892
- var REPLAY_CHUNK_BYTES3 = 512 * 1024;
3893
- var REPLAY_RETENTION_MS3 = 30 * 24 * 60 * 60 * 1e3;
3894
- var MASSIMO_BYTE_FRAME_STANZA3 = 64 * 1024;
3895
- var words = {
3896
- watchReplay: ["Watch replay", "Guarda replay", "Ver repetici\xF3n", "Voir le replay", "Wiederholung ansehen", "Assistir \xE0 repeti\xE7\xE3o", "\u30EA\u30D7\u30EC\u30A4\u3092\u898B\u308B"],
3897
- copyReplay: ["Copy link", "Copia link", "Copiar enlace", "Copier le lien", "Link kopieren", "Copiar link", "\u30EA\u30F3\u30AF\u3092\u30B3\u30D4\u30FC"],
3898
- replayCopied: ["Link copied", "Link copiato", "Enlace copiado", "Lien copi\xE9", "Link kopiert", "Link copiado", "\u30EA\u30F3\u30AF\u3092\u30B3\u30D4\u30FC\u3057\u307E\u3057\u305F"],
3899
- replay: ["Replay", "Replay", "Repetici\xF3n", "Replay", "Wiederholung", "Repeti\xE7\xE3o", "\u30EA\u30D7\u30EC\u30A4"],
3900
- replayPlay: ["Play", "Riproduci", "Reproducir", "Lire", "Abspielen", "Reproduzir", "\u518D\u751F"],
3901
- replayPause: ["Pause", "Pausa", "Pausar", "Pause", "Pause", "Pausar", "\u4E00\u6642\u505C\u6B62"],
3902
- replaySeek: ["Position", "Posizione", "Posici\xF3n", "Position", "Position", "Posi\xE7\xE3o", "\u518D\u751F\u4F4D\u7F6E"],
3903
- replaySpeed: ["Speed", "Velocit\xE0", "Velocidad", "Vitesse", "Geschwindigkeit", "Velocidade", "\u518D\u751F\u901F\u5EA6"],
3904
- replayTruncated: ["Partial recording", "Registrazione parziale", "Grabaci\xF3n parcial", "Enregistrement partiel", "Teilweise Aufzeichnung", "Grava\xE7\xE3o parcial", "\u4E00\u90E8\u306E\u307F\u306E\u9332\u753B"],
3905
- gameUpdated: ["This game was updated", "Questo gioco \xE8 stato aggiornato", "Este juego se ha actualizado", "Ce jeu a \xE9t\xE9 mis \xE0 jour", "Dieses Spiel wurde aktualisiert", "Este jogo foi atualizado", "\u30B2\u30FC\u30E0\u304C\u66F4\u65B0\u3055\u308C\u307E\u3057\u305F"],
3906
- reloadGame: ["Reload game", "Ricarica il gioco", "Recargar el juego", "Recharger le jeu", "Spiel neu laden", "Recarregar o jogo", "\u30B2\u30FC\u30E0\u3092\u518D\u8AAD\u307F\u8FBC\u307F"],
3907
- gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo", "\u30B2\u30FC\u30E0\u306E\u8A00\u8A9E"],
3908
- loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando...", "\u8AAD\u307F\u8FBC\u307F\u4E2D..."],
3909
- 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.", "\u8AAD\u307F\u8FBC\u307F\u306B\u6642\u9593\u304C\u304B\u304B\u3063\u3066\u3044\u307E\u3059\u3002\u3057\u3070\u3089\u304F\u5F85\u3064\u304B\u3001\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
3910
- home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar", "\u30D7\u30EC\u30A4"],
3911
- homeMenu: ["Menu", "Menu", "Men\xFA", "Menu", "Men\xFC", "Menu", "\u30E1\u30CB\u30E5\u30FC"],
3912
- mode: ["Mode", "Modalit\xE0", "Modo", "Mode", "Modus", "Modo", "\u30E2\u30FC\u30C9"],
3913
- singlePlayer: ["Single player", "Giocatore singolo", "Un jugador", "Un joueur", "Einzelspieler", "Um jogador", "\u30B7\u30F3\u30B0\u30EB\u30D7\u30EC\u30A4"],
3914
- multiplayer: ["Multiplayer", "Multigiocatore", "Multijugador", "Multijoueur", "Mehrspieler", "Multijogador", "\u30DE\u30EB\u30C1\u30D7\u30EC\u30A4"],
3915
- createRoom: ["Create a room", "Crea una stanza", "Crear una sala", "Cr\xE9er une salle", "Raum erstellen", "Criar uma sala", "\u30EB\u30FC\u30E0\u3092\u4F5C\u6210"],
3916
- play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar", "\u30D7\u30EC\u30A4"],
3917
- friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos", "\u53CB\u9054\u3068\u30D7\u30EC\u30A4"],
3918
- find: ["Find a match", "Trova una partita", "Buscar partida", "Trouver une partie", "Partie finden", "Encontrar partida", "\u5BFE\u6226\u3092\u63A2\u3059"],
3919
- join: ["Join with code", "Entra con codice", "Entrar con c\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\xF3digo", "\u30B3\u30FC\u30C9\u3067\u53C2\u52A0"],
3920
- joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\xE1 sala", "\u3053\u306E\u30EB\u30FC\u30E0\u306B\u53C2\u52A0"],
3921
- watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala", "\u30EB\u30FC\u30E0\u3092\u89B3\u6226"],
3922
- resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar", "\u518D\u958B"],
3923
- room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala", "\u30EB\u30FC\u30E0"],
3924
- code: ["Room code", "Codice stanza", "C\xF3digo de sala", "Code de salle", "Raumcode", "C\xF3digo da sala", "\u30EB\u30FC\u30E0\u30B3\u30FC\u30C9"],
3925
- copy: ["Copy invite", "Copia invito", "Copiar invitaci\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite", "\u62DB\u5F85\u3092\u30B3\u30D4\u30FC"],
3926
- copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\xE9", "Einladung kopiert", "Convite copiado", "\u62DB\u5F85\u3092\u30B3\u30D4\u30FC\u3057\u307E\u3057\u305F"],
3927
- copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:", "\u3053\u306E\u30EA\u30F3\u30AF\u3092\u30B3\u30D4\u30FC\u3057\u3066\u304F\u3060\u3055\u3044\uFF1A"],
3928
- joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \xE0 la salle...", "Raum wird betreten...", "Entrando na sala...", "\u30EB\u30FC\u30E0\u306B\u53C2\u52A0\u4E2D..."],
3929
- matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores...", "\u30D7\u30EC\u30A4\u30E4\u30FC\u3092\u691C\u7D22\u4E2D..."],
3930
- queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores", "{n} / {max} \u4EBA"],
3931
- cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar", "\u30AD\u30E3\u30F3\u30BB\u30EB"],
3932
- close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\xDFen", "Fechar", "\u9589\u3058\u308B"],
3933
- back: ["Back", "Indietro", "Volver", "Retour", "Zur\xFCck", "Voltar", "\u623B\u308B"],
3934
- ready: ["Ready", "Pronto", "Listo", "Pr\xEAt", "Bereit", "Pronto", "\u6E96\u5099\u5B8C\u4E86"],
3935
- unready: ["Not ready", "Non pronto", "No listo", "Pas pr\xEAt", "Nicht bereit", "N\xE3o pronto", "\u6E96\u5099\u3092\u89E3\u9664"],
3936
- start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\xE7ar", "\u958B\u59CB"],
3937
- role: ["Role", "Ruolo", "Rol", "R\xF4le", "Rolle", "Fun\xE7\xE3o", "\u5F79\u5272"],
3938
- team: ["Team", "Squadra", "Equipo", "\xC9quipe", "Team", "Equipe", "\u30C1\u30FC\u30E0"],
3939
- host: ["Host", "Host", "Anfitrion", "H\xF4te", "Host", "Anfitri\xE3o", "\u30DB\u30B9\u30C8"],
3940
- you: ["You", "Tu", "T\xFA", "Vous", "Du", "Voc\xEA", "\u3042\u306A\u305F"],
3941
- away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente", "\u96E2\u5E2D\u4E2D"],
3942
- needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores", "\u30D7\u30EC\u30A4\u30E4\u30FC\u3092\u5F85\u3063\u3066\u3044\u307E\u3059"],
3943
- 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", "\u5168\u54E1\u306E\u6E96\u5099\u5B8C\u4E86\u3092\u5F85\u3063\u3066\u3044\u307E\u3059"],
3944
- 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", "\u5FC5\u8981\u306A\u5F79\u5272\u3092\u9078\u3093\u3067\u304F\u3060\u3055\u3044"],
3945
- needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \xE9quipes", "Teams auswahlen", "Escolha as equipes", "\u5FC5\u8981\u306A\u30C1\u30FC\u30E0\u3092\u9078\u3093\u3067\u304F\u3060\u3055\u3044"],
3946
- 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", "\u30DB\u30B9\u30C8\u3092\u5F85\u3063\u3066\u3044\u307E\u3059"],
3947
- starting: ["Starting in", "Si inizia tra", "Empieza en", "D\xE9but dans", "Start in", "Come\xE7a em", "\u958B\u59CB\u307E\u3067"],
3948
- playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando", "\u30D7\u30EC\u30A4\u4E2D"],
3949
- ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada", "\u8A66\u5408\u7D42\u4E86"],
3950
- rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos", "{n}/{max} \u4EBA\u304C\u6E96\u5099\u5B8C\u4E86"],
3951
- rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche", "\u518D\u6226\u3092\u958B\u59CB"],
3952
- won: ["You won", "Hai vinto", "Has ganado", "Vous avez gagn\xE9", "Du hast gewonnen", "Voc\xEA venceu", "\u52DD\u5229"],
3953
- lost: ["You lost", "Hai perso", "Has perdido", "Vous avez perdu", "Du hast verloren", "Voc\xEA perdeu", "\u6557\u5317"],
3954
- draw: ["Draw", "Pareggio", "Empate", "\xC9galit\xE9", "Unentschieden", "Empate", "\u5F15\u304D\u5206\u3051"],
3955
- standings: ["Standings", "Piazzamenti", "Posiciones", "R\xE9sultats", "Platzierungen", "Coloca\xE7\xF5es", "\u9806\u4F4D"],
3956
- points: ["points", "punti", "puntos", "points", "Punkte", "pontos", "\u30DD\u30A4\u30F3\u30C8"],
3957
- time: ["time", "tempo", "tiempo", "temps", "Zeit", "tempo", "\u6642\u9593"],
3958
- distance: ["distance", "distanza", "distancia", "distance", "Distanz", "dist\xE2ncia", "\u8DDD\u96E2"],
3959
- again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente", "\u3082\u3046\u4E00\u5EA6\u30D7\u30EC\u30A4"],
3960
- 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.", "\u65B0\u3057\u3044\u30EB\u30FC\u30E0\u3067\u3059\u3002\u65B0\u3057\u3044\u62DB\u5F85\u3092\u5171\u6709\u3057\u3066\u304F\u3060\u3055\u3044\u3002"],
3961
- watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo", "\u89B3\u6226\u4E2D"],
3962
- delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\xF6gerung", "Atraso de {n}s", "{n}\u79D2\u306E\u9045\u5EF6"],
3963
- exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair", "\u7D42\u4E86"],
3964
- leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\xFCbergehend verlassen", "Sair por enquanto", "\u4E00\u6642\u9000\u51FA"],
3965
- leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala", "\u30EB\u30FC\u30E0\u3092\u9000\u51FA"],
3966
- 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.", "\u30EB\u30FC\u30E0\u306F\u5F8C\u304B\u3089\u518D\u958B\u3067\u304D\u307E\u3059\u3002"],
3967
- 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.", "\u30B2\u30FC\u30E0\u306F\u7D9A\u304D\u307E\u3059\u3002\u518D\u53C2\u52A0\u3067\u304D\u308B\u6642\u9593\u306F\u9650\u3089\u308C\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002"],
3968
- 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.", "\u30EB\u30FC\u30E0\u3092\u9000\u51FA\u3059\u308B\u3068\u53C2\u52A0\u67A0\u3092\u624B\u653E\u3057\u307E\u3059\u3002"],
3969
- reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando...", "\u518D\u63A5\u7D9A\u4E2D..."],
3970
- 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", "\u5225\u306E\u30BF\u30D6\u3067\u958B\u304B\u308C\u307E\u3057\u305F"],
3971
- 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.", "\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
3972
- 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.", "\u3053\u306E\u30EB\u30FC\u30E0\u306F\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002"],
3973
- 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.", "\u30EB\u30FC\u30E0\u306F\u6E80\u54E1\u3067\u3059\u3002"],
3974
- 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.", "\u76F8\u624B\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
3975
- 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.", "6\u6587\u5B57\u306E\u30EB\u30FC\u30E0\u30B3\u30FC\u30C9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002"],
3976
- 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.", "\u30EB\u30FC\u30E0\u306F\u5909\u66F4\u3092\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093\u3067\u3057\u305F\u3002"],
3977
- unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\xFCgbar", "Indisponivel agora", "\u73FE\u5728\u5229\u7528\u3067\u304D\u307E\u305B\u3093"],
3978
- 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.", "\u63A5\u7D9A\u3067\u304D\u307E\u305B\u3093\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
3979
- 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.", "\u30EB\u30FC\u30E0\u30B3\u30FC\u30C9\u3092\u63A7\u3048\u3066\u304F\u3060\u3055\u3044\u3002\u518D\u958B\u60C5\u5831\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002"],
3980
- friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo", "\u53CB\u9054\u3068\u30D1\u30FC\u30C6\u30A3\u30FC"],
3981
- 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.", "\u30ED\u30FC\u30AB\u30EB\u30D7\u30EC\u30D3\u30E5\u30FC\u3067\u306F\u53CB\u9054\u3068\u30D1\u30FC\u30C6\u30A3\u30FC\u306F\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002"],
3982
- 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.", "\u53CB\u9054\u3068\u30D1\u30FC\u30C6\u30A3\u30FC\u3092\u5229\u7528\u3059\u308B\u306B\u306FCaisual\u306B\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u304F\u3060\u3055\u3044\u3002"],
3983
- online: ["Online", "Online", "En linea", "En ligne", "Online", "Online", "\u30AA\u30F3\u30E9\u30A4\u30F3"],
3984
- noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online", "\u30AA\u30F3\u30E9\u30A4\u30F3\u306E\u53CB\u9054\u306F\u3044\u307E\u305B\u3093"],
3985
- createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\xE9er un groupe", "Gruppe erstellen", "Criar grupo", "\u30D1\u30FC\u30C6\u30A3\u30FC\u3092\u4F5C\u6210"],
3986
- inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo", "\u30D1\u30FC\u30C6\u30A3\u30FC\u306B\u62DB\u5F85"],
3987
- leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo", "\u30D1\u30FC\u30C6\u30A3\u30FC\u3092\u9000\u51FA"],
3988
- accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar", "\u627F\u8AFE"],
3989
- decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar", "\u8F9E\u9000"],
3990
- follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se", "\u4E00\u7DD2\u306B\u53C2\u52A0"],
3991
- voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz", "\u30DC\u30A4\u30B9"],
3992
- voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz", "\u30DC\u30A4\u30B9\u306B\u53C2\u52A0"],
3993
- voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz", "\u30DC\u30A4\u30B9\u3092\u9000\u51FA"],
3994
- voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar", "\u30DF\u30E5\u30FC\u30C8"],
3995
- voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone", "\u30DF\u30E5\u30FC\u30C8\u89E3\u9664"],
3996
- voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\xE9sactiv\xE9e", "Sprachchat aus", "Voz desativada", "\u30DC\u30A4\u30B9\u30AA\u30D5"],
3997
- voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz...", "\u30DC\u30A4\u30B9\u306B\u63A5\u7D9A\u4E2D..."],
3998
- voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\xE9e", "Sprachchat verbunden", "Voz conectada", "\u30DC\u30A4\u30B9\u63A5\u7D9A\u6E08\u307F"],
3999
- voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\xE9", "Stumm", "Silenciado", "\u30DF\u30E5\u30FC\u30C8\u4E2D"],
4000
- voiceMic: ["Mic on", "Microfono attivo", "Micr\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo", "\u30DE\u30A4\u30AF\u30AA\u30F3"],
4001
- voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\xC9coute seule", "Nur zuh\xF6ren", "Somente ouvindo", "\u805E\u304F\u3060\u3051"],
4002
- voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando", "\u767A\u8A71\u4E2D"],
4003
- voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz", "\u30DC\u30A4\u30B9\u53C2\u52A0\u8005"],
4004
- 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.", "\u4ED6\u306E\u53C2\u52A0\u8005\u306F\u307E\u3060\u3044\u307E\u305B\u3093\u3002"],
4005
- voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\xE4rke f\xFCr {name}", "Volume de {name}", "{name}\u306E\u97F3\u91CF"],
4006
- 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.", "\u30DC\u30A4\u30B9\u5BFE\u5FDC\u306E\u30EB\u30FC\u30E0\u306B\u53C2\u52A0\u3057\u3066\u304F\u3060\u3055\u3044\u3002"],
4007
- 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.", "\u89B3\u6226\u4E2D\u306F\u30DC\u30A4\u30B9\u3092\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002"],
4008
- 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.", "\u30DE\u30A4\u30AF\u304C\u8A31\u53EF\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u30D6\u30E9\u30A6\u30B6\u3067\u8A31\u53EF\u3057\u3066\u304B\u3089\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
4009
- 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.", "\u3053\u306E\u30D6\u30E9\u30A6\u30B6\u306F\u30DC\u30A4\u30B9\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093\u3002"],
4010
- 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.", "\u30DC\u30A4\u30B9\u306B\u63A5\u7D9A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002"],
4011
- 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.", "\u3053\u306E\u53C2\u52A0\u8005\u306F\u30DC\u30A4\u30B9\u3092\u9000\u51FA\u3057\u307E\u3057\u305F\u3002"],
4012
- shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab", "Shift+Tab\u30B7\u30E7\u30FC\u30C8\u30AB\u30C3\u30C8"],
4013
- menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual", "Caisual\u30E1\u30CB\u30E5\u30FC"],
4014
- retry: ["Retry", "Riprova", "Reintentar", "R\xE9essayer", "Erneut versuchen", "Tentar novamente", "\u518D\u8A66\u884C"]
4015
- };
4016
- var column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));
4017
- var dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5), ja: column(6) };
4018
- var styles = `
4019
- .game-icon{width:28px;height:28px;aspect-ratio:1;object-fit:contain;border-radius:7px;flex:none;vertical-align:middle}.game-icon-title{width:36px;height:36px;border-radius:10px}
4020
- .safe-area-probe{position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)}
4021
- :host{all:initial;position:fixed;inset:0;z-index:10000;pointer-events:none;font:15px/1.45 system-ui,sans-serif;color:#f4f4f1;color-scheme:dark;--accent:#a8efc5}
4022
- [data-layout],[data-surface],.sr{pointer-events:none}*{box-sizing:border-box}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,select,input{border:1px solid #ffffff30;background:#25292b;color:inherit;border-radius:12px;min-height:44px;padding:10px 14px}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}button:hover:not(:disabled){background:#343b3a}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:3px}a{color:var(--accent)}.primary{background:var(--accent);color:var(--accent-ink,#11221b);border-color:transparent;font-weight:700}.primary:hover:not(:disabled){filter:brightness(1.1);background:var(--accent)}.quiet{background:transparent}label{display:grid;gap:6px;text-align:left}select,input{width:100%;min-width:0}h1,h2,p{margin:0}h1{font-size:clamp(26px,5vw,42px);line-height:1.1;letter-spacing:-.035em}h2{font-size:20px}small,.muted{color:#bdc5c1}.stack{display:grid;gap:16px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.row>*{flex:0 1 auto}.row .grow,.grow{flex:1}.split{display:grid;grid-template-columns:1fr 1fr;gap:10px}.pill{position:absolute;top:max(10px,env(safe-area-inset-top));right:max(10px,env(safe-area-inset-right));display:flex;height:44px;border:1px solid #ffffff35;border-radius:24px;background:#171e20eF;box-shadow:0 4px 20px #0004;pointer-events:auto;overflow:hidden}.pill button{border:0;border-radius:0;padding:8px 13px;background:transparent}.pill button:focus-visible{outline-offset:-4px}.pill small{margin-left:8px}.backdrop{position:absolute;inset:0;background:#0b151ce8;backdrop-filter:blur(10px);pointer-events:auto;display:grid;place-items:center;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));overflow:auto}.backdrop.home{background-color:#142127;background-size:contain;background-repeat:no-repeat;background-position:center}.dialog{position:relative;width:min(100%,540px);max-height:100%;overflow:auto;overscroll-behavior:contain;background:#141b1df5;border:1px solid #ffffff25;border-radius:22px;padding:24px;box-shadow:0 20px 80px #0005}.dialog.wide{width:min(100%,700px)}.top{display:flex;align-items:center;gap:12px;margin-bottom:18px}.top h2{flex:1}.tabs{display:flex;gap:6px;flex-wrap:wrap;border-bottom:1px solid #ffffff25;padding-bottom:12px}.tabs button{min-height:36px;padding:6px 10px}.tabs [aria-current=true]{border-color:var(--accent)}.roster{list-style:none;padding:0;margin:0;display:grid;gap:8px;max-height:32dvh;overflow:auto}.roster li{display:flex;align-items:center;gap:8px;padding:10px;background:#ffffff08;border-radius:10px}.roster .name{flex:1;overflow-wrap:anywhere}.badge{border:1px solid #ffffff30;border-radius:6px;padding:2px 6px;font-size:12px}.code{font-size:24px;letter-spacing:.13em;font-variant-numeric:tabular-nums}.notice,.error{border-radius:10px;padding:10px;background:#a8efc514;overflow-wrap:anywhere}.error{background:#ff8b7720;color:#ffd2c9}.countdown{font-size:88px;line-height:1;text-align:center;font-variant-numeric:tabular-nums}.ended{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));left:50%;transform:translateX(-50%);max-width:calc(100% - 24px);width:max-content;background:#171e20f5;pointer-events:auto;border:1px solid #ffffff30;border-radius:16px;padding:10px;display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap}.ended [data-rematch-players]{max-width:100%;max-height:3.2em;overflow:auto;overflow-wrap:anywhere}.standings{list-style:none;margin:0;padding:0;flex-basis:100%;max-height:20dvh;overflow:auto;font-size:13px}.standings li{display:flex;justify-content:space-between;gap:16px;overflow-wrap:anywhere}.ended{max-height:calc(100dvh - 80px);overflow:auto}.ended strong{padding:0 8px}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}.checkbox{display:flex;align-items:center;gap:8px;font-size:13px}.checkbox input{width:18px;min-height:18px}.full{width:100%}
4023
- .game-heading{display:flex;align-items:center;gap:12px;min-width:0;flex:1}.game-heading h1{font-size:28px;overflow-wrap:anywhere}.home .top{margin-bottom:12px}.game-description{font-size:13px;line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.experience-tabs{display:grid;grid-template-columns:1fr 1fr;gap:4px;padding:4px;border:1px solid #ffffff18;border-radius:14px;background:#0003}.experience-tabs button{background:transparent;border-color:transparent;font-size:14px;font-weight:600;padding:10px 8px;border-radius:10px;color:#bdc5c1}.experience-tabs [aria-selected=true]{background:#ffffff16;color:#f4f4f1;box-shadow:0 1px 4px #0003}.experience-tabs button:focus-visible{outline-offset:-3px}.home-content{gap:14px;min-width:0}.mode-details{display:grid;gap:6px;min-width:0}.mode-details h2{font-size:16px;font-weight:600}.mode-details label{font-size:13px}.mode-instructions{font-size:12px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.play-actions{gap:8px}.play-actions .primary{min-height:50px;font-size:16px}.home-links{gap:4px}.home-links button{border-color:transparent;font-size:13px}.home-links button:hover:not(:disabled){background:#ffffff0a}.resume-action{gap:4px}.resume-action small{text-align:center}.panel-footer{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-top:18px;padding-top:10px;border-top:1px solid #ffffff18;color:#bdc5c1}.panel-footer .checkbox{font-size:11px;white-space:nowrap;min-height:32px;gap:6px}.panel-footer input{margin:0;accent-color:var(--accent);width:14px;min-height:14px}.panel-footer small{min-width:0;text-align:right;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-transform:uppercase}
4024
- [hidden]{display:none!important}.voice-peers{list-style:none;margin:0;padding:0;display:grid;gap:10px}.voice-peers li{border:1px solid #ffffff25;border-radius:12px;padding:12px;display:grid;gap:8px}.voice-peers [data-speaking=true]{border-color:var(--accent)}.voice-peers input{width:100%;accent-color:var(--accent);padding:0}.voice-peers label{font-size:13px}.pill .voice-toggle{width:44px;padding:8px}.voice-toggle[data-voice-state=on][data-muted=false]{color:var(--accent)}
4025
- .boot{position:absolute;inset:0;z-index:2;isolation:isolate;display:grid;place-items:center;overflow:auto;overscroll-behavior:contain;padding:max(100px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(48px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));background:#0b151c;opacity:1;transition:opacity .4s ease;pointer-events:auto;outline:none}
4026
- .boot::before,.boot::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:-1}.boot::before{background:radial-gradient(ellipse at 50% 38%,color-mix(in srgb,var(--accent),transparent 80%),transparent 65%)}.boot::after{background:radial-gradient(ellipse at 50% 38%,#0b151c20,#0b151cd9 85%),linear-gradient(#0b151c66,#0b151cbf)}
4027
- .boot-cover{position:fixed;inset:0;z-index:-2;width:100%;height:100%;aspect-ratio:3 / 2;object-fit:contain;filter:blur(20px);opacity:.65;pointer-events:none}
4028
- .boot-brand{position:absolute;top:max(28px,env(safe-area-inset-top));left:max(32px,env(safe-area-inset-left));display:flex;align-items:center;gap:10px;font-size:14px;font-weight:650;letter-spacing:.02em;color:#f4f4f1b3}.boot-brand span{display:grid;place-items:center;width:36px;height:36px;border:1px solid #ffffff25;border-radius:12px;background:#171e20af;box-shadow:0 4px 20px #0004;color:var(--boot-accent);font-size:20px;font-weight:800}
4029
- .boot-content{width:min(100%,900px);text-align:center;display:grid;justify-items:center;gap:24px}.boot h1{max-width:16ch;font-size:clamp(44px,8vw,108px);font-weight:800;line-height:1.04;letter-spacing:-.05em;overflow-wrap:anywhere;text-wrap:balance;color:var(--boot-accent);text-shadow:0 20px 80px #0005}
4030
- .boot-progress{width:112px;height:3px;border-radius:12px;background:#ffffff20;overflow:hidden;margin-top:12px}.boot-progress span{display:block;width:44%;height:100%;border-radius:inherit;background:var(--boot-accent);animation:boot-progress 1.8s ease-in-out infinite}.boot-status{max-width:42ch;min-height:3em;font-size:14px;line-height:1.5;color:#d3dad6;text-wrap:balance}.boot-recovery{min-height:44px}.boot-recovery .row{justify-content:center}.boot-leaving{opacity:0;pointer-events:none}
4031
- @keyframes boot-progress{0%{transform:translateX(-110%)}100%{transform:translateX(340%)}}
4032
- @media(max-width:480px){.dialog{padding:18px;border-radius:18px}.split{grid-template-columns:1fr 1fr;gap:8px}.tabs{gap:4px}.tabs button{font-size:13px;padding:6px 8px}.pill button:focus-visible{outline-offset:-4px}.pill small{display:none}.ended{gap:6px}.standings{list-style:none;margin:0;padding:0;flex-basis:100%;max-height:20dvh;overflow:auto;font-size:13px}.standings li{display:flex;justify-content:space-between;gap:16px;overflow-wrap:anywhere}.ended{max-height:calc(100dvh - 80px);overflow:auto}.ended strong{font-size:13px}.ended button{padding:8px 10px;font-size:13px}.roster{max-height:28dvh}}
4033
- .replay-controls{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));left:12px;right:12px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px;background:#141b1df5;border:1px solid #ffffff30;border-radius:16px;pointer-events:auto}.replay-position{flex:1;min-width:100px}.replay-controls label{font-size:12px}.replay-controls span{font-variant-numeric:tabular-nums;font-size:13px}.replay-link{display:inline-flex;align-items:center;min-height:44px;padding:10px 14px;border-radius:12px;text-decoration:none}
4034
- @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}.boot{transition:none}.boot-progress span{animation:none;transform:translateX(65%)}}
4035
- `;
4036
-
4037
3554
  // src/dev-network.ts
4038
3555
  function simulateNetwork(socket, options, random = Math.random) {
4039
3556
  const messages = /* @__PURE__ */ new Set();
@@ -4097,21 +3614,20 @@ iframe{display:block;border:1px solid #6e8985;width:390px;height:844px;backgroun
4097
3614
  #notice{padding:0 16px;min-height:20px}
4098
3615
  </style>
4099
3616
  <header><h1>Local players</h1><label>Size <select id="size"><option value="phone">Phone 390 x 844</option><option value="desktop">Desktop 960 x 640</option></select></label>
4100
- <label>Drop seconds <input id="seconds" type="number" min="1" max="60" value="3"></label><span>Use the overlay to create or join the same room.</span></header>
3617
+ <label>Drop seconds <input id="seconds" type="number" min="1" max="60" value="3"></label><span>Use the game menu to create or join the same room.</span></header>
4101
3618
  <p id="notice" role="status"></p><main id="players"></main>
4102
3619
  <script type="module">
4103
3620
  const params = new URL(location.href).searchParams, n = Number(params.get('n') ?? 4);
4104
3621
  const notice = document.querySelector('#notice');
4105
3622
  let serial = 0;
4106
- function add(watch) {
3623
+ function add() {
4107
3624
  const section = document.createElement('section'), bar = document.createElement('div'), title = document.createElement('strong');
4108
3625
  const slot = ++serial, id = crypto.randomUUID(), frame = document.createElement('iframe');
4109
- section.dataset.player = String(slot); title.textContent = watch ? 'Spectator ' + slot : 'Player ' + slot;
4110
- const drop = document.createElement('button'), spectate = document.createElement('button');
4111
- drop.textContent = 'Drop'; spectate.textContent = 'Spectate';
3626
+ section.dataset.player = String(slot); title.textContent = 'Player ' + slot;
3627
+ const drop = document.createElement('button');
3628
+ drop.textContent = 'Drop';
4112
3629
  frame.title = title.textContent; frame.allow = 'autoplay; fullscreen; microphone; gamepad; pointer-lock';
4113
3630
  const query = new URLSearchParams({ devPlayer: id, lang: params.get('lang') || 'en' });
4114
- if (watch) query.set('devWatch', watch);
4115
3631
  frame.src = '/?' + query;
4116
3632
  drop.onclick = async () => {
4117
3633
  const seconds = Number(document.querySelector('#seconds').value);
@@ -4122,13 +3638,7 @@ function add(watch) {
4122
3638
  notice.textContent = title.textContent + ': connection interrupted for ' + seconds + ' seconds.';
4123
3639
  } catch (error) { notice.textContent = error.message; }
4124
3640
  };
4125
- spectate.onclick = () => {
4126
- const code = frame.contentWindow.caisualDev?.roomCode;
4127
- if (!code) { notice.textContent = 'Join a room in this frame first.'; return; }
4128
- if (serial >= 12) { notice.textContent = 'Use at most 12 frames per page.'; return; }
4129
- add(code);
4130
- };
4131
- bar.append(title, drop, spectate); section.append(bar, frame); document.querySelector('main').append(section);
3641
+ bar.append(title, drop); section.append(bar, frame); document.querySelector('main').append(section);
4132
3642
  }
4133
3643
  document.querySelector('#size').onchange = event => { document.body.dataset.size = event.target.value; };
4134
3644
  if (!Number.isInteger(n) || n < 1 || n > 8) notice.textContent = 'Use /__caisual/players?n=4 with an integer from 1 to 8.';
@@ -4147,82 +3657,7 @@ var MASSIMO_CORPO = 262144;
4147
3657
  var MASSIMO_FRAME_MATCH = 4096;
4148
3658
  var DURATA_STANZA_APERTA = 24 * 60 * 60 * 1e3;
4149
3659
  var VALORE_CHIAVE_MATCH = /^[A-Za-z0-9_.:-]+$/;
4150
- var PREFISSO_DEPOSITO = /^[a-z0-9_-]{0,32}$/;
4151
- var LIMITE_DEPOSITO2 = 256 * 1024;
4152
- var MASSIMO_CHIAVI_DEPOSITO = 4096;
4153
3660
  var VERSIONE_STATO_DEV = 1;
4154
- function erroreDeposito(code, message) {
4155
- return Object.assign(new Error(message), { code });
4156
- }
4157
- var DepositoDev = class {
4158
- constructor(salva) {
4159
- this.salva = salva;
4160
- }
4161
- salva;
4162
- valori = /* @__PURE__ */ new Map();
4163
- carica(valori) {
4164
- for (const [key, value] of valori) this.valori.set(key, structuredClone(value));
4165
- }
4166
- persisti() {
4167
- const valori = [...this.valori.entries()].map(([key, value]) => ({ key, value: structuredClone(value) })).sort((left, right) => left.key.localeCompare(right.key));
4168
- return this.salva(valori);
4169
- }
4170
- verificaChiave(key) {
4171
- if (typeof key !== "string" || !CHIAVE_SAVE.test(key)) {
4172
- throw erroreDeposito("store_invalid_key", "The shared store key is invalid.");
4173
- }
4174
- }
4175
- async get(key) {
4176
- this.verificaChiave(key);
4177
- const value = this.valori.get(key);
4178
- return value === void 0 ? null : structuredClone(value);
4179
- }
4180
- async set(key, value) {
4181
- this.verificaChiave(key);
4182
- let testo;
4183
- try {
4184
- testo = JSON.stringify(value);
4185
- } catch {
4186
- throw erroreDeposito("store_too_large", "The shared store value is not valid JSON.");
4187
- }
4188
- if (testo === void 0 || Buffer.byteLength(testo, "utf8") > LIMITE_DEPOSITO2) {
4189
- throw erroreDeposito("store_too_large", "The shared store value is too large.");
4190
- }
4191
- if (!this.valori.has(key) && this.valori.size >= MASSIMO_CHIAVI_DEPOSITO) {
4192
- throw erroreDeposito("store_full", "The shared store is full.");
4193
- }
4194
- this.valori.set(key, JSON.parse(testo));
4195
- await this.persisti();
4196
- }
4197
- async delete(key) {
4198
- this.verificaChiave(key);
4199
- this.valori.delete(key);
4200
- await this.persisti();
4201
- }
4202
- async list(prefix = "") {
4203
- if (typeof prefix !== "string" || !PREFISSO_DEPOSITO.test(prefix)) {
4204
- throw erroreDeposito("store_invalid_key", "The shared store prefix is invalid.");
4205
- }
4206
- return [...this.valori.keys()].filter((key) => key.startsWith(prefix)).sort().slice(0, MASSIMO_CHIAVI_DEPOSITO);
4207
- }
4208
- async increment(key, amount = 1) {
4209
- this.verificaChiave(key);
4210
- const current = this.valori.has(key) ? this.valori.get(key) : 0;
4211
- if (!Number.isSafeInteger(current) || !Number.isSafeInteger(amount)) {
4212
- throw erroreDeposito("store_not_integer", "The shared store value is not a safe integer.");
4213
- }
4214
- const result = Number(current) + amount;
4215
- if (!Number.isSafeInteger(result)) {
4216
- throw erroreDeposito("store_not_integer", "The shared store value is not a safe integer.");
4217
- }
4218
- if (!this.valori.has(key) && this.valori.size >= MASSIMO_CHIAVI_DEPOSITO) {
4219
- throw erroreDeposito("store_full", "The shared store is full.");
4220
- }
4221
- this.valori.set(key, result);
4222
- await this.persisti();
4223
- return result;
4224
- }
4225
- };
4226
3661
  var DevHttpError = class extends Error {
4227
3662
  constructor(status, code, message, hints = []) {
4228
3663
  super(message);
@@ -4313,14 +3748,14 @@ function serviceTicket(player, game, aud, secret) {
4313
3748
  exp: iat + DURATA_BIGLIETTO
4314
3749
  }, secret);
4315
3750
  }
4316
- function joinTicket(player, room, secret, aud = "room") {
3751
+ function joinTicket(player, room, secret) {
4317
3752
  const iat = currentSeconds();
4318
3753
  return signJwt({
4319
3754
  sub: player.id,
4320
3755
  name: player.name,
4321
3756
  guest: player.guest,
4322
3757
  room,
4323
- aud,
3758
+ aud: "room",
4324
3759
  iat,
4325
3760
  exp: iat + DURATA_INGRESSO
4326
3761
  }, secret);
@@ -4357,9 +3792,9 @@ function readServiceTicket(request, game, aud, secret) {
4357
3792
  }
4358
3793
  return payload;
4359
3794
  }
4360
- function readJoinTicket(token, room, aud, secret) {
3795
+ function readJoinTicket(token, room, secret) {
4361
3796
  const payload = verifyJwt(token, secret);
4362
- if (payload === null || payload.aud !== aud || payload.room !== room || typeof payload.sub !== "string" || payload.sub === "" || typeof payload.name !== "string" || payload.name === "" || typeof payload.guest !== "boolean" || !validTimes(payload, DURATA_INGRESSO)) return null;
3797
+ if (payload === null || payload.aud !== "room" || payload.room !== room || typeof payload.sub !== "string" || payload.sub === "" || typeof payload.name !== "string" || payload.name === "" || typeof payload.guest !== "boolean" || !validTimes(payload, DURATA_INGRESSO)) return null;
4363
3798
  return payload;
4364
3799
  }
4365
3800
  function readMatchTicket(token, game, secret) {
@@ -4527,10 +3962,13 @@ function parentPage(input) {
4527
3962
  <body>
4528
3963
  <iframe id="game" title="${input.slug}" data-src="${input.gameOrigin}/" allow="${input.allow}"></iframe>
4529
3964
  <script type="module">
4530
- import { creaPonteOspite, overlayConfiguration, mountOverlay, overlayLocale } from '/__caisual/overlay/v1.js';
3965
+ // In sviluppo il contenitore fa solo cio' che fa il sito: handshake, biglietti,
3966
+ // invito e lingue. Il menu, la lobby e i risultati sono dentro il gioco.
3967
+ import { creaPonteOspite } from '/__caisual/host/v1.js';
4531
3968
  const manifest = ${JSON.stringify(input.manifest).replaceAll("<", "\\u003c")};
4532
3969
  const gameOrigin = ${JSON.stringify(input.gameOrigin)};
4533
3970
  const portalOrigin = ${JSON.stringify(input.portalOrigin)};
3971
+ const gameLanguages = ${JSON.stringify(input.gameLanguages)};
4534
3972
  const frame = document.getElementById('game');
4535
3973
  const storageKey = 'caisual:dev:player';
4536
3974
  const devPlayer = new URL(location.href).searchParams.get('devPlayer');
@@ -4551,39 +3989,17 @@ function parentPage(input) {
4551
3989
  const invite = normalizedInvite && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(normalizedInvite)
4552
3990
  ? normalizedInvite
4553
3991
  : null;
4554
- const configuration = overlayConfiguration(manifest, gameOrigin + '/' + manifest.cover, invite, gameOrigin + '/' + manifest.icon);
4555
3992
  const choice = new URL(location.href).searchParams.get('lang');
4556
3993
  const languagePreferences = choice ? [choice] : (navigator.languages.length ? navigator.languages : [navigator.language]);
4557
- const language = overlayLocale(languagePreferences[0]);
4558
- document.documentElement.lang = language;
3994
+ document.documentElement.lang = languagePreferences[0] ?? 'en';
4559
3995
  const bridge = creaPonteOspite({
4560
3996
  n: 1, reload: () => window.location.reload(),
4561
3997
  finestra: window, frame, origineGioco: gameOrigin, origineLive: portalOrigin,
4562
- invite, ticket: session.portal, language, languagePreferences,
4563
- configuration,
3998
+ invite, ticket: session.portal, language: languagePreferences[0], languagePreferences, gameLanguages,
4564
3999
  rinnova: async (aud) => { session = await getSession(); return session[aud]; },
4565
4000
  onRoom(room) { window.caisualDev.roomCode = room?.code ?? null; },
4566
4001
  });
4567
- const overlay = mountOverlay({
4568
- container: document.body, frame, bridge, configuration, player: session.player,
4569
- language,
4570
- exit: () => { const url = new URL(location.href); url.searchParams.delete('invite'); url.searchParams.delete('devWatch'); location.href = url.href; },
4571
- inviteUrl: (code) => portalOrigin + '/?invite=' + code + '&lang=' + encodeURIComponent(languagePreferences[0]),
4572
- crew: { unavailable: 'local', getSnapshot: () => ({ connected: false, you: null, friends: [], party: null, invites: [], follow: null }),
4573
- subscribe: () => () => {}, party: { create() {}, invite() {}, accept() {}, decline() {}, leave() {} }, follow() {} },
4574
- });
4575
- const watchCode = new URL(location.href).searchParams.get('devWatch');
4576
- let watching = false;
4577
- bridge.subscribe((state) => {
4578
- if (watching || !state?.ready || !/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(watchCode ?? '')) return;
4579
- watching = true;
4580
- void bridge.request('room.watch', { code: watchCode }).catch((error) => {
4581
- const notice = document.createElement('p'); notice.textContent = error.message; notice.setAttribute('role', 'alert');
4582
- notice.style.cssText = 'position:fixed;bottom:12px;left:12px;right:12px;padding:12px;background:#142329;color:white;z-index:10000';
4583
- document.body.append(notice);
4584
- });
4585
- });
4586
- addEventListener('pagehide', () => { overlay?.dispose(); bridge.dispose(); }, { once: true });
4002
+ addEventListener('pagehide', () => { bridge.dispose(); }, { once: true });
4587
4003
  // Il gioco ha un'attesa limitata per il saluto: parte quando l'ospite puo' gia' rispondere.
4588
4004
  frame.src = frame.dataset.src;
4589
4005
  </script>
@@ -4599,7 +4015,7 @@ async function readGame(root) {
4599
4015
  } catch {
4600
4016
  throw new Error("caisual.json: file not found, unreadable, or invalid JSON.");
4601
4017
  }
4602
- const result = validaManifest(parsed);
4018
+ const result = validaManifestPubblicazione(parsed);
4603
4019
  if (!result.ok) {
4604
4020
  throw new Error(`caisual.json is not valid:
4605
4021
  ${result.errori.map((error) => `- ${error}`).join("\n")}`);
@@ -4652,7 +4068,6 @@ var DevService = class {
4652
4068
  this.port = port;
4653
4069
  this.day = day;
4654
4070
  this.network = network;
4655
- this.deposito = new DepositoDev((valori) => this.persistShared(valori));
4656
4071
  }
4657
4072
  root;
4658
4073
  clientRoot;
@@ -4668,7 +4083,6 @@ var DevService = class {
4668
4083
  playersById = /* @__PURE__ */ new Map();
4669
4084
  saves = /* @__PURE__ */ new Map();
4670
4085
  rooms = /* @__PURE__ */ new Map();
4671
- deposito;
4672
4086
  roomIndex = /* @__PURE__ */ new Map();
4673
4087
  roomByCode = /* @__PURE__ */ new Map();
4674
4088
  roomLoads = /* @__PURE__ */ new Map();
@@ -4684,8 +4098,7 @@ var DevService = class {
4684
4098
  await Promise.all([
4685
4099
  this.loadSecret(),
4686
4100
  this.loadRoomIndex(),
4687
- this.loadSaves(),
4688
- this.loadShared()
4101
+ this.loadSaves()
4689
4102
  ]);
4690
4103
  }
4691
4104
  statePath(name) {
@@ -4761,27 +4174,6 @@ var DevService = class {
4761
4174
  this.saves.set(id, records);
4762
4175
  }
4763
4176
  }
4764
- async loadShared() {
4765
- const value = await leggiJsonFacoltativo(this.statePath("shared.json"));
4766
- if (value === null) return;
4767
- const file = object(value);
4768
- if (file?.version !== VERSIONE_STATO_DEV || !Array.isArray(file.values) || file.values.length > MASSIMO_CHIAVI_DEPOSITO) {
4769
- throw new Error("The local shared store is invalid.");
4770
- }
4771
- const valori = /* @__PURE__ */ new Map();
4772
- for (const valueEntry of file.values) {
4773
- const entry = object(valueEntry);
4774
- if (entry === null || typeof entry.key !== "string" || !CHIAVE_SAVE.test(entry.key) || !Object.hasOwn(entry, "value") || valori.has(entry.key)) {
4775
- throw new Error("The local shared store is invalid.");
4776
- }
4777
- const serialized = JSON.stringify(entry.value);
4778
- if (serialized === void 0 || Buffer.byteLength(serialized, "utf8") > LIMITE_DEPOSITO2) {
4779
- throw new Error("The local shared store is invalid.");
4780
- }
4781
- valori.set(entry.key, JSON.parse(serialized));
4782
- }
4783
- this.deposito.carica([...valori.entries()]);
4784
- }
4785
4177
  serializePersistence(operation) {
4786
4178
  const result = this.persistenceOperations.then(operation);
4787
4179
  this.persistenceOperations = result.then(() => void 0, () => void 0);
@@ -4814,12 +4206,6 @@ var DevService = class {
4814
4206
  });
4815
4207
  });
4816
4208
  }
4817
- persistShared(valori) {
4818
- return this.serializePersistence(() => scriviJsonAtomico(this.statePath("shared.json"), {
4819
- version: VERSIONE_STATO_DEV,
4820
- values: valori
4821
- }));
4822
- }
4823
4209
  get portalOrigin() {
4824
4210
  return `http://localhost:${this.port}`;
4825
4211
  }
@@ -4855,15 +4241,8 @@ var DevService = class {
4855
4241
  this.rejectUpgrade(socket, 404, "room_not_found", "The room was not found.");
4856
4242
  return;
4857
4243
  }
4858
- const tokenRoom = url.searchParams.get("j");
4859
- const tokenWatch = url.searchParams.get("w");
4860
- if (tokenRoom !== null && tokenWatch !== null) {
4861
- this.rejectUpgrade(socket, 400, "invalid_request", "Provide either a room token or a watch token.");
4862
- return;
4863
- }
4864
- const aud = tokenWatch === null ? "room" : "watch";
4865
- const token = tokenWatch ?? tokenRoom;
4866
- const joined = token === null ? null : readJoinTicket(token, match[1], aud, this.secret);
4244
+ const token = url.searchParams.get("j");
4245
+ const joined = token === null ? null : readJoinTicket(token, match[1], this.secret);
4867
4246
  const origin = request.headers.origin;
4868
4247
  const nodeClient = origin === void 0 && request.headers["user-agent"] === "node";
4869
4248
  if (joined === null || origin !== this.gameOrigin && !nodeClient) {
@@ -4884,23 +4263,6 @@ var DevService = class {
4884
4263
  return;
4885
4264
  }
4886
4265
  this.droppedUntil.delete(identity.id);
4887
- if (aud === "watch") {
4888
- const permission2 = await localRoom.room.canWatch();
4889
- if (!permission2.ok) {
4890
- const status = permission2.code === "room_not_found" ? 404 : 409;
4891
- this.rejectUpgrade(socket, status, permission2.code, this.roomErrorMessage(permission2.code));
4892
- return;
4893
- }
4894
- try {
4895
- const websocket = this.roomSocket(request, socket, head, identity.id);
4896
- await localRoom.room.watch(websocket, identity);
4897
- } catch {
4898
- if (!socket.destroyed) {
4899
- this.rejectUpgrade(socket, 400, "invalid_request", "The WebSocket request is invalid.");
4900
- }
4901
- }
4902
- return;
4903
- }
4904
4266
  const permission = await localRoom.room.canJoin(identity);
4905
4267
  if (!permission.ok) {
4906
4268
  const status = permission.code === "room_not_found" ? 404 : 409;
@@ -5029,9 +4391,9 @@ var DevService = class {
5029
4391
  for (const [playerId, expiresAt] of localRoom.pendingMatch) {
5030
4392
  if (expiresAt <= now) localRoom.pendingMatch.delete(playerId);
5031
4393
  }
5032
- if (info.mode !== ticket.mode) continue;
4394
+ if (info.origin !== "matchmaking" || info.mode !== ticket.mode) continue;
5033
4395
  const risolta = risolviModalita(this.manifest, info.mode);
5034
- const canEnter = info.status === "lobby" || info.status === "playing" && !risolta.lobby;
4396
+ const canEnter = info.status === "lobby" || info.status === "countdown" || info.status === "playing" && !risolta.lobby;
5035
4397
  if (!canEnter || info.players + localRoom.pendingMatch.size >= risolta.players.max) continue;
5036
4398
  const permission = await localRoom.room.canJoin(playerFromTicket(ticket));
5037
4399
  if (!permission.ok) {
@@ -5055,7 +4417,8 @@ var DevService = class {
5055
4417
  try {
5056
4418
  const { roomId, localRoom } = await this.openLocalRoom(
5057
4419
  first.ticket.mode,
5058
- playerFromTicket(first.ticket)
4420
+ playerFromTicket(first.ticket),
4421
+ "matchmaking"
5059
4422
  );
5060
4423
  const expiresAt = Date.now() + DURATA_INGRESSO * 1e3;
5061
4424
  for (const waiting of selected) {
@@ -5163,7 +4526,7 @@ var DevService = class {
5163
4526
  response.setHeader("Content-Type", "text/javascript; charset=utf-8");
5164
4527
  response.setHeader("Cache-Control", "no-store");
5165
4528
  response.setHeader("X-Content-Type-Options", "nosniff");
5166
- response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.21.0\nvar 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(`\n`))throw W();for(let m of l.trimEnd().split(`\n`))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&&gt(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};\n');
4529
+ response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.22.0\nvar 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};\n');
5167
4530
  return;
5168
4531
  }
5169
4532
  const textMatch = url.pathname.match(/^\/__caisual\/text\/([^/]+)\.json$/);
@@ -5211,14 +4574,178 @@ var DevService = class {
5211
4574
  response.end(request.method === "HEAD" ? void 0 : body);
5212
4575
  }
5213
4576
  async handlePortal(request, response, url) {
5214
- if (url.pathname === "/__caisual/overlay/v1.css" && (request.method === "GET" || request.method === "HEAD")) {
5215
- response.writeHead(200, { "Content-Type": "text/css; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
5216
- response.end(request.method === "HEAD" ? void 0 : styles);
4577
+ if (url.pathname === "/__caisual/host/v1.js" && (request.method === "GET" || request.method === "HEAD")) {
4578
+ response.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
4579
+ response.end(request.method === "HEAD" ? void 0 : `// src/errors.ts
4580
+ function creaErrore(code, message, version = {}) {
4581
+ return Object.assign(new Error(message), { name: "CaisualError", code, ...version });
4582
+ }
4583
+
4584
+ // src/host/index.ts
4585
+ function record(valore) {
4586
+ return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
4587
+ }
4588
+ var CODICE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/;
4589
+ function eMessaggioReady(value) {
4590
+ return record(value)?.type === "caisual:ready";
4591
+ }
4592
+ function eRichiestaBiglietto(value) {
4593
+ const data = record(value);
4594
+ return data?.type === "caisual:ticket" && (data.aud === void 0 || data.aud === "portal" || data.aud === "live");
4595
+ }
4596
+ function stanzaDaMessaggio(value) {
4597
+ const data = record(value);
4598
+ if (data?.type !== "caisual:room") return void 0;
4599
+ if (data.room === null) return null;
4600
+ const room = record(data.room);
4601
+ return typeof room?.code === "string" && CODICE.test(room.code) ? { code: room.code } : void 0;
4602
+ }
4603
+ function creaPonteOspite(input) {
4604
+ let port = null, instance = null;
4605
+ let disposed = false, legacyReady = true;
4606
+ let polling = null, pollingEnd = null;
4607
+ let fermaCrew = null;
4608
+ const stopPolling = () => {
4609
+ if (polling !== null) input.finestra.clearInterval(polling);
4610
+ if (pollingEnd !== null) input.finestra.clearTimeout(pollingEnd);
4611
+ polling = pollingEnd = null;
4612
+ };
4613
+ const askReady = () => {
4614
+ if (!disposed && input.frame.src !== "") input.frame.contentWindow?.postMessage({ type: "caisual:ready?" }, input.origineGioco);
4615
+ };
4616
+ const poll = () => {
4617
+ stopPolling();
4618
+ polling = input.finestra.setInterval(askReady, 500);
4619
+ pollingEnd = input.finestra.setTimeout(stopPolling, 1e4);
4620
+ askReady();
4621
+ };
4622
+ const loaded = () => {
4623
+ legacyReady = true;
4624
+ poll();
4625
+ };
4626
+ const listen = (event) => {
4627
+ if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow || !eMessaggioReady(event.data)) return;
4628
+ const data = record(event.data);
4629
+ const nextInstance = typeof data.instance === "string" && data.instance.length <= 128 ? data.instance : null;
4630
+ if (port && (nextInstance !== null ? nextInstance === instance : !legacyReady)) return;
4631
+ stopPolling();
4632
+ legacyReady = false;
4633
+ instance = nextInstance;
4634
+ fermaCrew?.();
4635
+ fermaCrew = null;
4636
+ port?.close();
4637
+ input.onRoom(null);
4638
+ const channel = input.creaCanale?.() ?? new MessageChannel();
4639
+ const currentPort = channel.port1;
4640
+ port = currentPort;
4641
+ const current = () => !disposed && port === currentPort;
4642
+ currentPort.onmessage = (event2) => {
4643
+ if (!current()) return;
4644
+ const data2 = record(event2.data);
4645
+ if (eRichiestaBiglietto(data2)) {
4646
+ const aud = data2?.aud === "live" ? "live" : "portal";
4647
+ void input.rinnova(aud).then((ticket) => {
4648
+ if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, ticket });
4649
+ }).catch(() => {
4650
+ if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, error: "offline" });
4651
+ });
4652
+ return;
4653
+ }
4654
+ if (data2?.type === "caisual:reload") {
4655
+ const target = record(data2.target);
4656
+ const code = typeof target?.code === "string" && CODICE.test(target.code) ? target.code : void 0;
4657
+ 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;
4658
+ input.reload?.(code || roomId ? { code, roomId } : void 0);
4659
+ return;
4660
+ }
4661
+ const room = stanzaDaMessaggio(data2);
4662
+ if (room !== void 0) {
4663
+ input.onRoom(room);
4664
+ return;
4665
+ }
4666
+ if (data2?.type === "caisual:crew") gestisciCrew(data2, currentPort, current);
4667
+ };
4668
+ currentPort.start();
4669
+ input.frame.contentWindow?.postMessage({
4670
+ type: "caisual:hello",
4671
+ n: input.n,
4672
+ ticket: input.ticket,
4673
+ live: input.origineLive,
4674
+ invite: input.invite,
4675
+ ...input.language ? { language: input.language } : {},
4676
+ ...input.languagePreferences ? { languagePreferences: [...input.languagePreferences] } : {},
4677
+ ...input.gameLanguages ? { gameLanguages: [...input.gameLanguages] } : {}
4678
+ }, input.origineGioco, [channel.port2]);
4679
+ };
4680
+ function gestisciCrew(data, porta, current) {
4681
+ const crew = input.crew;
4682
+ if (!crew) {
4683
+ if (data.op === "subscribe") porta.postMessage({ type: "caisual:crew-state", state: null });
5217
4684
  return;
5218
4685
  }
5219
- if (url.pathname === "/__caisual/overlay/v1.js" && (request.method === "GET" || request.method === "HEAD")) {
5220
- response.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
5221
- response.end(request.method === "HEAD" ? void 0 : '// ../contracts/src/slug.ts\nvar NOMI_RISERVATI = [\n "www",\n "api",\n "app",\n "play",\n "live",\n "multi",\n "cdn",\n "assets",\n "static",\n "mail",\n "mx",\n "ns1",\n "ns2",\n "autodiscover",\n "_dmarc",\n "admin",\n "login",\n "account",\n "auth",\n "pay",\n "secure",\n "support",\n "help",\n "blog",\n "status",\n "dev",\n "staging",\n "test",\n "caisual",\n "shipz"\n];\nvar RISERVATI = new Set(NOMI_RISERVATI);\nvar SLUG_NUOVO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nvar SLUG_STORICO = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\nfunction isValidSlug(value) {\n return value.length >= 3 && value.length <= 32 && SLUG_NUOVO.test(value) || SLUG_STORICO.test(value);\n}\nfunction isReservedSlug(value) {\n return RISERVATI.has(value);\n}\n\n// ../contracts/src/i18n.ts\nfunction normalizeLanguage(value) {\n if (typeof value !== "string" || value.length > 128) return null;\n try {\n return Intl.getCanonicalLocales(value)[0] ?? null;\n } catch {\n return null;\n }\n}\nfunction manifestLanguages(manifest) {\n return manifest.languages?.length ? [...manifest.languages] : [manifest.language ?? "en"];\n}\nfunction languageFallbacks(language, defaultLanguage = "en") {\n const result = [];\n let tag = normalizeLanguage(language);\n while (tag) {\n result.push(tag);\n const parts = tag.split("-");\n parts.pop();\n if (parts.at(-1)?.length === 1) parts.pop();\n tag = parts.join("-");\n }\n result.push(normalizeLanguage(defaultLanguage) ?? defaultLanguage);\n return [...new Set(result)];\n}\nfunction resolveText(value, language, defaultLanguage = "en", key = "") {\n if (typeof value === "string") return value;\n if (value) {\n for (const tag of languageFallbacks(language, defaultLanguage)) {\n const name = Object.keys(value).find((name2) => name2.toLowerCase() === tag.toLowerCase());\n if (name !== void 0 && typeof value[name] === "string") return value[name];\n }\n }\n return key;\n}\n\n// ../contracts/src/manifest.ts\nfunction risolviModalita(manifest, mode) {\n const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);\n if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");\n return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };\n}\nfunction risolviPresentazione(manifest, mode, language = manifestLanguages(manifest)[0]) {\n risolviModalita(manifest, mode);\n const scelta = manifest.modes.find((voce) => voce.id === mode);\n return {\n execution: scelta?.execution ?? null,\n label: resolveText(scelta?.label, language, manifestLanguages(manifest)[0], scelta?.id ?? manifest.name ?? "Play"),\n instructions: resolveText(scelta?.instructions, language, manifestLanguages(manifest)[0]) || null\n };\n}\nvar TETTO_GIOCATORI = 24;\nvar RITARDO_SPETTATORI_MS = 3e3;\nvar MASSIMO_CLASSIFICHE = 32;\nvar CAMPI = /* @__PURE__ */ new Set([\n "overlay",\n "manifest",\n "id",\n "name",\n "description",\n "cover",\n "card",\n "icon",\n "screenshots",\n "tags",\n "languages",\n "language",\n "platform",\n "orientation",\n "input",\n "visibility",\n "network",\n "isolated",\n "requires",\n "players",\n "lobby",\n "persistent",\n "replays",\n "spectators",\n "boards",\n "roles",\n "teams",\n "voice",\n "modes"\n]);\nvar INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);\nvar PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);\nvar ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);\nvar VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);\nvar VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);\nvar PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);\nvar TAG = /^[a-z0-9-]+$/;\nvar ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nvar CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;\nvar ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;\nfunction oggetto(value) {\n if (typeof value !== "object" || value === null || Array.isArray(value)) return null;\n return value;\n}\nfunction percorsoRelativo(value) {\n if (value === "" || value.startsWith("/") || value.includes("\\\\") || value.includes("\\0")) return false;\n if (value.includes("?") || value.includes("#")) return false;\n const parti = value.split("/");\n if (parti.some((parte) => parte === "" || parte === "." || parte === "..")) return false;\n try {\n const decoded = parti.map((parte) => decodeURIComponent(parte));\n return !decoded.some((parte) => parte === "" || parte === "." || parte === ".." || parte.includes("/"));\n } catch {\n return false;\n }\n}\nfunction hostValido(value) {\n if (value.length === 0 || value.length > 253) return false;\n if (value.includes("://") || /[/:?#@]/.test(value)) return false;\n const parti = value.split(".");\n return parti.every(\n (parte) => parte.length >= 1 && parte.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(parte)\n );\n}\nfunction interoTra(value, min, max) {\n return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;\n}\nfunction stringaDefault(dati, campo, valoreDefault, errori) {\n const value = dati[campo];\n if (value === void 0) return valoreDefault;\n if (typeof value !== "string") {\n errori.push(`${campo}: must be a string.`);\n return valoreDefault;\n }\n return value;\n}\nfunction testoFacoltativo(value, key, max, path, errors) {\n if (value[key] === void 0) return void 0;\n const check = (text2, field2) => {\n if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\\r\\n\\u0000-\\u001f]/.test(text2)) {\n errors.push(`${field2}: must contain 1-${max} characters on one line.`);\n return void 0;\n }\n return text2.trim();\n };\n const text = value[key], field = path ? `${path}.${key}` : key;\n if (typeof text === "string") return check(text, field);\n const translations = oggetto(text);\n if (!translations || Object.keys(translations).length === 0) {\n errors.push(`${field}: must be a string or a non-empty language-to-text object.`);\n return void 0;\n }\n const result = {};\n for (const [raw, text2] of Object.entries(translations)) {\n const tag = normalizeLanguage(raw);\n if (!tag) {\n errors.push(`${field}.${raw}: must be a BCP 47 language tag.`);\n continue;\n }\n if (Object.hasOwn(result, tag)) errors.push(`${field}.${raw}: duplicate language.`);\n const checked = check(text2, `${field}.${raw}`);\n if (checked !== void 0) result[tag] = checked;\n }\n return result;\n}\nfunction validaManifest(valore) {\n const errori = [];\n const dati = oggetto(valore);\n if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };\n for (const campo of Object.keys(dati)) {\n if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);\n }\n if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");\n else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");\n const id = stringaDefault(dati, "id", "", errori);\n if (dati.id === void 0) errori.push("id: is required.");\n else if (typeof dati.id === "string") {\n if (!isValidSlug(id)) {\n errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters.");\n } else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");\n }\n const name = stringaDefault(dati, "name", "", errori);\n if (dati.name === void 0) errori.push("name: is required.");\n else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {\n errori.push("name: must contain 1-60 characters.");\n }\n const description = dati.description === "" ? "" : testoFacoltativo(dati, "description", 500, "", errori) ?? "";\n const immagini = { cover: "", card: "", icon: "" };\n const usati = /* @__PURE__ */ new Set();\n for (const campo of ["cover", "card", "icon"]) {\n const path = dati[campo];\n if (path === void 0 || path === null) errori.push(`${campo}: is required.`);\n else if (typeof path !== "string" || !percorsoRelativo(path)) errori.push(`${campo}: must be a relative file path inside client/ without query, fragment, or parent segments.`);\n else {\n if (!/\\.(png|jpe?g|webp)$/i.test(path)) errori.push(`${campo}: must be a PNG, JPEG or WebP file.`);\n const canonical = decodeURIComponent(path);\n if (usati.has(canonical)) errori.push(`${campo}: each image must use a different file; cover, card and icon cannot share a path.`);\n usati.add(canonical);\n immagini[campo] = path;\n }\n }\n const { cover, card, icon } = immagini;\n const screenshots = [];\n if (dati.screenshots !== void 0) {\n if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");\n else {\n if (dati.screenshots.length > 8) errori.push("screenshots: must contain at most 8 paths.");\n for (const [indice, value] of dati.screenshots.entries()) {\n if (typeof value !== "string" || !percorsoRelativo(value)) {\n errori.push(`screenshots[${indice}]: must be a relative file path without query, fragment, or parent segments.`);\n } else screenshots.push(value);\n }\n }\n }\n const tags = [];\n if (dati.tags !== void 0) {\n if (!Array.isArray(dati.tags)) errori.push("tags: must be an array.");\n else {\n if (dati.tags.length > 10) errori.push("tags: must contain at most 10 tags.");\n for (const [indice, value] of dati.tags.entries()) {\n if (typeof value !== "string" || value.length > 24 || !TAG.test(value)) {\n errori.push(`tags[${indice}]: must be 1-24 lowercase letters, digits, or hyphens.`);\n } else tags.push(value);\n }\n }\n }\n const legacyLanguage = stringaDefault(dati, "language", "en", errori);\n if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {\n errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");\n }\n const languages2 = [];\n if (!Array.isArray(dati.languages) || dati.languages.length === 0) {\n errori.push("languages: must be a non-empty array of BCP 47 language tags.");\n } else for (const [index, raw] of dati.languages.entries()) {\n const tag = normalizeLanguage(raw);\n if (!tag) errori.push(`languages[${index}]: must be a BCP 47 language tag.`);\n else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);\n else languages2.push(tag);\n }\n if (!languages2.includes("en")) errori.push("languages: English is always required alongside the game\'s own languages.");\n const language = languages2[0] ?? legacyLanguage;\n if (typeof description === "object") {\n for (const tag of Object.keys(description)) {\n if (!languages2.includes(tag)) errori.push(`description.${tag}: language must be declared in languages.`);\n }\n }\n if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {\n errori.push("language: must match the first entry in languages when both are present.");\n }\n let platform = "both";\n if (dati.platform === void 0) errori.push("platform: is required.");\n else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {\n errori.push("platform: must be desktop, mobile, or both.");\n } else platform = dati.platform;\n let orientation = "landscape";\n if (dati.orientation !== void 0) {\n if (typeof dati.orientation !== "string" || !ORIENTATION.has(dati.orientation)) {\n errori.push("orientation: must be landscape or portrait.");\n } else orientation = dati.orientation;\n }\n const input = [];\n if (dati.input !== void 0) {\n if (!Array.isArray(dati.input)) errori.push("input: must be an array.");\n else for (const [indice, value] of dati.input.entries()) {\n if (typeof value !== "string" || !INPUT.has(value)) {\n errori.push(`input[${indice}]: must be keyboard, mouse, touch, or gamepad.`);\n } else if (input.includes(value)) errori.push(`input[${indice}]: duplicate value ${value}.`);\n else input.push(value);\n }\n }\n let visibility = "public";\n if (dati.visibility !== void 0) {\n if (typeof dati.visibility !== "string" || !VISIBILITY.has(dati.visibility)) {\n errori.push("visibility: must be public or unlisted.");\n } else visibility = dati.visibility;\n }\n const network = [];\n if (dati.network !== void 0) {\n if (!Array.isArray(dati.network)) errori.push("network: must be an array of host names.");\n else for (const [indice, value] of dati.network.entries()) {\n if (typeof value !== "string" || !hostValido(value)) {\n errori.push(`network[${indice}]: must be a host name without scheme, port, path, query, or fragment.`);\n } else if (network.includes(value)) errori.push(`network[${indice}]: duplicate host ${value}.`);\n else network.push(value);\n }\n }\n if (dati.isolated !== void 0) {\n if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");\n }\n const requires = {\n webgl2: false,\n webgpu: false,\n wasm: false,\n threads: false,\n memoryMb: null,\n performance: "light"\n };\n if (dati.requires !== void 0) {\n const value = oggetto(dati.requires);\n if (value === null) errori.push("requires: must be an object.");\n else {\n for (const campo of Object.keys(value)) {\n if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {\n errori.push(`requires.${campo}: unknown field.`);\n }\n }\n for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {\n if (value[campo] === void 0) continue;\n if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);\n else requires[campo] = value[campo];\n }\n if (value.memoryMb !== void 0) {\n if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {\n errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");\n } else requires.memoryMb = value.memoryMb;\n }\n if (value.performance !== void 0) {\n if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {\n errori.push("requires.performance: must be light, medium, or heavy.");\n } else requires.performance = value.performance;\n }\n }\n }\n let players = { min: 1, max: 1 };\n if (dati.players !== void 0) {\n const value = oggetto(dati.players);\n if (value === null) errori.push("players: must be an object with min and max.");\n else {\n for (const campo of Object.keys(value)) {\n if (campo !== "min" && campo !== "max") errori.push(`players.${campo}: unknown field.`);\n }\n if (!interoTra(value.min, 1, TETTO_GIOCATORI)) errori.push(`players.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);\n if (!interoTra(value.max, 1, TETTO_GIOCATORI)) errori.push(`players.max: must be an integer from 1 to ${TETTO_GIOCATORI} in manifest version 1.`);\n if (interoTra(value.min, 1, TETTO_GIOCATORI) && interoTra(value.max, 1, TETTO_GIOCATORI)) {\n if (value.min > value.max) errori.push("players.max: must be greater than or equal to players.min.");\n else players = { min: value.min, max: value.max };\n }\n }\n }\n let lobby = false;\n if (dati.lobby !== void 0) {\n if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");\n else lobby = dati.lobby;\n }\n let persistent = false;\n if (dati.persistent !== void 0) {\n if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");\n else persistent = dati.persistent;\n }\n const replays = dati.replays === true;\n if (dati.replays !== void 0 && typeof dati.replays !== "boolean") errori.push("replays: must be a boolean.");\n let spectators = { delayMs: RITARDO_SPETTATORI_MS };\n if (dati.spectators === false || dati.spectators === null) spectators = null;\n else if (dati.spectators !== void 0 && dati.spectators !== true) {\n const value = oggetto(dati.spectators);\n if (value === null) {\n errori.push("spectators: must be a boolean or an object with delayMs.");\n } else {\n for (const campo of Object.keys(value)) {\n if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);\n }\n if (!interoTra(value.delayMs, 0, 3e4)) {\n errori.push("spectators.delayMs: must be an integer from 0 to 30000.");\n } else spectators = { delayMs: value.delayMs };\n }\n }\n let overlay = null;\n if (dati.overlay !== void 0 && dati.overlay !== null) {\n const value = oggetto(dati.overlay);\n if (value === null) errori.push("overlay: must be an object or null.");\n else {\n for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);\n if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");\n if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {\n errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");\n }\n overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };\n }\n }\n const boards = {};\n if (dati.boards !== void 0) {\n const value = oggetto(dati.boards);\n if (value === null) errori.push("boards: must be an object of board ids.");\n else {\n if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {\n errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);\n }\n for (const [id2, raw] of Object.entries(value)) {\n let valido = true;\n if (!ID_CLASSIFICA.test(id2)) {\n errori.push(`boards.${id2}: invalid board id.`);\n valido = false;\n }\n const board = oggetto(raw);\n if (board === null) {\n errori.push(`boards.${id2}.source: must be "client" or "server".`);\n continue;\n }\n for (const campo of Object.keys(board)) {\n if (!["source", "label", "periods", "day"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);\n }\n if (board.source !== "client" && board.source !== "server") {\n errori.push(`boards.${id2}.source: must be "client" or "server".`);\n valido = false;\n }\n if (board.day !== void 0 && board.day !== "submit" && board.day !== "start") errori.push(`boards.${id2}.day: must be "submit" or "start".`);\n if (board.day === "start" && board.source !== "server") errori.push(`boards.${id2}.day: start requires source "server".`);\n const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);\n let periods = ["all-time"];\n if (board.periods !== void 0) {\n if (!Array.isArray(board.periods) || board.periods.length < 1 || board.periods.length > 2 || board.periods.some((period) => period !== "daily" && period !== "all-time") || new Set(board.periods).size !== board.periods.length) {\n errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);\n } else periods = [...board.periods];\n }\n if (valido) Object.defineProperty(boards, id2, { value: {\n source: board.source,\n periods,\n ...board.day === void 0 ? {} : { day: board.day },\n ...label === void 0 ? {} : { label }\n }, enumerable: true, configurable: true, writable: true });\n }\n }\n }\n const roles = [];\n if (dati.roles !== void 0) {\n if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");\n else {\n const ids = /* @__PURE__ */ new Set();\n for (const [indice, raw] of dati.roles.entries()) {\n const value = oggetto(raw);\n if (value === null) {\n errori.push(`roles[${indice}]: must be an object.`);\n continue;\n }\n for (const campo of Object.keys(value)) {\n if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);\n }\n const idRuolo = value.id;\n const min = value.min;\n const max = value.max;\n let valido = true;\n if (typeof idRuolo !== "string" || idRuolo.length > 32 || !ID_INTERNO.test(idRuolo)) {\n errori.push(`roles[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);\n valido = false;\n } else if (ids.has(idRuolo)) {\n errori.push(`roles[${indice}].id: duplicate role ${idRuolo}.`);\n valido = false;\n } else ids.add(idRuolo);\n if (!interoTra(min, 0, TETTO_GIOCATORI)) {\n errori.push(`roles[${indice}].min: must be an integer from 0 to ${TETTO_GIOCATORI}.`);\n valido = false;\n }\n if (max !== void 0 && !interoTra(max, 0, TETTO_GIOCATORI)) {\n errori.push(`roles[${indice}].max: must be an integer from 0 to ${TETTO_GIOCATORI} when present.`);\n valido = false;\n }\n if (typeof min === "number" && typeof max === "number" && min > max) {\n errori.push(`roles[${indice}].max: must be greater than or equal to min.`);\n valido = false;\n }\n const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);\n if (valido) roles.push({\n id: idRuolo,\n min,\n ...max === void 0 ? {} : { max },\n ...label === void 0 ? {} : { label }\n });\n }\n }\n }\n let teams = null;\n if (dati.teams !== void 0 && dati.teams !== null) {\n const value = oggetto(dati.teams);\n if (value === null) errori.push("teams: must be null or an object with min and max.");\n else {\n for (const campo of Object.keys(value)) {\n if (campo !== "min" && campo !== "max") errori.push(`teams.${campo}: unknown field.`);\n }\n if (!interoTra(value.min, 2, TETTO_GIOCATORI)) errori.push(`teams.min: must be an integer from 2 to ${TETTO_GIOCATORI}.`);\n if (!interoTra(value.max, 2, TETTO_GIOCATORI)) errori.push(`teams.max: must be an integer from 2 to ${TETTO_GIOCATORI}.`);\n if (interoTra(value.min, 2, TETTO_GIOCATORI) && interoTra(value.max, 2, TETTO_GIOCATORI)) {\n if (value.min > value.max) errori.push("teams.max: must be greater than or equal to teams.min.");\n else teams = { min: value.min, max: value.max };\n }\n }\n }\n let voice = "none";\n if (dati.voice !== void 0) {\n if (typeof dati.voice !== "string" || !VOICE.has(dati.voice)) {\n errori.push("voice: must be none, room, team, or proximity.");\n } else voice = dati.voice;\n }\n const modes = [];\n if (dati.modes !== void 0) {\n if (!Array.isArray(dati.modes)) errori.push("modes: must be an array.");\n else {\n const ids = /* @__PURE__ */ new Set();\n for (const [indice, raw] of dati.modes.entries()) {\n const value = oggetto(raw);\n if (value === null) {\n errori.push(`modes[${indice}]: must be an object.`);\n continue;\n }\n for (const campo of Object.keys(value)) {\n if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);\n }\n if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {\n errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);\n continue;\n }\n if (ids.has(value.id)) {\n errori.push(`modes[${indice}].id: duplicate mode ${value.id}.`);\n continue;\n }\n ids.add(value.id);\n const modo = { id: value.id };\n for (const [key2, max] of [["label", 48], ["instructions", 160]]) {\n const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);\n if (text !== void 0) modo[key2] = text;\n }\n if (value.execution !== void 0) {\n if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);\n else modo.execution = value.execution;\n }\n if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);\n if (value.players !== void 0) {\n const campo = `modes[${indice}].players`;\n const range = oggetto(value.players);\n if (range === null) errori.push(`${campo}: must be an object with min and max.`);\n else {\n for (const key2 of Object.keys(range)) {\n if (key2 !== "min" && key2 !== "max") errori.push(`${campo}.${key2}: unknown field.`);\n }\n if (!interoTra(range.min, 1, TETTO_GIOCATORI)) errori.push(`${campo}.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);\n if (!interoTra(range.max, 1, TETTO_GIOCATORI)) errori.push(`${campo}.max: must be an integer from 1 to ${TETTO_GIOCATORI}.`);\n if (interoTra(range.min, 1, TETTO_GIOCATORI) && interoTra(range.max, 1, TETTO_GIOCATORI)) {\n if (range.min > range.max) errori.push(`${campo}.max: must be greater than or equal to min.`);\n else modo.players = { min: range.min, max: range.max };\n }\n }\n }\n if (value.lobby !== void 0) {\n if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);\n else modo.lobby = value.lobby;\n }\n if (modo.execution === "local") {\n const range = modo.players ?? players;\n if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);\n if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);\n if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);\n }\n if (value.matchmaking === void 0) {\n modes.push(modo);\n continue;\n }\n const matchmaking = oggetto(value.matchmaking);\n if (matchmaking === null) {\n errori.push(`modes[${indice}].matchmaking: must be an object.`);\n continue;\n }\n for (const campo of Object.keys(matchmaking)) {\n if (!["key", "timeoutMs", "defaults"].includes(campo)) {\n errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);\n }\n }\n let valido = true;\n const key = [];\n if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {\n errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);\n valido = false;\n } else for (const [keyIndice, item] of matchmaking.key.entries()) {\n if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {\n errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);\n valido = false;\n } else if (key.includes(item)) {\n errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);\n valido = false;\n } else key.push(item);\n }\n if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {\n errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);\n valido = false;\n }\n let defaults;\n if (matchmaking.defaults !== void 0) {\n const values = oggetto(matchmaking.defaults);\n if (values === null || Object.keys(values).length !== key.length || key.some((field) => !Object.hasOwn(values, field))) {\n errori.push(`modes[${indice}].matchmaking.defaults: must contain exactly the declared key fields.`);\n } else {\n defaults = {};\n for (const [field, value2] of Object.entries(values)) {\n if (!(typeof value2 === "string" && value2.length >= 1 && value2.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value2)) && !Number.isSafeInteger(value2)) {\n errori.push(`modes[${indice}].matchmaking.defaults.${field}: must be a string of 1-64 characters or a safe integer.`);\n } else Object.defineProperty(defaults, field, { value: value2, enumerable: true });\n }\n }\n }\n if (valido) modes.push({ ...modo, matchmaking: {\n ...defaults === void 0 ? {} : { defaults },\n key,\n timeoutMs: matchmaking.timeoutMs\n } });\n }\n }\n }\n if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");\n if (errori.length > 0) return { ok: false, errori };\n return { ok: true, manifest: {\n manifest: 1,\n overlay,\n id,\n name,\n description,\n cover,\n card,\n icon,\n screenshots,\n tags,\n languages: languages2,\n language,\n platform,\n orientation,\n input,\n visibility,\n network,\n requires,\n players,\n lobby,\n persistent,\n replays,\n spectators,\n boards,\n roles,\n teams,\n voice,\n modes\n } };\n}\n\n// ../contracts/src/replay.ts\nvar REPLAY_MAX_BYTES = 10 * 1024 * 1024;\nvar REPLAY_MAX_DURATION_MS = 30 * 60 * 1e3;\nvar REPLAY_CHUNK_BYTES = 512 * 1024;\nvar REPLAY_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;\nvar REPLAY_ID = /^[A-Za-z0-9_-]{22}$/;\n\n// ../contracts/src/overlay.ts\nvar OVERLAY_PANELS = ["home", "room", "invite", "friends", "voice"];\nfunction overlayConfiguration(manifest, coverUrl = null, invite = null, iconUrl = null) {\n const validated = validaManifest(manifest);\n if (!validated.ok) throw new Error("The overlay manifest is invalid.");\n const { boards: _legacy, ...visible } = validated.manifest;\n return { manifest: visible, coverUrl, iconUrl, invite };\n}\nfunction record(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;\n}\nfunction validSafeArea(value) {\n const area = record(value);\n 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);\n}\nfunction validOverlayView(value) {\n const data = record(value);\n 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) => {\n const rect = record(value2);\n 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);\n });\n}\nfunction validOverlayRequest(value) {\n const message = record(value), args = record(message?.args);\n if (message?.type !== "caisual:overlay" || message.v !== 1 || typeof message.epoch !== "string" || message.epoch.length < 1 || message.epoch.length > 128 || typeof message.requestId !== "string" || !(/^[1-9][0-9]{0,15}$/.test(message.requestId) && Number.isSafeInteger(Number(message.requestId))) || args === null) return false;\n if (Object.keys(message).some((key) => !["type", "v", "epoch", "requestId", "sessionId", "op", "args"].includes(key)) || !(message.sessionId === void 0 || message.sessionId === null || typeof message.sessionId === "string" && /^[1-9][0-9]{0,15}$/.test(message.sessionId))) return false;\n const keys = (...allowed) => Object.keys(args).every((key) => allowed.includes(key));\n const text = (key) => typeof args[key] === "string" && args[key].length >= 1 && args[key].length <= 64;\n switch (message.op) {\n case "replay.play":\n case "replay.pause":\n return keys() && typeof message.sessionId === "string";\n case "replay.seek":\n return keys("positionMs") && typeof message.sessionId === "string" && typeof args.positionMs === "number" && Number.isFinite(args.positionMs) && args.positionMs >= 0 && args.positionMs <= REPLAY_MAX_DURATION_MS;\n case "replay.speed":\n return keys("speed") && typeof message.sessionId === "string" && [0.5, 1, 2, 4].includes(Number(args.speed)) && typeof args.speed === "number";\n case "local.start":\n return keys("mode") && text("mode");\n case "room.create":\n return keys("mode") && (args.mode === null || text("mode"));\n case "room.join":\n return keys("code") && (args.code === void 0 || text("code"));\n case "room.watch":\n return keys("code") && text("code");\n case "room.match": {\n const key = record(args.key);\n return keys("mode", "key") && text("mode") && (args.key === void 0 || key !== null && Object.keys(key).length <= 8 && Object.values(key).every((v) => typeof v === "string" && v.length >= 1 && v.length <= 64 || typeof v === "number" && Number.isSafeInteger(v)));\n }\n case "room.ready":\n return keys("ready") && typeof args.ready === "boolean";\n case "room.role":\n case "room.requestRole":\n return keys("role") && text("role");\n case "room.team":\n return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;\n case "room.restart":\n case "room.start":\n case "session.cancel":\n case "session.leave":\n case "session.disconnect":\n case "session.resume":\n return keys();\n case "voice.join":\n case "voice.leave":\n return keys() && typeof message.sessionId === "string";\n case "voice.mute":\n return keys("muted") && typeof args.muted === "boolean" && typeof message.sessionId === "string";\n case "voice.setVolume":\n return keys("playerId", "volume") && typeof message.sessionId === "string" && typeof args.playerId === "string" && args.playerId.length > 0 && args.playerId.length <= 128 && typeof args.volume === "number" && Number.isFinite(args.volume) && args.volume >= 0 && args.volume <= 1;\n case "overlay.view":\n return validOverlayView(args);\n default:\n return false;\n }\n}\nfunction validOverlaySessionState(value) {\n const data = record(value);\n const exact = (v, keys) => v !== null && Object.keys(v).length === keys.length && Object.keys(v).every((key) => keys.includes(key));\n const text = (v) => typeof v === "string" && v.length <= 128;\n const nullable = (v) => v === null || text(v);\n const finite = (v) => typeof v === "number" && Number.isFinite(v);\n if (!data || !exact(data, ["kind", "id", "mode", "localStatus", "ready", "capabilities", "room", "waiting", "resume", "resumeError", ..."voice" in data ? ["voice"] : []])) return false;\n if (data.voice !== void 0 && data.voice !== null && (data.kind !== "room" || !record(data.room) || !validOverlayVoice(data.voice))) return false;\n const capabilities = record(data.capabilities), room = record(data.room), waiting = record(data.waiting), resume = record(data.resume);\n if (!["boot", "home", "attaching", "matching", "local", "room", "watch"].includes(String(data.kind)) || !nullable(data.id) || !nullable(data.mode) || ![null, "playing", "ended"].includes(data.localStatus) || typeof data.ready !== "boolean" || typeof data.resumeError !== "boolean" || !exact(capabilities, ["local", "rooms", "overlay", "requestRole"]) || !Object.values(capabilities).every((v) => typeof v === "boolean")) return false;\n if (data.waiting !== null && (!exact(waiting, ["players", "min", "max"]) || !Object.values(waiting).every((v) => Number.isInteger(v) && Number(v) >= 0 && Number(v) <= 24))) return false;\n if (data.resume !== null && (!exact(resume, ["version", "code", "mode", "updatedAt"]) || resume.version !== 1 || !text(resume.code) || !nullable(resume.mode) || !finite(resume.updatedAt))) return false;\n if (data.room === null) return true;\n if (!exact(room, ["code", "mode", "status", "host", "you", "players", "countdownAt", "connection", "closedCode", "limits", "lobby", "persistent", "delayMs", "requestRole", ..."replay" in (room ?? {}) ? ["replay"] : [], ..."replayId" in (room ?? {}) ? ["replayId"] : [], ..."result" in (room ?? {}) ? ["result"] : [], ..."rematch" in (room ?? {}) ? ["rematch"] : []]) || !room) return false;\n if (room.replayId !== void 0 && (typeof room.replayId !== "string" || !REPLAY_ID.test(room.replayId))) return false;\n if (room.replay !== void 0) {\n const playback = record(room.replay);\n if (data.kind !== "watch" || !exact(playback, ["positionMs", "durationMs", "paused", "speed", "truncated"]) || !playback || !finite(playback.positionMs) || !finite(playback.durationMs) || Number(playback.positionMs) < 0 || Number(playback.positionMs) > Number(playback.durationMs) || Number(playback.durationMs) > REPLAY_MAX_DURATION_MS || ![0.5, 1, 2, 4].includes(Number(playback.speed)) || typeof playback.speed !== "number" || typeof playback.paused !== "boolean" || typeof playback.truncated !== "boolean") return false;\n }\n const limits = record(room.limits), rematch = record(room.rematch);\n if (room.rematch !== void 0 && room.rematch !== null && (!exact(rematch, ["keepSetup", "autoStart"]) || typeof rematch.keepSetup !== "boolean" || typeof rematch.autoStart !== "boolean")) return false;\n return text(room.code) && nullable(room.mode) && nullable(room.host) && nullable(room.you) && ["lobby", "countdown", "playing", "finished", "ended"].includes(String(room.status)) && ["connecting", "connected", "reconnecting", "disconnected", "ended", "closed", "replaced"].includes(String(room.connection)) && ["countdownAt", "closedCode", "delayMs"].every((key) => room[key] === null || finite(room[key])) && ["lobby", "persistent", "requestRole"].every((key) => typeof room[key] === "boolean") && exact(limits, ["min", "max"]) && Object.values(limits).every((v) => Number.isInteger(v) && Number(v) >= 1 && Number(v) <= 24) && Array.isArray(room.players) && room.players.length <= 24 && room.players.every((value2) => {\n const player = record(value2);\n return exact(player, ["id", "name", "guest", "role", "team", "ready", "connected"]) && player !== null && text(player.id) && text(player.name) && nullable(player.role) && (player.team === null || Number.isInteger(player.team) && Number(player.team) >= 1 && Number(player.team) <= 24) && ["guest", "ready", "connected"].every((key) => typeof player[key] === "boolean");\n });\n}\nfunction validOverlayVoice(value) {\n const voice = record(value);\n if (!voice || Object.keys(voice).length !== 6 || !["mode", "state", "mic", "muted", "speaking", "peers"].every((key) => key in voice) || !["room", "team", "proximity"].includes(String(voice.mode)) || !["off", "joining", "on", "reconnecting"].includes(String(voice.state)) || !["mic", "muted", "speaking"].every((key) => typeof voice[key] === "boolean") || !Array.isArray(voice.peers) || voice.peers.length > 24) return false;\n const ids = /* @__PURE__ */ new Set();\n return voice.peers.every((value2) => {\n const peer = record(value2);\n if (!peer || Object.keys(peer).length !== 5 || !["id", "mic", "muted", "speaking", "volume"].every((key) => key in peer) || typeof peer.id !== "string" || !peer.id.length || peer.id.length > 128 || ids.has(peer.id) || !["mic", "muted", "speaking"].every((key) => typeof peer[key] === "boolean") || typeof peer.volume !== "number" || !Number.isFinite(peer.volume) || peer.volume < 0 || peer.volume > 1) return false;\n ids.add(peer.id);\n return true;\n });\n}\n\n// ../contracts/src/room-limits.ts\nvar MASSIMO_BYTE_FRAME_STANZA = 64 * 1024;\n\n// ../contracts/src/match-result.ts\nfunction readMatchResult(value, playerIds) {\n const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;\n const result = object(value);\n if (!result || !Array.isArray(result.standings)) return null;\n const known = new Set(playerIds), seen = /* @__PURE__ */ new Set();\n const standings = [];\n for (const item of result.standings) {\n const row = object(item);\n if (!row || typeof row.playerId !== "string" || !known.has(row.playerId) || seen.has(row.playerId)) continue;\n seen.add(row.playerId);\n standings.push({\n playerId: row.playerId,\n ...typeof row.score === "number" && Number.isFinite(row.score) ? { score: row.score } : {},\n ...typeof row.rank === "number" && Number.isSafeInteger(row.rank) && row.rank > 0 ? { rank: row.rank } : {}\n });\n }\n if (!standings.length) return null;\n return {\n standings,\n ...Array.isArray(result.winners) ? { winners: [...new Set(result.winners.filter((id) => typeof id === "string" && seen.has(id)))] } : {},\n ...typeof result.draw === "boolean" ? { draw: result.draw } : {},\n ...typeof result.unit === "string" ? { unit: result.unit } : {}\n };\n}\n\n// src/errors.ts\nfunction creaErrore(code, message, version = {}) {\n return Object.assign(new Error(message), { name: "CaisualError", code, ...version });\n}\n\n// src/overlay/host-bridge.ts\nfunction eMessaggioReady(value) {\n return record(value)?.type === "caisual:ready";\n}\nfunction eRichiestaBiglietto(value) {\n const data = record(value);\n return data?.type === "caisual:ticket" && (data.aud === void 0 || data.aud === "portal" || data.aud === "live");\n}\nfunction stanzaDaMessaggio(value) {\n const data = record(value);\n if (data?.type !== "caisual:room") return void 0;\n if (data.room === null) return null;\n const room = record(data.room);\n return typeof room?.code === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(room.code) ? { code: room.code } : void 0;\n}\nfunction creaPonteOspite(input) {\n let port = null, epoch = null, instance = null;\n let disposed = false, legacyReady = true, sequence = 0, requestId = 0;\n let state = null, clockOffset = null;\n let polling = null, pollingEnd = null;\n const pending = /* @__PURE__ */ new Map();\n const states = /* @__PURE__ */ new Set();\n const shortcuts = /* @__PURE__ */ new Set();\n const opens = /* @__PURE__ */ new Set();\n const errors = /* @__PURE__ */ new Set();\n const notify = (listeners, value) => {\n for (const listener of listeners) try {\n listener(value);\n } catch {\n }\n };\n const rejectPending = () => {\n for (const value of pending.values()) {\n input.finestra.clearTimeout(value.timer);\n value.reject(creaErrore("session_replaced", "The game document changed."));\n }\n pending.clear();\n };\n const stopPolling = () => {\n if (polling !== null) input.finestra.clearInterval(polling);\n if (pollingEnd !== null) input.finestra.clearTimeout(pollingEnd);\n polling = pollingEnd = null;\n };\n const askReady = () => {\n if (!disposed && input.frame.src !== "") input.frame.contentWindow?.postMessage({ type: "caisual:ready?" }, input.origineGioco);\n };\n const poll = () => {\n stopPolling();\n polling = input.finestra.setInterval(askReady, 500);\n pollingEnd = input.finestra.setTimeout(stopPolling, 1e4);\n askReady();\n };\n const loaded = () => {\n legacyReady = true;\n poll();\n };\n const listen = (event) => {\n if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow || !eMessaggioReady(event.data)) return;\n const data = record(event.data);\n const nextInstance = typeof data.instance === "string" && data.instance.length <= 128 ? data.instance : null;\n if (port && (nextInstance !== null ? nextInstance === instance : !legacyReady)) return;\n stopPolling();\n legacyReady = false;\n instance = nextInstance;\n rejectPending();\n port?.close();\n input.onRoom(null);\n epoch = input.epoch?.() ?? crypto.randomUUID();\n sequence = requestId = 0;\n state = null;\n clockOffset = null;\n notify(states, null);\n const channel = input.creaCanale?.() ?? new MessageChannel();\n const currentPort = channel.port1, currentEpoch = epoch;\n port = currentPort;\n const current = () => !disposed && port === currentPort && epoch === currentEpoch;\n currentPort.onmessage = (event2) => {\n if (!current()) return;\n const data2 = record(event2.data);\n if (eRichiestaBiglietto(data2)) {\n const aud = data2?.aud === "live" ? "live" : "portal";\n void input.rinnova(aud).then((ticket) => {\n if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, ticket });\n }).catch(() => {\n if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, error: "offline" });\n });\n return;\n }\n if (data2?.type === "caisual:reload") {\n const target = record(data2.target);\n const code = typeof target?.code === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(target.code) ? target.code : void 0;\n 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;\n input.reload?.(code || roomId ? { code, roomId, watch: target?.watch === true } : void 0);\n return;\n }\n const room = stanzaDaMessaggio(data2);\n if (room !== void 0) {\n input.onRoom(room);\n return;\n }\n if (data2?.v !== 1 || data2.epoch !== currentEpoch) return;\n if (data2.type === "caisual:overlay-response" && typeof data2.requestId === "string") {\n const item = pending.get(data2.requestId);\n if (!item) return;\n if (data2.ok !== true && (data2.ok !== false || typeof record(data2.error)?.code !== "string" || typeof record(data2.error)?.message !== "string")) return;\n pending.delete(data2.requestId);\n input.finestra.clearTimeout(item.timer);\n const response = data2;\n if (response.ok) item.resolve();\n else item.reject(creaErrore(response.error.code, response.error.message));\n } else if (data2.type === "caisual:overlay-state" && Number.isSafeInteger(data2.seq) && data2.seq > sequence) {\n if (!validOverlaySessionState(data2.state) || typeof data2.serverTime !== "number" || !Number.isFinite(data2.serverTime)) return;\n clockOffset = data2.serverTime - Date.now();\n sequence = data2.seq;\n state = structuredClone(data2.state);\n notify(states, state);\n } else if (data2.type === "caisual:overlay-error" && data2.sessionId === state?.id) {\n const error = record(data2.error);\n if (typeof error?.code === "string" && typeof error.message === "string") notify(errors, { sessionId: data2.sessionId, error: { code: error.code, message: error.message } });\n } else if (data2.type === "caisual:overlay-shortcut") {\n notify(shortcuts, void 0);\n } else if (data2.type === "caisual:overlay-open" && OVERLAY_PANELS.includes(data2.panel)) {\n notify(opens, data2.panel);\n }\n };\n currentPort.start();\n input.frame.contentWindow?.postMessage({\n type: "caisual:hello",\n replay: input.replay ?? null,\n n: input.n,\n ticket: input.ticket,\n live: input.origineLive,\n invite: input.invite,\n // language resta disponibile ai kit pubblicati prima della separazione delle lingue.\n ...input.language ? { language: input.language, uiLanguage: input.language } : {},\n ...input.languagePreferences ? { languagePreferences: input.languagePreferences } : {},\n ...input.configuration ? { gameLanguages: manifestLanguages(input.configuration.manifest) } : {},\n ...input.configuration && data.overlayVersion === 1 ? { overlay: { v: 1, epoch, configuration: input.configuration } } : {}\n }, input.origineGioco, [channel.port2]);\n };\n input.finestra.addEventListener("message", listen);\n input.frame.addEventListener?.("load", loaded);\n poll();\n return {\n get replay() {\n return input.replay ?? null;\n },\n get watch() {\n return input.watch === true;\n },\n reload() {\n input.reload?.();\n },\n get epoch() {\n return epoch;\n },\n serverTime() {\n return clockOffset === null ? null : Date.now() + clockOffset;\n },\n get state() {\n return state === null ? null : structuredClone(state);\n },\n subscribe(listener) {\n states.add(listener);\n listener(state);\n return () => {\n states.delete(listener);\n };\n },\n onShortcut(listener) {\n shortcuts.add(listener);\n return () => {\n shortcuts.delete(listener);\n };\n },\n onOpen(listener) {\n opens.add(listener);\n return () => {\n opens.delete(listener);\n };\n },\n onError(listener) {\n errors.add(listener);\n return () => {\n errors.delete(listener);\n };\n },\n request(op, args) {\n if (!port || !epoch || disposed) return Promise.reject(creaErrore("offline", "The game bridge is not connected."));\n if (pending.size >= 32) return Promise.reject(creaErrore("rate_limited", "Too many overlay requests."));\n const id = String(++requestId), request = {\n type: "caisual:overlay",\n v: 1,\n epoch,\n requestId: id,\n op,\n args,\n ...["replay.play", "replay.pause", "replay.seek", "replay.speed", "room.ready", "room.role", "room.requestRole", "room.team", "room.start", "room.restart", "session.leave", "session.disconnect", "voice.join", "voice.mute", "voice.leave", "voice.setVolume"].includes(op) ? { sessionId: state?.id ?? null } : {}\n };\n if (!validOverlayRequest(request)) return Promise.reject(creaErrore("invalid_request", "The overlay request is invalid."));\n return new Promise((resolve, reject) => {\n const timeout = op === "room.match" ? 31e4 : input.requestTimeoutMs ?? 15e3;\n const timer = input.finestra.setTimeout(() => {\n pending.delete(id);\n reject(creaErrore("timeout", "The overlay request timed out."));\n }, timeout);\n pending.set(id, { resolve, reject, timer });\n try {\n port.postMessage(request);\n } catch (error) {\n input.finestra.clearTimeout(timer);\n pending.delete(id);\n reject(error);\n }\n });\n },\n dispose() {\n disposed = true;\n stopPolling();\n rejectPending();\n port?.close();\n port = null;\n input.finestra.removeEventListener("message", listen);\n input.frame.removeEventListener?.("load", loaded);\n states.clear();\n opens.clear();\n shortcuts.clear();\n errors.clear();\n }\n };\n}\nfunction avviaHandshake(input) {\n const bridge = creaPonteOspite(input);\n return () => bridge.dispose();\n}\nfunction gameViewport(frame) {\n const rect = frame.getBoundingClientRect();\n const zoomX = frame.offsetWidth ? rect.width / frame.offsetWidth : 1;\n const zoomY = frame.offsetHeight ? rect.height / frame.offsetHeight : 1;\n const left = rect.left + frame.clientLeft * zoomX, top = rect.top + frame.clientTop * zoomY;\n return {\n left,\n top,\n right: left + frame.clientWidth * zoomX,\n bottom: top + frame.clientHeight * zoomY,\n scaleX: zoomX ? 1 / zoomX : 1,\n scaleY: zoomY ? 1 / zoomY : 1\n };\n}\nfunction measureSafeArea(frame, probe) {\n const win = frame.ownerDocument.defaultView, css = win.getComputedStyle(probe), viewport = gameViewport(frame);\n const clamp = (value, max) => Math.max(0, Math.min(max, value));\n return {\n top: clamp(((parseFloat(css.paddingTop) || 0) - viewport.top) * viewport.scaleY, frame.clientHeight),\n right: clamp((viewport.right - (win.innerWidth - (parseFloat(css.paddingRight) || 0))) * viewport.scaleX, frame.clientWidth),\n bottom: clamp((viewport.bottom - (win.innerHeight - (parseFloat(css.paddingBottom) || 0))) * viewport.scaleY, frame.clientHeight),\n left: clamp(((parseFloat(css.paddingLeft) || 0) - viewport.left) * viewport.scaleX, frame.clientWidth)\n };\n}\n\n// src/overlay/locale.ts\nvar languages = ["en", "it", "es", "fr", "de", "pt", "ja"];\nfunction overlayLanguage(raw) {\n const value = raw?.toLowerCase().split("-")[0];\n return languages.includes(value) ? value : "en";\n}\nfunction overlayLocale(raw) {\n const tag = normalizeLanguage(raw);\n return tag && languages.includes(tag.split("-")[0]) ? tag : "en";\n}\n\n// src/overlay/i18n.ts\nvar words = {\n watchReplay: ["Watch replay", "Guarda replay", "Ver repetici\\xF3n", "Voir le replay", "Wiederholung ansehen", "Assistir \\xE0 repeti\\xE7\\xE3o", "\\u30EA\\u30D7\\u30EC\\u30A4\\u3092\\u898B\\u308B"],\n copyReplay: ["Copy link", "Copia link", "Copiar enlace", "Copier le lien", "Link kopieren", "Copiar link", "\\u30EA\\u30F3\\u30AF\\u3092\\u30B3\\u30D4\\u30FC"],\n replayCopied: ["Link copied", "Link copiato", "Enlace copiado", "Lien copi\\xE9", "Link kopiert", "Link copiado", "\\u30EA\\u30F3\\u30AF\\u3092\\u30B3\\u30D4\\u30FC\\u3057\\u307E\\u3057\\u305F"],\n replay: ["Replay", "Replay", "Repetici\\xF3n", "Replay", "Wiederholung", "Repeti\\xE7\\xE3o", "\\u30EA\\u30D7\\u30EC\\u30A4"],\n replayPlay: ["Play", "Riproduci", "Reproducir", "Lire", "Abspielen", "Reproduzir", "\\u518D\\u751F"],\n replayPause: ["Pause", "Pausa", "Pausar", "Pause", "Pause", "Pausar", "\\u4E00\\u6642\\u505C\\u6B62"],\n replaySeek: ["Position", "Posizione", "Posici\\xF3n", "Position", "Position", "Posi\\xE7\\xE3o", "\\u518D\\u751F\\u4F4D\\u7F6E"],\n replaySpeed: ["Speed", "Velocit\\xE0", "Velocidad", "Vitesse", "Geschwindigkeit", "Velocidade", "\\u518D\\u751F\\u901F\\u5EA6"],\n replayTruncated: ["Partial recording", "Registrazione parziale", "Grabaci\\xF3n parcial", "Enregistrement partiel", "Teilweise Aufzeichnung", "Grava\\xE7\\xE3o parcial", "\\u4E00\\u90E8\\u306E\\u307F\\u306E\\u9332\\u753B"],\n gameUpdated: ["This game was updated", "Questo gioco \\xE8 stato aggiornato", "Este juego se ha actualizado", "Ce jeu a \\xE9t\\xE9 mis \\xE0 jour", "Dieses Spiel wurde aktualisiert", "Este jogo foi atualizado", "\\u30B2\\u30FC\\u30E0\\u304C\\u66F4\\u65B0\\u3055\\u308C\\u307E\\u3057\\u305F"],\n reloadGame: ["Reload game", "Ricarica il gioco", "Recargar el juego", "Recharger le jeu", "Spiel neu laden", "Recarregar o jogo", "\\u30B2\\u30FC\\u30E0\\u3092\\u518D\\u8AAD\\u307F\\u8FBC\\u307F"],\n gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo", "\\u30B2\\u30FC\\u30E0\\u306E\\u8A00\\u8A9E"],\n loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando...", "\\u8AAD\\u307F\\u8FBC\\u307F\\u4E2D..."],\n 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.", "\\u8AAD\\u307F\\u8FBC\\u307F\\u306B\\u6642\\u9593\\u304C\\u304B\\u304B\\u3063\\u3066\\u3044\\u307E\\u3059\\u3002\\u3057\\u3070\\u3089\\u304F\\u5F85\\u3064\\u304B\\u3001\\u3082\\u3046\\u4E00\\u5EA6\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar", "\\u30D7\\u30EC\\u30A4"],\n homeMenu: ["Menu", "Menu", "Men\\xFA", "Menu", "Men\\xFC", "Menu", "\\u30E1\\u30CB\\u30E5\\u30FC"],\n mode: ["Mode", "Modalit\\xE0", "Modo", "Mode", "Modus", "Modo", "\\u30E2\\u30FC\\u30C9"],\n singlePlayer: ["Single player", "Giocatore singolo", "Un jugador", "Un joueur", "Einzelspieler", "Um jogador", "\\u30B7\\u30F3\\u30B0\\u30EB\\u30D7\\u30EC\\u30A4"],\n multiplayer: ["Multiplayer", "Multigiocatore", "Multijugador", "Multijoueur", "Mehrspieler", "Multijogador", "\\u30DE\\u30EB\\u30C1\\u30D7\\u30EC\\u30A4"],\n createRoom: ["Create a room", "Crea una stanza", "Crear una sala", "Cr\\xE9er une salle", "Raum erstellen", "Criar uma sala", "\\u30EB\\u30FC\\u30E0\\u3092\\u4F5C\\u6210"],\n play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar", "\\u30D7\\u30EC\\u30A4"],\n friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos", "\\u53CB\\u9054\\u3068\\u30D7\\u30EC\\u30A4"],\n find: ["Find a match", "Trova una partita", "Buscar partida", "Trouver une partie", "Partie finden", "Encontrar partida", "\\u5BFE\\u6226\\u3092\\u63A2\\u3059"],\n join: ["Join with code", "Entra con codice", "Entrar con c\\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\\xF3digo", "\\u30B3\\u30FC\\u30C9\\u3067\\u53C2\\u52A0"],\n joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\\xE1 sala", "\\u3053\\u306E\\u30EB\\u30FC\\u30E0\\u306B\\u53C2\\u52A0"],\n watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala", "\\u30EB\\u30FC\\u30E0\\u3092\\u89B3\\u6226"],\n resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar", "\\u518D\\u958B"],\n room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala", "\\u30EB\\u30FC\\u30E0"],\n code: ["Room code", "Codice stanza", "C\\xF3digo de sala", "Code de salle", "Raumcode", "C\\xF3digo da sala", "\\u30EB\\u30FC\\u30E0\\u30B3\\u30FC\\u30C9"],\n copy: ["Copy invite", "Copia invito", "Copiar invitaci\\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite", "\\u62DB\\u5F85\\u3092\\u30B3\\u30D4\\u30FC"],\n copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\\xE9", "Einladung kopiert", "Convite copiado", "\\u62DB\\u5F85\\u3092\\u30B3\\u30D4\\u30FC\\u3057\\u307E\\u3057\\u305F"],\n copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:", "\\u3053\\u306E\\u30EA\\u30F3\\u30AF\\u3092\\u30B3\\u30D4\\u30FC\\u3057\\u3066\\u304F\\u3060\\u3055\\u3044\\uFF1A"],\n joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \\xE0 la salle...", "Raum wird betreten...", "Entrando na sala...", "\\u30EB\\u30FC\\u30E0\\u306B\\u53C2\\u52A0\\u4E2D..."],\n matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores...", "\\u30D7\\u30EC\\u30A4\\u30E4\\u30FC\\u3092\\u691C\\u7D22\\u4E2D..."],\n queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores", "{n} / {max} \\u4EBA"],\n cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar", "\\u30AD\\u30E3\\u30F3\\u30BB\\u30EB"],\n close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\\xDFen", "Fechar", "\\u9589\\u3058\\u308B"],\n back: ["Back", "Indietro", "Volver", "Retour", "Zur\\xFCck", "Voltar", "\\u623B\\u308B"],\n ready: ["Ready", "Pronto", "Listo", "Pr\\xEAt", "Bereit", "Pronto", "\\u6E96\\u5099\\u5B8C\\u4E86"],\n unready: ["Not ready", "Non pronto", "No listo", "Pas pr\\xEAt", "Nicht bereit", "N\\xE3o pronto", "\\u6E96\\u5099\\u3092\\u89E3\\u9664"],\n start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\\xE7ar", "\\u958B\\u59CB"],\n role: ["Role", "Ruolo", "Rol", "R\\xF4le", "Rolle", "Fun\\xE7\\xE3o", "\\u5F79\\u5272"],\n team: ["Team", "Squadra", "Equipo", "\\xC9quipe", "Team", "Equipe", "\\u30C1\\u30FC\\u30E0"],\n host: ["Host", "Host", "Anfitrion", "H\\xF4te", "Host", "Anfitri\\xE3o", "\\u30DB\\u30B9\\u30C8"],\n you: ["You", "Tu", "T\\xFA", "Vous", "Du", "Voc\\xEA", "\\u3042\\u306A\\u305F"],\n away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente", "\\u96E2\\u5E2D\\u4E2D"],\n needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores", "\\u30D7\\u30EC\\u30A4\\u30E4\\u30FC\\u3092\\u5F85\\u3063\\u3066\\u3044\\u307E\\u3059"],\n 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", "\\u5168\\u54E1\\u306E\\u6E96\\u5099\\u5B8C\\u4E86\\u3092\\u5F85\\u3063\\u3066\\u3044\\u307E\\u3059"],\n 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", "\\u5FC5\\u8981\\u306A\\u5F79\\u5272\\u3092\\u9078\\u3093\\u3067\\u304F\\u3060\\u3055\\u3044"],\n needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \\xE9quipes", "Teams auswahlen", "Escolha as equipes", "\\u5FC5\\u8981\\u306A\\u30C1\\u30FC\\u30E0\\u3092\\u9078\\u3093\\u3067\\u304F\\u3060\\u3055\\u3044"],\n 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", "\\u30DB\\u30B9\\u30C8\\u3092\\u5F85\\u3063\\u3066\\u3044\\u307E\\u3059"],\n starting: ["Starting in", "Si inizia tra", "Empieza en", "D\\xE9but dans", "Start in", "Come\\xE7a em", "\\u958B\\u59CB\\u307E\\u3067"],\n playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando", "\\u30D7\\u30EC\\u30A4\\u4E2D"],\n ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\\xE9e", "Spiel beendet", "Partida encerrada", "\\u8A66\\u5408\\u7D42\\u4E86"],\n rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\\xEAts", "{n}/{max} bereit", "{n}/{max} prontos", "{n}/{max} \\u4EBA\\u304C\\u6E96\\u5099\\u5B8C\\u4E86"],\n rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche", "\\u518D\\u6226\\u3092\\u958B\\u59CB"],\n won: ["You won", "Hai vinto", "Has ganado", "Vous avez gagn\\xE9", "Du hast gewonnen", "Voc\\xEA venceu", "\\u52DD\\u5229"],\n lost: ["You lost", "Hai perso", "Has perdido", "Vous avez perdu", "Du hast verloren", "Voc\\xEA perdeu", "\\u6557\\u5317"],\n draw: ["Draw", "Pareggio", "Empate", "\\xC9galit\\xE9", "Unentschieden", "Empate", "\\u5F15\\u304D\\u5206\\u3051"],\n standings: ["Standings", "Piazzamenti", "Posiciones", "R\\xE9sultats", "Platzierungen", "Coloca\\xE7\\xF5es", "\\u9806\\u4F4D"],\n points: ["points", "punti", "puntos", "points", "Punkte", "pontos", "\\u30DD\\u30A4\\u30F3\\u30C8"],\n time: ["time", "tempo", "tiempo", "temps", "Zeit", "tempo", "\\u6642\\u9593"],\n distance: ["distance", "distanza", "distancia", "distance", "Distanz", "dist\\xE2ncia", "\\u8DDD\\u96E2"],\n again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente", "\\u3082\\u3046\\u4E00\\u5EA6\\u30D7\\u30EC\\u30A4"],\n 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.", "\\u65B0\\u3057\\u3044\\u30EB\\u30FC\\u30E0\\u3067\\u3059\\u3002\\u65B0\\u3057\\u3044\\u62DB\\u5F85\\u3092\\u5171\\u6709\\u3057\\u3066\\u304F\\u3060\\u3055\\u3044\\u3002"],\n watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo", "\\u89B3\\u6226\\u4E2D"],\n delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\\xF6gerung", "Atraso de {n}s", "{n}\\u79D2\\u306E\\u9045\\u5EF6"],\n exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair", "\\u7D42\\u4E86"],\n leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\\xFCbergehend verlassen", "Sair por enquanto", "\\u4E00\\u6642\\u9000\\u51FA"],\n leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala", "\\u30EB\\u30FC\\u30E0\\u3092\\u9000\\u51FA"],\n 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.", "\\u30EB\\u30FC\\u30E0\\u306F\\u5F8C\\u304B\\u3089\\u518D\\u958B\\u3067\\u304D\\u307E\\u3059\\u3002"],\n 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.", "\\u30B2\\u30FC\\u30E0\\u306F\\u7D9A\\u304D\\u307E\\u3059\\u3002\\u518D\\u53C2\\u52A0\\u3067\\u304D\\u308B\\u6642\\u9593\\u306F\\u9650\\u3089\\u308C\\u308B\\u5834\\u5408\\u304C\\u3042\\u308A\\u307E\\u3059\\u3002"],\n 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.", "\\u30EB\\u30FC\\u30E0\\u3092\\u9000\\u51FA\\u3059\\u308B\\u3068\\u53C2\\u52A0\\u67A0\\u3092\\u624B\\u653E\\u3057\\u307E\\u3059\\u3002"],\n reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando...", "\\u518D\\u63A5\\u7D9A\\u4E2D..."],\n 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", "\\u5225\\u306E\\u30BF\\u30D6\\u3067\\u958B\\u304B\\u308C\\u307E\\u3057\\u305F"],\n 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.", "\\u554F\\u984C\\u304C\\u767A\\u751F\\u3057\\u307E\\u3057\\u305F\\u3002\\u3082\\u3046\\u4E00\\u5EA6\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u3053\\u306E\\u30EB\\u30FC\\u30E0\\u306F\\u5229\\u7528\\u3067\\u304D\\u307E\\u305B\\u3093\\u3002"],\n 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.", "\\u30EB\\u30FC\\u30E0\\u306F\\u6E80\\u54E1\\u3067\\u3059\\u3002"],\n 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.", "\\u76F8\\u624B\\u304C\\u898B\\u3064\\u304B\\u308A\\u307E\\u305B\\u3093\\u3067\\u3057\\u305F\\u3002\\u3082\\u3046\\u4E00\\u5EA6\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "6\\u6587\\u5B57\\u306E\\u30EB\\u30FC\\u30E0\\u30B3\\u30FC\\u30C9\\u3092\\u5165\\u529B\\u3057\\u3066\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u30EB\\u30FC\\u30E0\\u306F\\u5909\\u66F4\\u3092\\u53D7\\u3051\\u4ED8\\u3051\\u307E\\u305B\\u3093\\u3067\\u3057\\u305F\\u3002"],\n unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\\xFCgbar", "Indisponivel agora", "\\u73FE\\u5728\\u5229\\u7528\\u3067\\u304D\\u307E\\u305B\\u3093"],\n 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.", "\\u63A5\\u7D9A\\u3067\\u304D\\u307E\\u305B\\u3093\\u3002\\u3082\\u3046\\u4E00\\u5EA6\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u30EB\\u30FC\\u30E0\\u30B3\\u30FC\\u30C9\\u3092\\u63A7\\u3048\\u3066\\u304F\\u3060\\u3055\\u3044\\u3002\\u518D\\u958B\\u60C5\\u5831\\u3092\\u4FDD\\u5B58\\u3067\\u304D\\u307E\\u305B\\u3093\\u3067\\u3057\\u305F\\u3002"],\n friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo", "\\u53CB\\u9054\\u3068\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC"],\n 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.", "\\u30ED\\u30FC\\u30AB\\u30EB\\u30D7\\u30EC\\u30D3\\u30E5\\u30FC\\u3067\\u306F\\u53CB\\u9054\\u3068\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC\\u306F\\u5229\\u7528\\u3067\\u304D\\u307E\\u305B\\u3093\\u3002"],\n 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.", "\\u53CB\\u9054\\u3068\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC\\u3092\\u5229\\u7528\\u3059\\u308B\\u306B\\u306FCaisual\\u306B\\u30ED\\u30B0\\u30A4\\u30F3\\u3057\\u3066\\u304F\\u3060\\u3055\\u3044\\u3002"],\n online: ["Online", "Online", "En linea", "En ligne", "Online", "Online", "\\u30AA\\u30F3\\u30E9\\u30A4\\u30F3"],\n noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online", "\\u30AA\\u30F3\\u30E9\\u30A4\\u30F3\\u306E\\u53CB\\u9054\\u306F\\u3044\\u307E\\u305B\\u3093"],\n createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\\xE9er un groupe", "Gruppe erstellen", "Criar grupo", "\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC\\u3092\\u4F5C\\u6210"],\n inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo", "\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC\\u306B\\u62DB\\u5F85"],\n leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo", "\\u30D1\\u30FC\\u30C6\\u30A3\\u30FC\\u3092\\u9000\\u51FA"],\n accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar", "\\u627F\\u8AFE"],\n decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar", "\\u8F9E\\u9000"],\n follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se", "\\u4E00\\u7DD2\\u306B\\u53C2\\u52A0"],\n voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz", "\\u30DC\\u30A4\\u30B9"],\n voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz", "\\u30DC\\u30A4\\u30B9\\u306B\\u53C2\\u52A0"],\n voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz", "\\u30DC\\u30A4\\u30B9\\u3092\\u9000\\u51FA"],\n voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar", "\\u30DF\\u30E5\\u30FC\\u30C8"],\n voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone", "\\u30DF\\u30E5\\u30FC\\u30C8\\u89E3\\u9664"],\n voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\\xE9sactiv\\xE9e", "Sprachchat aus", "Voz desativada", "\\u30DC\\u30A4\\u30B9\\u30AA\\u30D5"],\n voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz...", "\\u30DC\\u30A4\\u30B9\\u306B\\u63A5\\u7D9A\\u4E2D..."],\n voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\\xE9e", "Sprachchat verbunden", "Voz conectada", "\\u30DC\\u30A4\\u30B9\\u63A5\\u7D9A\\u6E08\\u307F"],\n voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\\xE9", "Stumm", "Silenciado", "\\u30DF\\u30E5\\u30FC\\u30C8\\u4E2D"],\n voiceMic: ["Mic on", "Microfono attivo", "Micr\\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo", "\\u30DE\\u30A4\\u30AF\\u30AA\\u30F3"],\n voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\\xC9coute seule", "Nur zuh\\xF6ren", "Somente ouvindo", "\\u805E\\u304F\\u3060\\u3051"],\n voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando", "\\u767A\\u8A71\\u4E2D"],\n voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz", "\\u30DC\\u30A4\\u30B9\\u53C2\\u52A0\\u8005"],\n 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.", "\\u4ED6\\u306E\\u53C2\\u52A0\\u8005\\u306F\\u307E\\u3060\\u3044\\u307E\\u305B\\u3093\\u3002"],\n voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\\xE4rke f\\xFCr {name}", "Volume de {name}", "{name}\\u306E\\u97F3\\u91CF"],\n 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.", "\\u30DC\\u30A4\\u30B9\\u5BFE\\u5FDC\\u306E\\u30EB\\u30FC\\u30E0\\u306B\\u53C2\\u52A0\\u3057\\u3066\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u89B3\\u6226\\u4E2D\\u306F\\u30DC\\u30A4\\u30B9\\u3092\\u5229\\u7528\\u3067\\u304D\\u307E\\u305B\\u3093\\u3002"],\n 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.", "\\u30DE\\u30A4\\u30AF\\u304C\\u8A31\\u53EF\\u3055\\u308C\\u3066\\u3044\\u307E\\u305B\\u3093\\u3002\\u30D6\\u30E9\\u30A6\\u30B6\\u3067\\u8A31\\u53EF\\u3057\\u3066\\u304B\\u3089\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u3053\\u306E\\u30D6\\u30E9\\u30A6\\u30B6\\u306F\\u30DC\\u30A4\\u30B9\\u306B\\u5BFE\\u5FDC\\u3057\\u3066\\u3044\\u307E\\u305B\\u3093\\u3002"],\n 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.", "\\u30DC\\u30A4\\u30B9\\u306B\\u63A5\\u7D9A\\u3067\\u304D\\u307E\\u305B\\u3093\\u3067\\u3057\\u305F\\u3002\\u3082\\u3046\\u4E00\\u5EA6\\u304A\\u8A66\\u3057\\u304F\\u3060\\u3055\\u3044\\u3002"],\n 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.", "\\u3053\\u306E\\u53C2\\u52A0\\u8005\\u306F\\u30DC\\u30A4\\u30B9\\u3092\\u9000\\u51FA\\u3057\\u307E\\u3057\\u305F\\u3002"],\n shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab", "Shift+Tab\\u30B7\\u30E7\\u30FC\\u30C8\\u30AB\\u30C3\\u30C8"],\n menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual", "Caisual\\u30E1\\u30CB\\u30E5\\u30FC"],\n retry: ["Retry", "Riprova", "Reintentar", "R\\xE9essayer", "Erneut versuchen", "Tentar novamente", "\\u518D\\u8A66\\u884C"]\n};\nvar column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));\nvar dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5), ja: column(6) };\nfunction translator(language) {\n const dictionary = dictionaries[overlayLanguage(language)];\n return (key, values = {}) => dictionary[key].replace(/\\{(\\w+)\\}/g, (_all, name) => String(values[name] ?? ""));\n}\nfunction errorText(code) {\n if (code === "version_outdated") return "gameUpdated";\n if (code === "permission_denied") return "voiceDenied";\n if (code === "unsupported") return "voiceUnsupported";\n if (code === "voice_disabled") return "voiceUnavailable";\n if (code === "voice_error") return "voiceFailed";\n if (code === "voice_peer_missing") return "voicePeerGone";\n if (code === "not_publishing") return "voiceListening";\n if (["room_not_found", "room_ended", "version_closed", "no_resume"].includes(code)) return "noRoom";\n if (["room_full", "role_full"].includes(code)) return "full";\n if (code === "replaced") return "replaced";\n if (code === "no_match") return "noMatch";\n if (code === "invalid_code") return "invalidCode";\n if (["offline", "timeout"].includes(code)) return "offline";\n if (code.startsWith("role_") || ["not_in_lobby", "not_host", "session_replaced"].includes(code)) return "refused";\n if (code === "save_failed") return "saveFailed";\n return "error";\n}\n\n// src/overlay/ui-model.ts\nfunction phase(session) {\n if (!session || session.kind === "boot") return "boot";\n if (session.kind === "attaching" || session.kind === "matching") return session.kind;\n if (session.room && ["closed", "replaced"].includes(session.room.connection)) return "error";\n if (session.kind === "local") return session.localStatus === "ended" ? "ended" : "playing";\n if (session.room?.status === "ended" || session.room?.status === "finished") return "ended";\n if (session.kind === "watch") return "watching";\n if (session.kind === "room" && session.room) return session.room.status;\n return "home";\n}\nfunction initialUi(manifest) {\n return { session: null, panel: "auto", mode: manifest.modes[0]?.id ?? "", busy: false, error: null, notice: null, shortcutEnabled: true };\n}\nfunction groupModes(manifest) {\n const groups = { singlePlayer: [], multiplayer: [] };\n for (const mode of manifest.modes) groups[risolviModalita(manifest, mode.id).players.max === 1 ? "singlePlayer" : "multiplayer"].push(mode);\n return groups;\n}\nfunction reduceUi(model, action) {\n switch (action.type) {\n case "session": {\n const next = action.session, changed = next?.id !== model.session?.id || next === null;\n const pending = next?.kind === "attaching" || next?.kind === "matching";\n const nextPhase = phase(next), transition = phase(model.session) !== nextPhase;\n const automatic = transition && ["lobby", "countdown", "playing", "ended"].includes(nextPhase) && [null, "auto", "room", "invite", "home"].includes(model.panel);\n return {\n ...model,\n session: next,\n mode: next?.mode ?? model.mode,\n panel: changed || pending || automatic ? "auto" : model.panel,\n error: changed ? null : model.error,\n notice: changed ? null : model.notice\n };\n }\n case "panel":\n return { ...model, panel: action.panel, error: null, notice: null };\n case "mode":\n return { ...model, mode: action.mode, error: null };\n case "busy":\n return { ...model, busy: action.busy };\n case "error":\n return { ...model, error: action.code, busy: false };\n case "notice":\n return { ...model, notice: action.notice };\n case "shortcut":\n return { ...model, shortcutEnabled: action.enabled };\n }\n}\nfunction visiblePanel(model) {\n const current = phase(model.session);\n if (current === "boot" || current === "attaching" || current === "matching" || current === "error") return current;\n if (model.session?.room?.limits.max === 1 && ["room", "invite"].includes(model.panel ?? "")) return "home";\n if (model.panel !== "auto") return model.panel;\n if (model.session?.room?.limits.max === 1 && current === "lobby") return null;\n return current === "home" ? "home" : current === "lobby" ? "room" : current === "countdown" ? "countdown" : null;\n}\nfunction primaryAction(manifest, mode) {\n const selected = manifest.modes.find((item) => item.id === mode);\n if (!selected) return null;\n return {\n op: selected.execution === "local" ? "local.start" : "room.create",\n friends: selected.execution === "room" && risolviModalita(manifest, mode).players.max > 1\n };\n}\nfunction startReason(manifest, session) {\n const room = session?.room;\n if (!room || session.kind !== "room" || room.status !== "lobby" || room.connection !== "connected") return "unavailable";\n const connected = room.players.filter((p) => p.connected), active = connected.filter((p) => p.role !== "spectator");\n if (active.length < room.limits.min) return "needPlayers";\n if (connected.some((p) => !p.ready)) return "needReady";\n if (manifest.roles.some((role) => active.filter((p) => p.role === role.id).length < role.min)) return "needRoles";\n if (manifest.teams && (active.some((p) => p.team === null) || new Set(active.map((p) => p.team)).size < manifest.teams.min)) return "needTeams";\n return room.host !== room.you ? "waitHost" : null;\n}\nfunction canPlayAgain(session) {\n if (phase(session) !== "ended") return false;\n if (session?.kind === "local") return true;\n if (session?.room?.status === "finished") return session.kind === "room" && session.room.connection === "connected" && (session.room.limits.max === 1 || session.room.players.some((p) => p.id === session.room.you && p.connected && p.role !== "spectator" && !p.ready));\n return session?.kind === "room" && (session.room?.limits.max === 1 || !session.room?.lobby || session.room.host === session.room.you);\n}\nfunction normalizeInvite(code) {\n const value = code.toUpperCase().replace(/[\\s-]/g, "");\n return /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(value) ? value : null;\n}\nfunction matchPresentation(session) {\n const room = session?.room;\n if (!room || !["finished", "ended"].includes(room.status)) return null;\n const result = readMatchResult(room.result, room.players.map((p) => p.id));\n if (!result) return null;\n const own = session?.kind === "room" && room.players.some((p) => p.id === room.you && p.role !== "spectator") && result.standings.some((p) => p.playerId === room.you);\n const first = result.standings[0];\n const winners = result.winners ?? result.standings.filter((p, i) => i === 0 || first.rank !== void 0 && p.rank === first.rank).map((p) => p.playerId);\n return { result, outcome: !own ? "ended" : result.draw ? "draw" : winners.includes(room.you) ? "won" : "lost" };\n}\n\n// src/overlay/styles.ts\nvar styles = `\n.game-icon{width:28px;height:28px;aspect-ratio:1;object-fit:contain;border-radius:7px;flex:none;vertical-align:middle}.game-icon-title{width:36px;height:36px;border-radius:10px}\n.safe-area-probe{position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)}\n:host{all:initial;position:fixed;inset:0;z-index:10000;pointer-events:none;font:15px/1.45 system-ui,sans-serif;color:#f4f4f1;color-scheme:dark;--accent:#a8efc5}\n[data-layout],[data-surface],.sr{pointer-events:none}*{box-sizing:border-box}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,select,input{border:1px solid #ffffff30;background:#25292b;color:inherit;border-radius:12px;min-height:44px;padding:10px 14px}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}button:hover:not(:disabled){background:#343b3a}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:3px}a{color:var(--accent)}.primary{background:var(--accent);color:var(--accent-ink,#11221b);border-color:transparent;font-weight:700}.primary:hover:not(:disabled){filter:brightness(1.1);background:var(--accent)}.quiet{background:transparent}label{display:grid;gap:6px;text-align:left}select,input{width:100%;min-width:0}h1,h2,p{margin:0}h1{font-size:clamp(26px,5vw,42px);line-height:1.1;letter-spacing:-.035em}h2{font-size:20px}small,.muted{color:#bdc5c1}.stack{display:grid;gap:16px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.row>*{flex:0 1 auto}.row .grow,.grow{flex:1}.split{display:grid;grid-template-columns:1fr 1fr;gap:10px}.pill{position:absolute;top:max(10px,env(safe-area-inset-top));right:max(10px,env(safe-area-inset-right));display:flex;height:44px;border:1px solid #ffffff35;border-radius:24px;background:#171e20eF;box-shadow:0 4px 20px #0004;pointer-events:auto;overflow:hidden}.pill button{border:0;border-radius:0;padding:8px 13px;background:transparent}.pill button:focus-visible{outline-offset:-4px}.pill small{margin-left:8px}.backdrop{position:absolute;inset:0;background:#0b151ce8;backdrop-filter:blur(10px);pointer-events:auto;display:grid;place-items:center;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));overflow:auto}.backdrop.home{background-color:#142127;background-size:contain;background-repeat:no-repeat;background-position:center}.dialog{position:relative;width:min(100%,540px);max-height:100%;overflow:auto;overscroll-behavior:contain;background:#141b1df5;border:1px solid #ffffff25;border-radius:22px;padding:24px;box-shadow:0 20px 80px #0005}.dialog.wide{width:min(100%,700px)}.top{display:flex;align-items:center;gap:12px;margin-bottom:18px}.top h2{flex:1}.tabs{display:flex;gap:6px;flex-wrap:wrap;border-bottom:1px solid #ffffff25;padding-bottom:12px}.tabs button{min-height:36px;padding:6px 10px}.tabs [aria-current=true]{border-color:var(--accent)}.roster{list-style:none;padding:0;margin:0;display:grid;gap:8px;max-height:32dvh;overflow:auto}.roster li{display:flex;align-items:center;gap:8px;padding:10px;background:#ffffff08;border-radius:10px}.roster .name{flex:1;overflow-wrap:anywhere}.badge{border:1px solid #ffffff30;border-radius:6px;padding:2px 6px;font-size:12px}.code{font-size:24px;letter-spacing:.13em;font-variant-numeric:tabular-nums}.notice,.error{border-radius:10px;padding:10px;background:#a8efc514;overflow-wrap:anywhere}.error{background:#ff8b7720;color:#ffd2c9}.countdown{font-size:88px;line-height:1;text-align:center;font-variant-numeric:tabular-nums}.ended{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));left:50%;transform:translateX(-50%);max-width:calc(100% - 24px);width:max-content;background:#171e20f5;pointer-events:auto;border:1px solid #ffffff30;border-radius:16px;padding:10px;display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap}.ended [data-rematch-players]{max-width:100%;max-height:3.2em;overflow:auto;overflow-wrap:anywhere}.standings{list-style:none;margin:0;padding:0;flex-basis:100%;max-height:20dvh;overflow:auto;font-size:13px}.standings li{display:flex;justify-content:space-between;gap:16px;overflow-wrap:anywhere}.ended{max-height:calc(100dvh - 80px);overflow:auto}.ended strong{padding:0 8px}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}.checkbox{display:flex;align-items:center;gap:8px;font-size:13px}.checkbox input{width:18px;min-height:18px}.full{width:100%}\n.game-heading{display:flex;align-items:center;gap:12px;min-width:0;flex:1}.game-heading h1{font-size:28px;overflow-wrap:anywhere}.home .top{margin-bottom:12px}.game-description{font-size:13px;line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.experience-tabs{display:grid;grid-template-columns:1fr 1fr;gap:4px;padding:4px;border:1px solid #ffffff18;border-radius:14px;background:#0003}.experience-tabs button{background:transparent;border-color:transparent;font-size:14px;font-weight:600;padding:10px 8px;border-radius:10px;color:#bdc5c1}.experience-tabs [aria-selected=true]{background:#ffffff16;color:#f4f4f1;box-shadow:0 1px 4px #0003}.experience-tabs button:focus-visible{outline-offset:-3px}.home-content{gap:14px;min-width:0}.mode-details{display:grid;gap:6px;min-width:0}.mode-details h2{font-size:16px;font-weight:600}.mode-details label{font-size:13px}.mode-instructions{font-size:12px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.play-actions{gap:8px}.play-actions .primary{min-height:50px;font-size:16px}.home-links{gap:4px}.home-links button{border-color:transparent;font-size:13px}.home-links button:hover:not(:disabled){background:#ffffff0a}.resume-action{gap:4px}.resume-action small{text-align:center}.panel-footer{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-top:18px;padding-top:10px;border-top:1px solid #ffffff18;color:#bdc5c1}.panel-footer .checkbox{font-size:11px;white-space:nowrap;min-height:32px;gap:6px}.panel-footer input{margin:0;accent-color:var(--accent);width:14px;min-height:14px}.panel-footer small{min-width:0;text-align:right;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-transform:uppercase}\n[hidden]{display:none!important}.voice-peers{list-style:none;margin:0;padding:0;display:grid;gap:10px}.voice-peers li{border:1px solid #ffffff25;border-radius:12px;padding:12px;display:grid;gap:8px}.voice-peers [data-speaking=true]{border-color:var(--accent)}.voice-peers input{width:100%;accent-color:var(--accent);padding:0}.voice-peers label{font-size:13px}.pill .voice-toggle{width:44px;padding:8px}.voice-toggle[data-voice-state=on][data-muted=false]{color:var(--accent)}\n.boot{position:absolute;inset:0;z-index:2;isolation:isolate;display:grid;place-items:center;overflow:auto;overscroll-behavior:contain;padding:max(100px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(48px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));background:#0b151c;opacity:1;transition:opacity .4s ease;pointer-events:auto;outline:none}\n.boot::before,.boot::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:-1}.boot::before{background:radial-gradient(ellipse at 50% 38%,color-mix(in srgb,var(--accent),transparent 80%),transparent 65%)}.boot::after{background:radial-gradient(ellipse at 50% 38%,#0b151c20,#0b151cd9 85%),linear-gradient(#0b151c66,#0b151cbf)}\n.boot-cover{position:fixed;inset:0;z-index:-2;width:100%;height:100%;aspect-ratio:3 / 2;object-fit:contain;filter:blur(20px);opacity:.65;pointer-events:none}\n.boot-brand{position:absolute;top:max(28px,env(safe-area-inset-top));left:max(32px,env(safe-area-inset-left));display:flex;align-items:center;gap:10px;font-size:14px;font-weight:650;letter-spacing:.02em;color:#f4f4f1b3}.boot-brand span{display:grid;place-items:center;width:36px;height:36px;border:1px solid #ffffff25;border-radius:12px;background:#171e20af;box-shadow:0 4px 20px #0004;color:var(--boot-accent);font-size:20px;font-weight:800}\n.boot-content{width:min(100%,900px);text-align:center;display:grid;justify-items:center;gap:24px}.boot h1{max-width:16ch;font-size:clamp(44px,8vw,108px);font-weight:800;line-height:1.04;letter-spacing:-.05em;overflow-wrap:anywhere;text-wrap:balance;color:var(--boot-accent);text-shadow:0 20px 80px #0005}\n.boot-progress{width:112px;height:3px;border-radius:12px;background:#ffffff20;overflow:hidden;margin-top:12px}.boot-progress span{display:block;width:44%;height:100%;border-radius:inherit;background:var(--boot-accent);animation:boot-progress 1.8s ease-in-out infinite}.boot-status{max-width:42ch;min-height:3em;font-size:14px;line-height:1.5;color:#d3dad6;text-wrap:balance}.boot-recovery{min-height:44px}.boot-recovery .row{justify-content:center}.boot-leaving{opacity:0;pointer-events:none}\n@keyframes boot-progress{0%{transform:translateX(-110%)}100%{transform:translateX(340%)}}\n@media(max-width:480px){.dialog{padding:18px;border-radius:18px}.split{grid-template-columns:1fr 1fr;gap:8px}.tabs{gap:4px}.tabs button{font-size:13px;padding:6px 8px}.pill button:focus-visible{outline-offset:-4px}.pill small{display:none}.ended{gap:6px}.standings{list-style:none;margin:0;padding:0;flex-basis:100%;max-height:20dvh;overflow:auto;font-size:13px}.standings li{display:flex;justify-content:space-between;gap:16px;overflow-wrap:anywhere}.ended{max-height:calc(100dvh - 80px);overflow:auto}.ended strong{font-size:13px}.ended button{padding:8px 10px;font-size:13px}.roster{max-height:28dvh}}\n.replay-controls{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));left:12px;right:12px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:12px;background:#141b1df5;border:1px solid #ffffff30;border-radius:16px;pointer-events:auto}.replay-position{flex:1;min-width:100px}.replay-controls label{font-size:12px}.replay-controls span{font-variant-numeric:tabular-nums;font-size:13px}.replay-link{display:inline-flex;align-items:center;min-height:44px;padding:10px 14px;border-radius:12px;text-decoration:none}\n@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}.boot{transition:none}.boot-progress span{animation:none;transform:translateX(65%)}}\n`;\n\n// src/overlay/voice-panel.ts\nfunction voiceEligible(manifest, session) {\n return manifest.voice !== "none" && session?.kind !== "watch" && session?.room?.players.find((player) => player.id === session.room?.you)?.role !== "spectator";\n}\nfunction voiceStatus(voice, t) {\n const key = voice.state === "joining" ? "voiceJoining" : voice.state === "reconnecting" ? "reconnecting" : voice.state === "off" ? "voiceOff" : "voiceOn";\n return t(key);\n}\nfunction updateVoicePanel(container, input) {\n const { session, t } = input, voice = session?.kind === "room" ? session.voice : null;\n if (!voiceEligible(input.manifest, session) || !voice) {\n container.replaceChildren();\n const note = container.ownerDocument.createElement("p");\n note.textContent = t(session?.kind === "watch" || session?.room?.players.find((p) => p.id === session.room?.you)?.role === "spectator" ? "voiceWatch" : "voiceUnavailable");\n container.append(note);\n return;\n }\n if (!container.querySelector("[data-voice-status]")) container.innerHTML = `<p role="status" aria-live="polite" data-voice-status></p><p data-voice-self></p>\n <div class="row"><button type="button" data-action="voice-join"></button><button type="button" data-action="voice-mute"></button><button type="button" data-action="voice-leave"></button></div>\n <p class="error" role="alert" data-voice-error hidden></p><h3 data-voice-heading></h3><ul class="voice-peers" data-voice-peers></ul><p class="muted" data-voice-empty></p>`;\n const get = (selector) => container.querySelector(selector);\n const status = get("[data-voice-status]");\n status.textContent = voiceStatus(voice, t);\n status.dataset.voiceState = voice.state;\n const mic = (value) => t(!value.mic ? "voiceListening" : value.muted ? "voiceMuted" : value.speaking ? "voiceSpeaking" : "voiceMic");\n get("[data-voice-self]").textContent = voice.state === "off" ? "" : `${t("you")}: ${mic(voice)}`;\n const join = get(\'[data-action="voice-join"]\'), mute = get(\'[data-action="voice-mute"]\'), leave = get(\'[data-action="voice-leave"]\');\n join.textContent = t("voiceJoin");\n join.hidden = voice.state !== "off";\n join.disabled = session?.room?.connection !== "connected" || input.pending === "voice.join";\n mute.textContent = t(voice.muted ? "voiceUnmute" : "voiceMute");\n mute.hidden = voice.state !== "on" || !voice.mic;\n mute.disabled = input.pending === "voice.mute";\n mute.setAttribute("aria-pressed", String(voice.muted));\n leave.textContent = t("voiceLeave");\n leave.hidden = voice.state === "off" && input.pending !== "voice.join";\n leave.disabled = input.pending === "voice.leave";\n const error = get("[data-voice-error]");\n error.hidden = !input.error;\n error.textContent = input.error ? t(errorText(input.error)) : "";\n get("[data-voice-heading]").textContent = t("voicePeers");\n get("[data-voice-empty]").textContent = t("voiceEmpty");\n get("[data-voice-empty]").hidden = voice.peers.length > 0;\n const list = get("[data-voice-peers]"), ids = new Set(voice.peers.map((peer) => peer.id));\n for (const row of list.querySelectorAll("[data-voice-peer]")) if (!ids.has(row.dataset.voicePeer)) row.remove();\n for (const peer of voice.peers) {\n let row = [...list.children].find((node) => node.dataset.voicePeer === peer.id);\n if (!row) {\n row = container.ownerDocument.createElement("li");\n row.dataset.voicePeer = peer.id;\n row.innerHTML = \'<div class="row"><strong data-peer-name></strong><small data-peer-status></small></div><label><span data-volume-label></span><input type="range" min="0" max="1" step="0.05" data-control="voice-volume"></label>\';\n row.querySelector("input").dataset.peer = peer.id;\n list.append(row);\n }\n const name = session?.room?.players.find((player) => player.id === peer.id)?.name ?? peer.id;\n row.dataset.mic = String(peer.mic);\n row.dataset.muted = String(peer.muted);\n row.dataset.speaking = String(peer.speaking);\n row.querySelector("[data-peer-name]").textContent = name;\n row.querySelector("[data-peer-status]").textContent = mic(peer);\n row.querySelector("[data-volume-label]").textContent = t("voiceVolume", { name });\n const range = row.querySelector("input");\n if (range.dataset.editing !== "true") range.value = String(peer.volume);\n range.setAttribute("aria-valuetext", `${Math.round(Number(range.value) * 100)}%`);\n range.disabled = voice.state !== "on";\n }\n}\n\n// src/overlay/ui.ts\nvar escape = (value) => String(value ?? "").replace(/[&<>"\']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", \'"\': "&quot;", "\'": "&#39;" })[c]);\nfunction mountOverlay(input) {\n const manifest = input.configuration.manifest;\n if (manifest.overlay?.version !== 1 && !input.bridge.replay) return null;\n const document = input.container.ownerDocument, win = document.defaultView, t = translator(input.language);\n const host = document.createElement("div");\n host.dataset.caisualOverlay = "";\n host.lang = overlayLanguage(input.language);\n host.style.setProperty("pointer-events", "none", "important");\n const root = host.attachShadow({ mode: "open" });\n if (typeof win.CSSStyleSheet?.prototype.replaceSync === "function" && "adoptedStyleSheets" in root) {\n const sheet = new win.CSSStyleSheet();\n sheet.replaceSync(styles);\n root.adoptedStyleSheets = [sheet];\n } else {\n const sheet = document.createElement("link");\n sheet.rel = "stylesheet";\n sheet.href = "/__caisual/overlay/v1.css";\n root.append(sheet);\n }\n const elements = document.createElement("div");\n elements.dataset.layout = "";\n elements.style.pointerEvents = "none";\n elements.innerHTML = `<div data-surface></div><div class="sr" role="status" aria-live="polite" data-live></div>`;\n const safeProbe = document.createElement("div");\n safeProbe.className = "safe-area-probe";\n safeProbe.setAttribute("aria-hidden", "true");\n root.append(elements, safeProbe);\n const surface = root.querySelector("[data-surface]"), live = root.querySelector("[data-live]");\n surface.style.pointerEvents = "none";\n live.style.pointerEvents = "none";\n const accent = manifest.overlay?.accent ?? "#a8efc5";\n host.style.setProperty("--accent", accent);\n const rgb = [1, 3, 5].map((i) => parseInt(accent.slice(i, i + 2), 16) / 255).map((v) => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);\n const luminance = rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;\n host.style.setProperty("--accent-ink", luminance > 0.179 ? "#000000" : "#ffffff");\n host.style.setProperty("--boot-accent", luminance > 0.179 ? accent : `color-mix(in srgb, ${accent}, #ffffff 70%)`);\n input.container.append(host);\n let model = initialUi(manifest), disposed = false, operation = 0, lastView = "", geometryFrame = 0;\n let inviteAfterCreate;\n let lastPhase = "", wasModal = false, copyFallback = null;\n let boot = null, bootTimer = 0, bootFadeTimer = 0;\n let voiceError = null, voicePending = null, voiceOperation = 0;\n let codeDraft = input.configuration.invite ?? "";\n const oldInert = Boolean(input.frame.inert), oldTabIndex = input.frame.getAttribute("tabindex");\n try {\n model.shortcutEnabled = win.localStorage.getItem("caisual-overlay-shortcut-v1") !== "off";\n } catch {\n }\n const stops = [];\n const modeGroups = groupModes(manifest);\n const selectedMode = () => manifest.modes.find((mode) => mode.id === model.mode);\n const disabled = () => model.busy ? " disabled" : "";\n const button = (action, key, extra = "", off = false) => `<button type="button" data-action="${action}"${extra}${off || model.busy ? " disabled" : ""}>${t(key)}</button>`;\n function resetBootWait() {\n win.clearTimeout(bootTimer);\n if (!boot || phase(model.session) !== "boot") return;\n boot.querySelector("[data-boot-message]").textContent = t("loading");\n boot.querySelector("[data-boot-recovery]").hidden = true;\n bootTimer = win.setTimeout(() => {\n bootTimer = 0;\n if (disposed || !boot) return;\n boot.querySelector("[data-boot-message]").textContent = t("loadingSlow");\n boot.querySelector("[data-boot-recovery]").hidden = false;\n }, 9e3);\n }\n function updateBoot(loading) {\n if (loading) {\n if (boot) {\n win.clearTimeout(bootFadeTimer);\n bootFadeTimer = 0;\n boot.inert = false;\n boot.removeAttribute("aria-hidden");\n boot.style.pointerEvents = "auto";\n boot.classList.remove("boot-leaving");\n return;\n }\n boot = document.createElement("section");\n boot.className = "boot";\n boot.tabIndex = -1;\n boot.setAttribute("aria-labelledby", "boot-title");\n boot.setAttribute("aria-describedby", "boot-status");\n boot.style.pointerEvents = "auto";\n boot.innerHTML = `<div class="boot-brand" aria-hidden="true"><span>C</span>Caisual</div>\n <div class="boot-content"><h1 id="boot-title">${escape(manifest.name)}</h1>\n <div class="boot-progress" aria-hidden="true"><span></span></div>\n <p class="boot-status" id="boot-status" role="status" aria-live="polite" aria-atomic="true"><span class="sr">${escape(manifest.name)}. </span><span data-boot-message></span></p>\n <div class="boot-recovery"><div class="row" data-boot-recovery hidden>${button("reload", "retry", \' class="primary"\')}${button("exit-now", "exit", \' class="quiet"\')}</div></div>\n </div>`;\n if (input.configuration.coverUrl) {\n const cover = document.createElement("img");\n cover.className = "boot-cover";\n cover.alt = "";\n cover.setAttribute("aria-hidden", "true");\n cover.addEventListener("error", () => {\n cover.hidden = true;\n }, { once: true });\n cover.src = input.configuration.coverUrl;\n boot.prepend(cover);\n }\n elements.append(boot);\n resetBootWait();\n } else if (boot && !boot.inert) {\n boot.inert = true;\n boot.setAttribute("aria-hidden", "true");\n boot.style.pointerEvents = "none";\n boot.classList.add("boot-leaving");\n const remove = () => {\n win.clearTimeout(bootTimer);\n bootTimer = 0;\n boot?.remove();\n boot = null;\n bootFadeTimer = 0;\n };\n if (win.matchMedia?.("(prefers-reduced-motion: reduce)").matches) remove();\n else bootFadeTimer = win.setTimeout(remove, 420);\n }\n }\n const dispatch = (action) => {\n if (disposed) return;\n model = reduceUi(model, action);\n render();\n };\n const announce = (text) => {\n if (live.textContent !== text) live.textContent = text;\n };\n const controls = () => [...root.querySelectorAll(\'button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),[tabindex="0"]\')].filter((el) => el.tabIndex !== -1 && !el.closest("[hidden]"));\n const soloMode = (mode) => (mode === null || manifest.modes.some((item) => item.id === mode)) && risolviModalita(manifest, mode).players.max === 1;\n const solo = () => model.session?.room?.limits.max === 1;\n const roomCode = () => solo() ? null : model.session?.room?.code ?? null;\n const setPanel = (panel) => {\n copyFallback = null;\n dispatch({ type: "panel", panel });\n };\n const close = () => {\n const current = phase(model.session), panel = visiblePanel(model);\n if (current === "boot") return;\n if (current === "home") setPanel("home");\n else if (current === "lobby" && panel !== "room") setPanel("room");\n else setPanel(null);\n };\n const toggle = () => {\n if (visiblePanel(model)) close();\n else setPanel(model.session?.room && !model.session.room.replay ? "room" : "home");\n };\n async function perform(op, args, after) {\n const token = ++operation;\n dispatch({ type: "error", code: null });\n dispatch({ type: "busy", busy: true });\n try {\n await input.bridge.request(op, args);\n if (token === operation && !disposed) await after?.();\n } catch (error) {\n if (token === operation && !disposed && error.code !== "cancelled") dispatch({ type: "error", code: error.code ?? "offline" });\n } finally {\n if (token === operation && !disposed) dispatch({ type: "busy", busy: false });\n }\n }\n function updateVoice() {\n const container = root.querySelector("[data-voice-panel]");\n if (container) updateVoicePanel(container, { manifest, session: model.session, t, error: voiceError, pending: voicePending });\n const toggle2 = root.querySelector("[data-voice-toggle]"), voice = model.session?.voice;\n if (toggle2) {\n toggle2.dataset.voiceState = voice?.state ?? "off";\n toggle2.dataset.muted = String(voice?.muted ?? false);\n toggle2.setAttribute("aria-label", `${t("voice")}: ${voice ? voiceStatus(voice, t) : t("voiceOff")}`);\n toggle2.textContent = voice?.state === "on" && !voice.muted ? "\\u25CF" : "\\u25CB";\n }\n }\n async function performVoice(op, args) {\n const sessionId = model.session?.id, epoch = input.bridge.epoch, volume = op === "voice.setVolume";\n const token = volume ? voiceOperation : ++voiceOperation;\n const current = () => !disposed && model.session?.id === sessionId && input.bridge.epoch === epoch && token === voiceOperation;\n voiceError = null;\n if (!volume) voicePending = op;\n updateVoice();\n try {\n await input.bridge.request(op, args);\n } catch (error) {\n if (current()) voiceError = error.code ?? "voice_error";\n } finally {\n if (current()) {\n if (!volume) voicePending = null;\n updateVoice();\n }\n }\n }\n async function copyInvite() {\n const code = roomCode();\n if (!code) return;\n const url = input.inviteUrl(code);\n try {\n await win.navigator.clipboard.writeText(url);\n dispatch({ type: "notice", notice: t("copied") });\n } catch {\n copyFallback = url;\n render();\n root.querySelector(\'input[data-control="invite-link"]\')?.select();\n }\n }\n function invitation() {\n if (solo()) return "";\n const code = roomCode();\n if (!code) return `<p>${t("noRoom")}</p>`;\n return `<div class="row"><div class="grow"><small>${t("code")}</small><div class="code" data-room-code>${escape(code)}</div></div>${button("copy", "copy")}</div>${copyFallback ? `<label>${t("copyFailed")}<input data-control="invite-link" readonly value="${escape(copyFallback)}"></label>` : ""}`;\n }\n function navigation(panel) {\n const items = [];\n if (model.session?.room && !solo()) items.push(["room", "room"], ["invite", "copy"]);\n items.push(["friends", "friends"]);\n if (voiceEligible(manifest, model.session)) items.push(["voice", "voice"]);\n return `<nav class="tabs" aria-label="Caisual">${items.map(([id, key]) => button(`panel:${id}`, key, ` aria-current="${id === panel}"`)).join("")}</nav>`;\n }\n function footer() {\n const languages2 = escape(manifestLanguages(manifest).join(" \\xB7 "));\n return `<footer class="panel-footer"><label class="checkbox" title="${t("shortcut")}"><input type="checkbox" data-control="shortcut" aria-label="${t("shortcut")}"${model.shortcutEnabled ? " checked" : ""}>Shift+Tab</label><small data-game-languages title="${t("gameLanguages")}: ${languages2}" aria-label="${t("gameLanguages")}: ${languages2}">${languages2}</small></footer>`;\n }\n function home() {\n const selected = selectedMode(), action = primaryAction(manifest, model.mode), session = model.session;\n const description = resolveText(manifest.description, input.language, manifestLanguages(manifest)[0]);\n const singlePlayer = soloMode(model.mode), active = singlePlayer ? "singlePlayer" : "multiplayer";\n const modes = modeGroups[active], hasTabs = modeGroups.singlePlayer.length > 0 && modeGroups.multiplayer.length > 0;\n const playKey = singlePlayer ? "play" : input.crew?.getSnapshot().party ? "friendsPlay" : "createRoom";\n const resume = session?.resume && soloMode(session.resume.mode) === singlePlayer;\n return `${description ? `<p class="muted game-description" data-game-description title="${escape(description)}">${escape(description)}</p>` : ""}\n ${input.configuration.invite && phase(session) === "home" ? button("join-invite", input.bridge.watch ? "watch" : "joinInvite", \' class="primary"\', !session?.ready) : ""}\n ${hasTabs ? `<div class="experience-tabs" role="tablist" aria-label="${t("mode")}">${["singlePlayer", "multiplayer"].map((key) => button(`mode:${key}`, key, ` role="tab" id="tab-${key}" aria-selected="${key === active}" aria-controls="experience-panel" tabindex="${key === active ? 0 : -1}" data-mode="${escape(modeGroups[key][0].id)}"`)).join("")}</div>` : ""}\n <div class="stack home-content"${hasTabs ? ` role="tabpanel" id="experience-panel" aria-labelledby="tab-${active}"` : ""}>\n <div class="mode-details">${modes.length > 1 ? `<label>${t("mode")}<select data-control="mode"${disabled()}>${modes.map((mode) => `<option value="${escape(mode.id)}"${mode.id === model.mode ? " selected" : ""}>${escape(risolviPresentazione(manifest, mode.id, input.language).label)}</option>`).join("")}</select></label>` : `<h2 data-mode-label>${escape(risolviPresentazione(manifest, model.mode, input.language).label)}</h2>`}\n ${selected?.instructions ? `<p class="muted mode-instructions" data-mode-instructions title="${escape(resolveText(selected.instructions, input.language, manifestLanguages(manifest)[0]))}">${escape(resolveText(selected.instructions, input.language, manifestLanguages(manifest)[0]))}</p>` : ""}</div>\n ${resume ? `<div class="stack resume-action">${button("resume", "resume", "", !session.ready)}${singlePlayer ? "" : `<small>${escape(session.resume.code)}</small>`}</div>` : ""}\n <div class="stack play-actions">${!singlePlayer && selected?.matchmaking ? button("match", "find", \' class="primary"\', !selected.matchmaking.defaults || !session?.ready) : ""}\n ${action ? button("play", playKey, singlePlayer || !selected?.matchmaking ? \' class="primary"\' : "", !session?.ready) : ""}</div>\n ${!singlePlayer ? `<div class="split home-links">${button("panel:join", "join", \' class="quiet"\', !session?.ready)}${manifest.spectators ? button("panel:watch", "watch", \' class="quiet"\', !session?.ready) : ""}</div>` : ""}\n ${!singlePlayer ? `<div class="stack home-links">${button("panel:friends", "friends", \' class="quiet"\')}</div>` : ""}\n ${solo() ? button("panel:exit", "exit", \' class="quiet"\') : ""}\n </div>`;\n }\n function room() {\n const session = model.session, room2 = session?.room;\n if (!room2) return `<p>${t("noRoom")}</p>`;\n const own = room2.players.find((player) => player.id === room2.you), lobby = room2.status === "lobby" && session?.kind === "room";\n const canRole = session?.kind === "room" && (lobby || room2.status === "playing" && room2.requestRole);\n const reason = startReason(manifest, session);\n return `${invitation()}<ul class="roster" aria-label="${t("room")}">${room2.players.map((p) => `<li data-player-id="${escape(p.id)}"><span class="name">${escape(p.name)} ${p.id === room2.you ? `<small>(${t("you")})</small>` : ""}</span>${p.id === room2.host ? `<span class="badge">${t("host")}</span>` : ""}${p.role ? `<small>${escape(resolveText(manifest.roles.find((r) => r.id === p.role)?.label, input.language, manifestLanguages(manifest)[0], p.role))}</small>` : ""}${p.team ? `<small>${t("team")} ${p.team}</small>` : ""}<small>${!p.connected ? t("away") : lobby ? t(p.ready ? "ready" : "unready") : ""}</small></li>`).join("")}</ul>\n ${canRole && manifest.roles.length ? `<label>${t("role")}<select data-control="role"${disabled()}><option value="" disabled${!own?.role ? " selected" : ""}>${t("role")}</option>${manifest.roles.map((role) => `<option value="${escape(role.id)}"${role.id === own?.role ? " selected" : ""}>${escape(resolveText(role.label, input.language, manifestLanguages(manifest)[0], role.id))}</option>`).join("")}</select></label>` : ""}\n ${lobby && manifest.teams ? `<label>${t("team")}<select data-control="team"${disabled()}><option value="" disabled${!own?.team ? " selected" : ""}>${t("team")}</option>${Array.from({ length: manifest.teams.max }, (_, i) => `<option value="${i + 1}"${own?.team === i + 1 ? " selected" : ""}>${t("team")} ${i + 1}</option>`).join("")}</select></label>` : ""}\n ${lobby ? `<div class="row">${button("ready", own?.ready ? "unready" : "ready", \' class="primary"\', room2.connection !== "connected")}${room2.host === room2.you ? button("start", "start", "", reason !== null) : ""}</div>${reason ? `<p class="muted" data-start-reason>${t(reason)}</p>` : ""}` : ""}\n ${session?.kind === "watch" ? `<p>${t("watching")} \\xB7 ${t("delay", { n: (room2.delayMs ?? 0) / 1e3 })}</p>` : ""}\n ${navigation("room")}${button("panel:exit", "exit", \' class="quiet"\')}`;\n }\n function crew() {\n const provider = input.crew, state = provider?.getSnapshot();\n if (!provider || provider.unavailable || !state?.you) return `<p>${t(provider?.unavailable === "local" ? "localCrew" : "loginCrew")}</p>`;\n const online = state.friends.filter((friend) => friend.online), party = state.party;\n const person = (p) => `<li>${p.game ? `<img class="game-icon" src="${escape(p.game.iconUrl)}" alt="" />` : ""}<span class="name">${escape(p.name)}<small>${p.game ? ` \\xB7 ${escape(p.game.name)}` : ""}</small></span>${p.room && p.game ? button("follow", "follow", ` data-code="${escape(p.room.code)}" data-game="${escape(p.game.slug)}"`) : ""}${party?.leader === state.you.id && !party.members.some((member) => member.id === p.id) ? button("party-invite", "inviteParty", ` data-player="${escape(p.id)}"`) : ""}</li>`;\n return `${!state.connected ? `<p>${t("reconnecting")}</p>` : ""}${party ? `<ul class="roster">${party.members.map(person).join("")}</ul>${button("party-leave", "leaveParty")}` : button("party-create", "createParty")}\n ${state.invites.map((invite) => `<div class="row"><span class="grow">${escape(invite.from.name)}</span>${button("party-accept", "accept", ` data-party="${escape(invite.party)}"`)}${button("party-decline", "decline", ` data-party="${escape(invite.party)}"`)}</div>`).join("")}\n ${state.follow ? `<div class="row"><span class="grow"><img class="game-icon" src="${escape(state.follow.game.iconUrl)}" alt="" /> ${escape(state.follow.from.name)} \\xB7 ${escape(state.follow.game.name)}</span>${button("follow", "follow", ` data-code="${escape(state.follow.code)}" data-game="${escape(state.follow.game.slug)}"`)}</div>` : ""}\n <h2>${t("online")}</h2>${online.length ? `<ul class="roster">${online.map(person).join("")}</ul>` : `<p class="muted">${t("noFriends")}</p>`}`;\n }\n function content(panel) {\n switch (panel) {\n case "home":\n if (model.session?.room?.replay) return `${button("close", "back")}${button("exit-now", "exit")}`;\n return home();\n case "room":\n return room();\n case "invite":\n return invitation();\n case "friends":\n return crew();\n case "voice":\n return \'<div class="stack" data-voice-panel></div>\';\n case "join":\n case "watch":\n return `<form class="stack" data-form="${panel}"><label>${t("code")}<input data-control="code" name="code" autocomplete="off" autocapitalize="characters" spellcheck="false" maxlength="16" value="${escape(codeDraft)}" required></label><button class="primary" type="submit"${disabled()}>${t(panel === "join" ? "join" : "watch")}</button></form>`;\n case "attaching":\n case "matching":\n return `<p role="status">${t(panel === "matching" ? "matching" : "joining")}</p>${model.session?.waiting ? `<p>${t("queue", { n: model.session.waiting.players, max: model.session.waiting.max })}</p>` : ""}<button type="button" data-action="cancel">${t("cancel")}</button>`;\n case "countdown":\n return `<p>${t("starting")}</p><div class="countdown" data-countdown></div>`;\n case "boot":\n return "";\n case "error":\n return `<p role="alert">${t(model.session?.room?.connection === "replaced" ? "replaced" : "noRoom")}</p>${button("leave", "home")}${button("exit-now", "exit")}`;\n case "exit":\n return model.session?.kind === "room" && phase(model.session) !== "ended" ? `<p>${t(model.session.room?.persistent ? "leaveHint" : "temporaryHint")}</p>${invitation()}${button("disconnect-exit", "leaveNow", \' class="primary"\')}<p class="muted">${t("abandonHint")}</p>${button("leave-exit", "leaveRoom")}` : button("leave-exit", "exit", \' class="primary"\');\n }\n }\n function title(panel) {\n const keys = { boot: "loading", home: "home", room: "room", invite: "copy", friends: "friends", voice: "voice", join: "join", watch: "watch", attaching: "joining", matching: "matching", countdown: "starting", error: "error", exit: "exit" };\n return t(keys[panel]);\n }\n function updateCountdown() {\n const at = model.session?.room?.countdownAt, now = input.bridge.serverTime();\n const value = at === null || at === void 0 || now === null ? "..." : String(Math.max(0, Math.round((at - now) / 1e3)));\n const node = root.querySelector("[data-countdown]");\n if (node && node.textContent !== value) {\n node.textContent = value;\n announce(`${t("starting")} ${value}`);\n }\n }\n function geometry() {\n geometryFrame = 0;\n if (disposed || !input.bridge.epoch || !model.session) return;\n const frame = gameViewport(input.frame), { scaleX, scaleY } = frame;\n const reservedRects = [...root.querySelectorAll("[data-reserve]")].map((el) => {\n const rect = el.getBoundingClientRect(), left = Math.max(frame.left, rect.left), top = Math.max(frame.top, rect.top), right = Math.min(frame.right, rect.right), bottom = Math.min(frame.bottom, rect.bottom);\n return { x: Math.max(0, Math.round((left - frame.left) * scaleX)), y: Math.max(0, Math.round((top - frame.top) * scaleY)), width: Math.max(0, Math.round((right - left) * scaleX)), height: Math.max(0, Math.round((bottom - top) * scaleY)) };\n }).filter((rect) => rect.width && rect.height).slice(0, 8);\n const view = { inputBlocked: phase(model.session) === "boot" || !!visiblePanel(model), reservedRects, safeArea: measureSafeArea(input.frame, safeProbe), shortcutEnabled: model.shortcutEnabled };\n const serialized = `${input.bridge.epoch}:${JSON.stringify(view)}`;\n if (lastView === serialized) return;\n lastView = serialized;\n void input.bridge.request("overlay.view", view).catch(async (error) => {\n if (error?.code === "invalid_request" && lastView === serialized) {\n const { safeArea, ...legacy } = view;\n try {\n await input.bridge.request("overlay.view", legacy);\n return;\n } catch {\n }\n }\n if (lastView === serialized) lastView = "";\n });\n }\n function resize() {\n if (!geometryFrame) geometryFrame = win.requestAnimationFrame(geometry);\n }\n const replayLink = () => {\n const id = model.session?.room?.replayId;\n return manifest.replays && id && input.replayUrl ? input.replayUrl(id) : null;\n };\n function replayActions() {\n const url = replayLink();\n return url ? `<a class="primary replay-link" href="${escape(url)}">${t("watchReplay")}</a>${button("copy-replay", "copyReplay")}` : "";\n }\n const replayTime = (ms) => `${Math.floor(ms / 6e4)}:${String(Math.floor(ms / 1e3) % 60).padStart(2, "0")}`;\n function updateReplayPosition() {\n const playback = model.session?.room?.replay;\n if (!playback) return;\n const slider = root.querySelector("[data-control=replay-seek]");\n if (slider && slider.dataset.editing !== "true") slider.value = String(playback.positionMs);\n const time = root.querySelector("[data-replay-time]");\n if (time) time.textContent = `${replayTime(playback.positionMs)} / ${replayTime(playback.durationMs)}`;\n }\n function replayBar() {\n const playback = model.session?.room?.replay;\n if (!playback) return "";\n return `<div class="replay-controls" data-reserve role="region" aria-label="${t("replay")}">\n ${button(playback.paused ? "replay-play" : "replay-pause", playback.paused ? "replayPlay" : "replayPause")}\n <label class="replay-position">${t("replaySeek")}<input type="range" data-control="replay-seek" min="0" max="${playback.durationMs}" step="1" value="${playback.positionMs}" aria-label="${t("replaySeek")}"></label>\n <span data-replay-time>${replayTime(playback.positionMs)} / ${replayTime(playback.durationMs)}</span>\n <label>${t("replaySpeed")}<select data-control="replay-speed">${[0.5, 1, 2, 4].map((speed) => `<option value="${speed}"${speed === playback.speed ? " selected" : ""}>${speed}\\xD7</option>`).join("")}</select></label>\n ${playback.truncated ? `<small>${t("replayTruncated")}</small>` : ""}</div>`;\n }\n function resultBar() {\n const presentation = matchPresentation(model.session);\n if (!presentation) return `<strong>${t("ended")}</strong>`;\n const room2 = model.session.room, { result } = presentation;\n const unit = result.unit && ["points", "time", "distance"].includes(result.unit) ? t(result.unit) : result.unit;\n const rows = result.standings.map((p, i) => {\n const name = room2.players.find((player) => player.id === p.playerId).name;\n const score = p.score === void 0 ? "" : `<span>${escape(String(p.score))}${unit ? ` ${escape(unit)}` : ""}</span>`;\n return `<li><span>${p.rank ?? i + 1}. ${escape(name)}</span>${score}</li>`;\n }).join("");\n return `<strong data-outcome>${t(presentation.outcome)}</strong><ol class="standings" aria-label="${t("standings")}">${rows}</ol>`;\n }\n function rematchBar() {\n const session = model.session, room2 = session?.room;\n if (!room2 || room2.status !== "finished" || solo()) return "";\n const active = room2.players.filter((p) => p.connected && p.role !== "spectator");\n const ready = active.filter((p) => p.ready), host2 = session.kind === "room" && room2.host === room2.you;\n const canStart = room2.connection === "connected" && active.length >= room2.limits.min && ready.length === active.length;\n return `<small role="status" data-rematch-ready>${t("rematchReady", { n: ready.length, max: active.length })}</small>\n ${ready.length ? `<small data-rematch-players>${ready.map((p) => escape(p.name)).join(", ")}</small>` : ""}\n ${room2.rematch?.autoStart ? "" : host2 ? button("restart", "rematchStart", \' class="primary"\', !canStart) : `<small>${t("waitHost")}</small>`}`;\n }\n function render() {\n if (disposed) return;\n const panel = visiblePanel(model), current = phase(model.session), room2 = model.session?.room;\n const focused = root.activeElement;\n const focusPeer = focused?.dataset.peer;\n const focusKey = focused?.dataset.control ? ["control", focused.dataset.control] : focused?.dataset.action ? ["action", focused.dataset.action] : null;\n const previousScroll = root.querySelector(".dialog")?.scrollTop ?? 0;\n const selection = focused?.tagName === "INPUT" ? { start: focused.selectionStart, end: focused.selectionEnd } : null;\n const crewState = input.crew?.getSnapshot(), invitations = (crewState?.invites.length ?? 0) + (crewState?.follow ? 1 : 0);\n const label = current === "watching" ? t("watching") : room2?.connection === "reconnecting" ? t("reconnecting") : solo() ? "Caisual" : room2?.code ?? "Caisual";\n surface.innerHTML = current === "boot" ? "" : `<div class="pill" data-reserve><button type="button" data-action="menu" aria-label="${t("menu")}" aria-expanded="${!!panel}">C<span aria-hidden="true"><small>${escape(label)}</small></span></button>${voiceEligible(manifest, model.session) && model.session?.kind === "room" ? `<button type="button" class="voice-toggle" data-voice-toggle data-action="panel:voice"></button>` : ""}${invitations ? `<button type="button" data-action="panel:friends" aria-label="${t("friends")} (${invitations})">${invitations}</button>` : ""}</div>\n ${!panel ? replayBar() : ""}\n ${current === "ended" && !panel && !room2?.replay ? `<div class="ended" data-reserve role="region" aria-label="${t("ended")}">${resultBar()}${replayActions()}${canPlayAgain(model.session) ? button("again", "again", \' class="primary"\') : model.session?.kind === "room" && room2?.status !== "finished" && !solo() ? `<small>${t("waitHost")}</small>` : ""}${rematchBar()}${button("panel:home", "homeMenu")}</div>` : ""}\n ${panel ? `<div class="backdrop${panel === "home" ? " home" : ""}"><section class="dialog${panel === "friends" ? " wide" : ""}" role="dialog" aria-modal="true" aria-labelledby="panel-title" tabindex="-1"><div class="top">${panel === "home" ? `<div class="game-heading">${input.configuration.iconUrl ? `<img class="game-icon game-icon-title" src="${escape(input.configuration.iconUrl)}" alt="" />` : ""}<h1 id="panel-title">${escape(manifest.name)}</h1></div>` : `<h2 id="panel-title">${title(panel)}</h2>`}<button type="button" data-action="close" aria-label="${t("close")}">\\xD7</button></div><div class="stack">${content(panel)}${model.error ? `<p class="error" role="alert" data-error>${t(errorText(model.error))}</p>${model.error === "version_outdated" ? button("reload-game", "reloadGame", \' class="primary"\') : ""}` : ""}${model.session?.resumeError ? `<p class="error" role="alert">${t("saveFailed")}</p>` : ""}${model.notice ? `<p class="notice" role="status">${escape(model.notice)}</p>` : ""}</div>${panel === "home" || panel === "room" ? footer() : ""}</section></div>` : ""}`;\n for (const element of surface.querySelectorAll(".pill,.backdrop,.ended,.replay-controls")) element.style.pointerEvents = "auto";\n const backdrop = root.querySelector(".backdrop.home");\n if (backdrop && input.configuration.coverUrl) backdrop.style.backgroundImage = `linear-gradient(#0b151c99,#0b151cee),url(${JSON.stringify(input.configuration.coverUrl)})`;\n host.dataset.phase = current;\n host.dataset.panel = panel ?? "";\n input.frame.inert = !!panel || oldInert;\n if (panel) input.frame.tabIndex = -1;\n else if (oldTabIndex === null) input.frame.removeAttribute("tabindex");\n else input.frame.setAttribute("tabindex", oldTabIndex);\n updateVoice();\n updateBoot(current === "boot");\n const dialog = root.querySelector(".dialog");\n if (dialog) dialog.scrollTop = previousScroll;\n const focusPanel = current === "boot" ? boot : dialog;\n const matched = focusKey ? [...root.querySelectorAll(`[data-${focusKey[0]}]`)].find((el) => el.getAttribute(`data-${focusKey[0]}`) === focusKey[1] && el.dataset.peer === focusPeer) : null;\n if (!panel && wasModal && !input.frame.inert && input.frame.isConnected) {\n input.frame.focus({ preventScroll: true });\n input.frame.contentWindow?.focus();\n } else if (matched && (!panel || focusPanel?.contains(matched)) && !matched.hasAttribute("disabled")) {\n matched.focus({ preventScroll: true });\n if (matched.tagName === "INPUT" && selection?.start !== null && selection?.end !== null && selection) {\n try {\n matched.setSelectionRange(selection.start, selection.end);\n } catch {\n }\n }\n } else if (panel && (!wasModal || focused)) (current === "boot" ? boot : dialog?.querySelector(\'select,input,button:not([data-action="close"]):not(:disabled)\') ?? dialog)?.focus({ preventScroll: true });\n wasModal = !!panel;\n if (lastPhase !== current) {\n lastPhase = current;\n announce(current === "boot" ? "" : t({ home: "home", attaching: "joining", matching: "matching", lobby: "room", countdown: "starting", playing: "playing", ended: "ended", watching: "watching", error: "error" }[current]));\n }\n updateCountdown();\n resize();\n }\n const click = (event) => {\n const target = event.target.closest("button[data-action]");\n if (!target || target.disabled) return;\n const action = target.dataset.action;\n event.stopPropagation();\n if (action.startsWith("mode:") && target.dataset.mode) {\n dispatch({ type: "mode", mode: target.dataset.mode });\n return;\n }\n if (action.startsWith("panel:")) {\n setPanel(action.slice(6));\n return;\n }\n switch (action) {\n case "replay-play":\n void perform("replay.play", {});\n break;\n case "replay-pause":\n void perform("replay.pause", {});\n break;\n case "copy-replay": {\n const url = replayLink();\n if (url) void Promise.resolve().then(() => win.navigator.clipboard.writeText(url)).then(() => {\n announce(t("replayCopied"));\n }, () => {\n setPanel("home");\n dispatch({ type: "notice", notice: `${t("copyFailed")} ${url}` });\n });\n break;\n }\n case "menu":\n toggle();\n break;\n case "close":\n close();\n break;\n case "play": {\n const selected = primaryAction(manifest, model.mode);\n if (selected) void perform(selected.op, { mode: model.mode });\n break;\n }\n case "match":\n void perform("room.match", { mode: model.mode });\n break;\n case "join-invite":\n if (input.configuration.invite) void perform(input.bridge.watch ? "room.watch" : "room.join", { code: input.configuration.invite });\n break;\n case "resume":\n void perform("session.resume", {});\n break;\n case "cancel":\n void perform("session.cancel", {});\n break;\n case "ready":\n void perform("room.ready", { ready: !model.session?.room?.players.find((p) => p.id === model.session?.room?.you)?.ready });\n break;\n case "start":\n void perform("room.start", {});\n break;\n case "restart":\n void perform("room.restart", {});\n break;\n case "copy":\n void copyInvite();\n break;\n case "voice-join":\n void performVoice("voice.join", {});\n break;\n case "voice-mute":\n void performVoice("voice.mute", { muted: !model.session?.voice?.muted });\n break;\n case "voice-leave":\n void performVoice("voice.leave", {});\n break;\n case "again": {\n if (!canPlayAgain(model.session)) break;\n if (model.session?.kind === "local") void perform("local.start", { mode: model.session.mode ?? model.mode });\n else if (model.session?.room?.status === "finished") void perform("room.restart", {});\n else if (solo()) void perform("room.create", { mode: model.session?.room?.mode ?? null });\n else {\n inviteAfterCreate = roomCode();\n void perform("room.create", { mode: model.session?.room?.mode ?? null }).then(() => {\n if (model.error) inviteAfterCreate = void 0;\n });\n }\n break;\n }\n case "disconnect-exit":\n void perform("session.disconnect", {}, input.exit);\n break;\n case "leave-exit":\n void perform("session.leave", {}, input.exit);\n break;\n case "leave":\n void perform("session.leave", {}, () => setPanel("home"));\n break;\n case "exit-now":\n input.exit();\n break;\n case "reload-game":\n input.bridge.reload();\n break;\n case "reload":\n boot?.focus({ preventScroll: true });\n resetBootWait();\n input.frame.src = input.frame.src;\n break;\n case "party-create":\n input.crew?.party.create();\n break;\n case "party-leave":\n input.crew?.party.leave();\n break;\n case "party-invite":\n input.crew?.party.invite(target.dataset.player);\n break;\n case "party-accept":\n input.crew?.party.accept(target.dataset.party);\n break;\n case "party-decline":\n input.crew?.party.decline(target.dataset.party);\n break;\n case "follow":\n input.crew?.follow(target.dataset.game, target.dataset.code);\n break;\n }\n };\n const change = (event) => {\n const target = event.target, field = target.dataset.control;\n if (field === "replay-seek") {\n delete target.dataset.editing;\n void perform("replay.seek", { positionMs: Number(target.value) });\n return;\n }\n if (field === "replay-speed") {\n void perform("replay.speed", { speed: Number(target.value) });\n return;\n }\n if (field === "voice-volume") {\n target.dataset.editing = "true";\n void performVoice("voice.setVolume", { playerId: target.dataset.peer, volume: Number(target.value) }).finally(() => {\n delete target.dataset.editing;\n updateVoice();\n });\n return;\n }\n if (field === "mode") dispatch({ type: "mode", mode: target.value });\n if (field === "role") void perform(model.session?.room?.status === "lobby" ? "room.role" : "room.requestRole", { role: target.value });\n if (field === "team") void perform("room.team", { team: Number(target.value) });\n if (field === "shortcut") {\n const enabled = target.checked;\n try {\n win.localStorage.setItem("caisual-overlay-shortcut-v1", enabled ? "on" : "off");\n } catch {\n }\n dispatch({ type: "shortcut", enabled });\n }\n };\n const submit = (event) => {\n const form = event.target;\n if (!form.dataset.form) return;\n event.preventDefault();\n const code = normalizeInvite(form.querySelector(\'input[data-control="code"]\').value);\n if (!code) {\n dispatch({ type: "error", code: "invalid_code" });\n return;\n }\n void perform(form.dataset.form === "watch" ? "room.watch" : "room.join", { code });\n };\n const keydown = (event) => {\n const panel = visiblePanel(model);\n const tab = root.activeElement;\n if (tab?.getAttribute("role") === "tab" && ["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {\n event.preventDefault();\n event.stopImmediatePropagation();\n const tabs = [...root.querySelectorAll(\'[role="tab"]:not(:disabled)\')];\n const next = event.key === "Home" ? tabs[0] : event.key === "End" ? tabs.at(-1) : tabs.find((item) => item !== tab);\n if (next) {\n next.focus();\n next.click();\n }\n return;\n }\n if (panel && event.key === "Escape") {\n event.preventDefault();\n event.stopImmediatePropagation();\n close();\n return;\n }\n if (panel && event.key === "Tab") {\n const items = controls().filter((el) => el.closest(panel === "boot" ? ".boot" : ".dialog")), first = items[0], last = items.at(-1);\n if (!first) {\n event.preventDefault();\n return;\n }\n if (event.shiftKey && (root.activeElement === first || !items.includes(root.activeElement))) {\n event.preventDefault();\n last?.focus();\n } else if (!event.shiftKey && (root.activeElement === last || !items.includes(root.activeElement))) {\n event.preventDefault();\n first.focus();\n }\n } else if (!panel && model.shortcutEnabled && event.key === "Tab" && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) {\n event.preventDefault();\n toggle();\n }\n };\n root.addEventListener("input", (event) => {\n const node = event.target;\n if (node.dataset.control === "code") codeDraft = node.value;\n if (node.dataset.control === "voice-volume" || node.dataset.control === "replay-seek") node.dataset.editing = "true";\n });\n root.addEventListener("click", click);\n root.addEventListener("change", change);\n root.addEventListener("submit", submit);\n win.addEventListener("keydown", keydown, true);\n win.addEventListener("resize", resize);\n win.addEventListener("scroll", resize, true);\n win.visualViewport?.addEventListener("resize", resize);\n win.visualViewport?.addEventListener("scroll", resize);\n const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(resize) : null;\n observer?.observe(input.frame);\n const countdownTimer = win.setInterval(updateCountdown, 250);\n stops.push(input.bridge.subscribe((session) => {\n const previous = model.session;\n if (!session || session.id !== previous?.id) {\n voiceOperation++;\n voicePending = null;\n voiceError = null;\n }\n if (!session) {\n lastView = "";\n operation++;\n model.busy = false;\n }\n const withoutPosition = (state) => state?.room?.replay ? { ...state, room: { ...state.room, replay: { ...state.room.replay, positionMs: 0 } } } : state;\n if (previous?.room?.replay && session?.room?.replay && JSON.stringify(withoutPosition(previous)) === JSON.stringify(withoutPosition(session))) {\n model = reduceUi(model, { type: "session", session });\n updateReplayPosition();\n } else if (previous && session && JSON.stringify({ ...previous, voice: null }) === JSON.stringify({ ...session, voice: null })) {\n model = reduceUi(model, { type: "session", session });\n updateVoice();\n } else dispatch({ type: "session", session });\n const created = roomCode();\n if (inviteAfterCreate !== void 0 && created && created !== inviteAfterCreate) {\n inviteAfterCreate = void 0;\n setPanel("invite");\n dispatch({ type: "notice", notice: t("newRoom") });\n void copyInvite();\n }\n }));\n stops.push(input.bridge.onOpen((panel) => setPanel(panel)), input.bridge.onShortcut(toggle), input.bridge.onError(({ error }) => {\n if (!visiblePanel(model)) setPanel("room");\n dispatch({ type: "error", code: error.code });\n }));\n if (input.crew) stops.push(input.crew.subscribe(() => {\n const state = input.crew.getSnapshot();\n if (state.follow || state.invites.length) announce(t("friends"));\n render();\n }));\n render();\n return { element: host, root, dispose() {\n disposed = true;\n operation++;\n stops.forEach((stop) => stop());\n observer?.disconnect();\n win.clearInterval(countdownTimer);\n win.cancelAnimationFrame(geometryFrame);\n win.clearTimeout(bootTimer);\n win.clearTimeout(bootFadeTimer);\n win.removeEventListener("keydown", keydown, true);\n win.removeEventListener("resize", resize);\n win.removeEventListener("scroll", resize, true);\n win.visualViewport?.removeEventListener("resize", resize);\n win.visualViewport?.removeEventListener("scroll", resize);\n input.frame.inert = oldInert;\n if (oldTabIndex === null) input.frame.removeAttribute("tabindex");\n else input.frame.setAttribute("tabindex", oldTabIndex);\n void input.bridge.request("overlay.view", { inputBlocked: false, reservedRects: [], shortcutEnabled: false }).catch(() => {\n });\n host.remove();\n } };\n}\nexport {\n avviaHandshake,\n creaPonteOspite,\n eMessaggioReady,\n eRichiestaBiglietto,\n mountOverlay,\n overlayConfiguration,\n overlayLanguage,\n overlayLocale,\n styles as overlayStyles,\n stanzaDaMessaggio\n};\n');
4686
+ if (data.op === "subscribe") {
4687
+ const invia = () => {
4688
+ if (current()) porta.postMessage({ type: "caisual:crew-state", state: crew.getSnapshot() });
4689
+ };
4690
+ fermaCrew?.();
4691
+ fermaCrew = crew.subscribe(invia);
4692
+ invia();
4693
+ return;
4694
+ }
4695
+ const player = typeof data.player === "string" ? data.player : null;
4696
+ const party = typeof data.party === "string" ? data.party : null;
4697
+ if (data.op === "party") {
4698
+ if (data.action === "create") crew.party.create();
4699
+ else if (data.action === "leave") crew.party.leave();
4700
+ else if (data.action === "invite" && player) crew.party.invite(player);
4701
+ else if (data.action === "kick" && player) crew.party.kick(player);
4702
+ else if (data.action === "accept" && party) crew.party.accept(party);
4703
+ else if (data.action === "decline" && party) crew.party.decline(party);
4704
+ return;
4705
+ }
4706
+ if (data.op === "follow" && typeof data.slug === "string" && typeof data.code === "string" && CODICE.test(data.code)) {
4707
+ crew.follow(data.slug, data.code);
4708
+ }
4709
+ }
4710
+ input.finestra.addEventListener("message", listen);
4711
+ input.frame.addEventListener?.("load", loaded);
4712
+ poll();
4713
+ return {
4714
+ reload() {
4715
+ input.reload?.();
4716
+ },
4717
+ /** Il gioco e' collegato: serve al sito per sapere se il ponte ha agganciato il documento. */
4718
+ get collegato() {
4719
+ return port !== null;
4720
+ },
4721
+ invia(message) {
4722
+ if (!port || disposed) throw creaErrore("offline", "The game bridge is not connected.");
4723
+ port.postMessage(message);
4724
+ },
4725
+ dispose() {
4726
+ disposed = true;
4727
+ stopPolling();
4728
+ fermaCrew?.();
4729
+ fermaCrew = null;
4730
+ port?.close();
4731
+ port = null;
4732
+ input.finestra.removeEventListener("message", listen);
4733
+ input.frame.removeEventListener?.("load", loaded);
4734
+ }
4735
+ };
4736
+ }
4737
+ function avviaHandshake(input) {
4738
+ const bridge = creaPonteOspite(input);
4739
+ return () => bridge.dispose();
4740
+ }
4741
+ export {
4742
+ avviaHandshake,
4743
+ creaPonteOspite,
4744
+ eMessaggioReady,
4745
+ eRichiestaBiglietto,
4746
+ stanzaDaMessaggio
4747
+ };
4748
+ `);
5222
4749
  return;
5223
4750
  }
5224
4751
  if (url.pathname === "/__caisual/players" && (request.method === "GET" || request.method === "HEAD")) {
@@ -5252,7 +4779,8 @@ var DevService = class {
5252
4779
  gameOrigin: this.gameOrigin,
5253
4780
  portalOrigin: this.portalOrigin,
5254
4781
  slug: this.manifest.id,
5255
- manifest: this.manifest
4782
+ manifest: this.manifest,
4783
+ gameLanguages: manifestLanguages(this.manifest)
5256
4784
  });
5257
4785
  response.statusCode = 200;
5258
4786
  response.setHeader("Content-Type", "text/html; charset=utf-8");
@@ -5280,7 +4808,7 @@ var DevService = class {
5280
4808
  await this.handleKit(request, response, url);
5281
4809
  return;
5282
4810
  }
5283
- if (url.pathname === "/match" || url.pathname === "/rooms" || url.pathname === "/rooms/join" || url.pathname === "/rooms/watch" || /^\/rooms\/[^/]+(?:\/flush)?$/.test(url.pathname)) {
4811
+ if (url.pathname === "/match" || url.pathname === "/rooms" || url.pathname === "/rooms/join" || /^\/rooms\/[^/]+(?:\/flush)?$/.test(url.pathname)) {
5284
4812
  await this.handleLive(request, response, url);
5285
4813
  return;
5286
4814
  }
@@ -5441,10 +4969,6 @@ var DevService = class {
5441
4969
  await this.joinRoom(request, response, ticket, origin);
5442
4970
  return;
5443
4971
  }
5444
- if (url.pathname === "/rooms/watch" && request.method === "POST") {
5445
- await this.watchRoom(request, response, ticket, origin);
5446
- return;
5447
- }
5448
4972
  const match = /^\/rooms\/(g1-1\.[a-z0-9]{16})(?:\/(flush))?$/.exec(url.pathname);
5449
4973
  if (match !== null && match[1] !== void 0) {
5450
4974
  const localRoom = await this.loadLocalRoom(match[1]);
@@ -5453,16 +4977,13 @@ var DevService = class {
5453
4977
  }
5454
4978
  if (match[2] === "flush" && request.method === "POST") {
5455
4979
  const flushed = await localRoom.room.flush();
5456
- sendJson(response, {
5457
- scores: flushed.scores.length,
5458
- ended: flushed.ended !== null
5459
- }, 200, origin);
4980
+ sendJson(response, { ended: flushed.ended !== null }, 200, origin);
5460
4981
  return;
5461
4982
  }
5462
4983
  if (match[2] === void 0 && request.method === "GET") {
5463
4984
  const info = await localRoom.room.info();
5464
4985
  if (info === null) throw new DevHttpError(404, "room_not_found", "The room was not found.");
5465
- sendJson(response, info, 200, origin);
4986
+ sendJson(response, { ...info, network: localRoom.room.network() }, 200, origin);
5466
4987
  return;
5467
4988
  }
5468
4989
  }
@@ -5472,9 +4993,6 @@ var DevService = class {
5472
4993
  }
5473
4994
  }
5474
4995
  async createRoom(request, response, ticket, origin) {
5475
- if (this.definition === null) {
5476
- throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
5477
- }
5478
4996
  const body = object(await readBody(request));
5479
4997
  if (body === null || !Object.hasOwn(body, "mode") || body.mode !== null && typeof body.mode !== "string") {
5480
4998
  throw new DevHttpError(400, "invalid_request", "mode must be null or a valid mode name.");
@@ -5498,9 +5016,6 @@ var DevService = class {
5498
5016
  );
5499
5017
  }
5500
5018
  async startMatch(request, response, ticket, origin) {
5501
- if (this.definition === null) {
5502
- throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
5503
- }
5504
5019
  const body = object(await readBody(request));
5505
5020
  if (body === null || !Object.hasOwn(body, "mode") || !Object.hasOwn(body, "key") || Object.keys(body).some((field) => field !== "mode" && field !== "key" && field !== "n")) {
5506
5021
  throw new DevHttpError(400, "invalid_request", "The match request must contain only mode, key and n.");
@@ -5513,7 +5028,8 @@ var DevService = class {
5513
5028
  if (mode === void 0) {
5514
5029
  throw new DevHttpError(400, "invalid_request", "The matchmaking mode does not exist.");
5515
5030
  }
5516
- if (mode.execution === "local") throw new DevHttpError(400, "invalid_request", "Local modes cannot use matchmaking.");
5031
+ if (modalitaLocale(this.manifest, mode.id)) throw new DevHttpError(400, "mode_local", MODE_LOCAL_MESSAGE);
5032
+ if (this.definition === null) throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
5517
5033
  if (mode.matchmaking === void 0) {
5518
5034
  throw new DevHttpError(400, "invalid_request", "This mode does not support matchmaking.");
5519
5035
  }
@@ -5541,30 +5057,28 @@ var DevService = class {
5541
5057
  players: this.manifest.players,
5542
5058
  lobby: this.manifest.lobby,
5543
5059
  persistent: this.manifest.persistent,
5544
- spectators: this.manifest.spectators,
5545
5060
  roles: this.manifest.roles,
5546
5061
  teams: this.manifest.teams,
5547
5062
  modes: this.manifest.modes,
5548
5063
  voice: this.manifest.voice
5549
5064
  };
5550
5065
  }
5551
- async openLocalRoom(mode, creator) {
5066
+ async openLocalRoom(mode, creator, origin = "player") {
5067
+ if (modalitaLocale(this.manifest, mode)) throw new DevHttpError(400, "mode_local", MODE_LOCAL_MESSAGE);
5552
5068
  if (this.definition === null) {
5553
5069
  throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
5554
5070
  }
5555
- if (modalitaLocale(this.manifest, mode)) throw new DevHttpError(400, "invalid_request", "Local modes cannot create rooms.");
5556
5071
  const roomId = `g1-1.${randomUniform("abcdefghijklmnopqrstuvwxyz0123456789", 16)}`;
5557
5072
  const room = await createNodeRoom(
5558
5073
  this.definition,
5559
5074
  this.roomManifest(),
5560
5075
  {
5561
5076
  storageFile: join3(this.root, ".caisual-dev", "rooms", `${roomId}.json`),
5562
- deposito: this.deposito,
5563
5077
  dailyDay: this.day
5564
5078
  }
5565
5079
  );
5566
5080
  try {
5567
- const created = await room.create(roomId, mode, creator);
5081
+ const created = await room.create(roomId, mode, creator, origin);
5568
5082
  if (!created) throw new Error("The room could not be created.");
5569
5083
  } catch (cause) {
5570
5084
  await room.close();
@@ -5598,6 +5112,7 @@ var DevService = class {
5598
5112
  const pending = this.roomLoads.get(roomId);
5599
5113
  if (pending !== void 0) return pending;
5600
5114
  const record2 = this.roomIndex.get(roomId);
5115
+ if (record2 !== void 0 && modalitaLocale(this.manifest, record2.mode)) throw new DevHttpError(400, "mode_local", MODE_LOCAL_MESSAGE);
5601
5116
  if (record2 === void 0 || record2.game !== this.manifest.id || this.definition === null) {
5602
5117
  return void 0;
5603
5118
  }
@@ -5616,7 +5131,6 @@ var DevService = class {
5616
5131
  this.roomManifest(),
5617
5132
  {
5618
5133
  storageFile: join3(this.root, ".caisual-dev", "rooms", `${record2.roomId}.json`),
5619
- deposito: this.deposito,
5620
5134
  dailyDay: this.day
5621
5135
  }
5622
5136
  );
@@ -5664,19 +5178,6 @@ var DevService = class {
5664
5178
  }
5665
5179
  return { roomId, localRoom };
5666
5180
  }
5667
- async watchRoom(request, response, ticket, origin) {
5668
- const body = object(await readBody(request));
5669
- const { roomId, localRoom } = await this.resolveLocalRoom(body, ticket.game);
5670
- const permission = await localRoom.room.canWatch();
5671
- if (!permission.ok) {
5672
- throw new DevHttpError(
5673
- permission.code === "room_not_found" ? 404 : 409,
5674
- permission.code,
5675
- this.roomErrorMessage(permission.code)
5676
- );
5677
- }
5678
- sendJson(response, this.watchResponse(roomId, localRoom.code, playerFromTicket(ticket)), 200, origin);
5679
- }
5680
5181
  joinResponse(roomId, code, player) {
5681
5182
  const join5 = joinTicket(player, roomId, this.secret);
5682
5183
  return {
@@ -5686,15 +5187,6 @@ var DevService = class {
5686
5187
  url: `ws://localhost:${this.port}/rooms/${roomId}?j=${encodeURIComponent(join5)}`
5687
5188
  };
5688
5189
  }
5689
- watchResponse(roomId, code, player) {
5690
- const watch = joinTicket(player, roomId, this.secret, "watch");
5691
- return {
5692
- roomId,
5693
- code,
5694
- watch,
5695
- url: `ws://localhost:${this.port}/rooms/${roomId}?w=${encodeURIComponent(watch)}`
5696
- };
5697
- }
5698
5190
  uniqueCode() {
5699
5191
  for (let attempt = 0; attempt < 20; attempt += 1) {
5700
5192
  const code = randomUniform(ALFABETO_CODICE, 6);
@@ -5717,8 +5209,6 @@ var DevService = class {
5717
5209
  if (code === "room_full") return "Room is full.";
5718
5210
  if (code === "room_playing") return "The game has already started.";
5719
5211
  if (code === "room_ended") return "Room has ended.";
5720
- if (code === "spectators_disabled") return "Spectators are not allowed in this game.";
5721
- if (code === "spectators_full") return "The room has no spectator seats left.";
5722
5212
  return "Room not found.";
5723
5213
  }
5724
5214
  rejectUpgrade(socket, status, code, message) {
@@ -5749,7 +5239,7 @@ async function runDev(options) {
5749
5239
  readGame(root),
5750
5240
  loadDefinition(root)
5751
5241
  ]);
5752
- if (richiedeServer(manifest) && definition === null) throw new Error("server.js is required by a room mode.");
5242
+ if (richiedeServer(manifest) && definition === null) throw new Error("server.js is required for modes with two or more players.");
5753
5243
  const server = createServer();
5754
5244
  let service;
5755
5245
  await new Promise((resolveListen, rejectListen) => {
@@ -5791,6 +5281,8 @@ async function runDev(options) {
5791
5281
  server.on("upgrade", (request, socket, head) => {
5792
5282
  void service.handleUpgrade(request, socket, head);
5793
5283
  });
5284
+ process.stdout.write(`${NETWORK_GUIDANCE}
5285
+ `);
5794
5286
  process.stdout.write(`Game: ${service.gameOrigin}/
5795
5287
  `);
5796
5288
  process.stdout.write(`Portal: ${service.portalOrigin}/
@@ -5818,21 +5310,17 @@ function templateManifest(id, name, multiplayer) {
5818
5310
  manifest: 1,
5819
5311
  id,
5820
5312
  name,
5821
- description: { en: "Activate eight targets to complete a round." },
5313
+ description: { en: "Find your rhythm. Hit eight targets. Complete the round." },
5822
5314
  cover: "cover.png",
5823
5315
  card: "card.png",
5824
5316
  icon: "icon.png",
5825
5317
  languages: ["en"],
5826
5318
  platform: "both",
5827
- overlay: { version: 1, accent: "#ffffff" },
5828
- ...multiplayer ? { players: { min: 2, max: 4 }, lobby: true, persistent: true, spectators: { delayMs: 3e3 } } : {},
5319
+ ...multiplayer ? { players: { min: 2, max: 4 }, lobby: true, persistent: true } : {},
5829
5320
  modes: [
5830
- { id: "practice", execution: "local", label: { en: "Practice" }, instructions: { en: "Activate eight targets with a click, tap or Space." }, players: { min: 1, max: 1 }, lobby: false },
5321
+ { id: "practice", players: { min: 1, max: 1 }, lobby: false },
5831
5322
  ...multiplayer ? [{
5832
5323
  id: "together",
5833
- execution: "room",
5834
- label: { en: "Together" },
5835
- instructions: { en: "Activate eight targets together to complete a round." },
5836
5324
  matchmaking: { key: ["pool"], defaults: { pool: "v1" }, timeoutMs: 12e3 }
5837
5325
  }] : []
5838
5326
  ]
@@ -5845,7 +5333,8 @@ var templateTexts = {
5845
5333
  result: "8 / 8",
5846
5334
  progress: "{n} / 8"
5847
5335
  };
5848
- var templateIndex = `<!doctype html>
5336
+ function templateIndex(multiplayer) {
5337
+ return `<!doctype html>
5849
5338
  <html lang="en">
5850
5339
  <head>
5851
5340
  <meta charset="utf-8">
@@ -5854,7 +5343,7 @@ var templateIndex = `<!doctype html>
5854
5343
  <style>
5855
5344
  html,body{margin:0;width:100%;height:100%;overflow:hidden;background:#000000;color:#ffffff;font:16px system-ui}
5856
5345
  canvas{display:block;width:100vw;height:100dvh;touch-action:none;outline:none}
5857
- #status{position:absolute;left:max(16px,var(--caisual-safe-left, 0px));top:max(14px,var(--caisual-safe-top, 0px));margin:0;pointer-events:none;max-width:calc(100% - 210px)}
5346
+ #status{position:absolute;left:max(16px,env(safe-area-inset-left));top:max(14px,env(safe-area-inset-top));margin:0;pointer-events:none;max-width:calc(100% - 32px)}
5858
5347
  </style>
5859
5348
  </head>
5860
5349
  <body>
@@ -5862,18 +5351,18 @@ var templateIndex = `<!doctype html>
5862
5351
  <p id="status" role="status" aria-live="polite"></p>
5863
5352
  <script type="module">
5864
5353
  import { caisual } from '/__caisual/kit/v1.js';
5354
+ import { createMenu } from './menu.js';
5865
5355
  const c = await caisual.connect();
5866
5356
  const t = await c.text();
5867
5357
  document.documentElement.lang = c.player.language;
5868
5358
  document.title = t('title');
5869
5359
  // La sonda locale legge il client del gioco senza aprire un'altra sessione.
5870
- if (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c };
5360
+ if (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c, get room() { return room; }, get playing() { return playing; } };
5871
5361
  const canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), status = document.querySelector('#status');
5872
5362
  canvas.setAttribute('aria-label', t('controls'));
5873
- let session = { kind: 'idle' }, state = { hits: 0 }, blocked = false, stops = [], localId = null, offline = false, reserved = [];
5363
+ let state = { hits: 0 }, room = null, stops = [], playing = false;
5874
5364
  let width = 1, height = 1, target = { x: 0, y: 0, radius: 24 };
5875
5365
  const position = (hits) => ({ x: .25 + ((hits * 7) % 11) / 20, y: .28 + ((hits * 3) % 7) / 14 });
5876
- const playing = () => offline ? state.hits < 8 : session.kind === 'local' ? session.status === 'playing' : session.kind === 'room' && session.room.status === 'playing';
5877
5366
  function draw() {
5878
5367
  const point = position(state.hits), radius = Math.max(28, Math.min(width, height) * .09);
5879
5368
  target = { x: point.x * width, y: point.y * height, radius };
@@ -5889,74 +5378,243 @@ var templateIndex = `<!doctype html>
5889
5378
  ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center'; ctx.font = 'bold ' + Math.min(54, width / 10) + 'px system-ui'; ctx.fillText(t('complete'), width / 2, height / 2);
5890
5379
  }
5891
5380
  status.textContent = state.hits >= 8 ? t('result') : t('progress', { n: state.hits });
5892
- canvas.dataset.state = JSON.stringify({ hits: state.hits, target, playing: playing() });
5893
- }
5894
- function resize() { width = innerWidth; height = innerHeight; const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0); draw(); placeHud(); }
5895
- function placeHud() {
5896
- // La pillola puo' crescere con un invito: il campo resta intero e l'HUD le lascia spazio.
5897
- const left = parseFloat(getComputedStyle(status).left) || 16;
5898
- const rectangles = reserved.filter((rect) => rect.y < 72 && rect.x + rect.width > left);
5899
- const right = Math.min(width - 16, ...rectangles.map((rect) => rect.x));
5900
- status.style.top = right - left < 100 ? Math.max(14, ...rectangles.map((rect) => rect.y + rect.height + 8)) + 'px' : '';
5901
- status.style.maxWidth = Math.max(60, (right - left < 100 ? width - 16 : right - 12) - left) + 'px';
5902
- }
5903
- c.overlay.onChange((view) => { blocked = view.inputBlocked; reserved = view.reservedRects; placeHud(); });
5904
- c.session.onChange((next) => {
5905
- stops.forEach((stop) => stop()); stops = []; session = next;
5906
- if (next.kind === 'local') { if (next.id !== localId) state = { hits: 0 }; localId = next.id; }
5907
- else if (next.kind === 'room' || next.kind === 'watch') {
5908
- const room = next.room; state = room.state ?? { hits: 0 };
5909
- stops.push(room.onState((value) => { state = value; draw(); }), room.onStatus(draw));
5910
- } else state = { hits: 0 };
5911
- draw();
5381
+ canvas.dataset.state = JSON.stringify({ hits: state.hits, target, playing });
5382
+ }
5383
+ function resize() { width = innerWidth; height = innerHeight; const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0); draw(); }
5384
+ // Il menu e la lobby li disegna il gioco: la piattaforma da' solo le funzioni.
5385
+ const menu = createMenu({
5386
+ c, t, online: ${multiplayer}, mode: ${multiplayer ? "'together'" : "null"},
5387
+ resultText: () => t('result'),
5388
+ onSolo() { room = null; state = { hits: 0 }; playing = true; draw(); canvas.focus(); },
5389
+ onRoom(next) {
5390
+ stops.forEach((stop) => stop()); room = next; state = next.state ?? { hits: 0 };
5391
+ stops = [
5392
+ next.onState((value) => { state = value; draw(); }),
5393
+ next.onStatus((roomStatus) => { playing = roomStatus === 'playing'; draw(); }),
5394
+ ];
5395
+ playing = next.status === 'playing'; draw();
5396
+ },
5397
+ onExit() { room = null; playing = false; state = { hits: 0 }; draw(); },
5912
5398
  });
5913
5399
  function hit() {
5914
- if (blocked || !playing() || state.hits >= 8) return;
5400
+ if (!playing || state.hits >= 8) return;
5915
5401
  // Il server decide il progresso condiviso; il client propone solo la luce corrente.
5916
- if (session.kind === 'room') session.room.send({ hit: state.hits });
5917
- else { state = { hits: state.hits + 1 }; if (state.hits === 8 && !offline) c.session.finish(); draw(); }
5402
+ if (room) { room.send({ hit: state.hits }); return; }
5403
+ state = { hits: state.hits + 1 };
5404
+ if (state.hits === 8) { playing = false; menu.result(t('result')); }
5405
+ draw();
5918
5406
  }
5919
5407
  canvas.addEventListener('pointerdown', (event) => { if (Math.hypot(event.clientX - target.x, event.clientY - target.y) <= target.radius) hit(); });
5920
- addEventListener('keydown', (event) => { if (event.code === 'Space' && !event.repeat && !blocked) { event.preventDefault(); hit(); } });
5921
- addEventListener('resize', resize); resize(); c.session.ready();
5922
- // Senza ospite resta una prova locale utilizzabile anche aprendo il file da un server statico.
5923
- if (!c.session.capabilities.overlay) { offline = true; draw(); }
5408
+ addEventListener('keydown', (event) => { if (event.code === 'Space' && !event.repeat && playing) { event.preventDefault(); hit(); } });
5409
+ addEventListener('resize', resize); resize();
5924
5410
  </script>
5925
5411
  </body>
5926
5412
  </html>
5927
5413
  `;
5928
- var templateServer = `import { defineGame } from '@caisual/kit/server';
5414
+ }
5415
+ var templateServer = `// Le scie grafiche restano sul client per rispettare ${NETWORK_BUDGET.recipientBytesPerSecond / 1e3} kB/s per destinatario e ${NETWORK_BUDGET.roomBytesPerSecond / 1e6} MB/s per stanza.
5416
+ // A 20 aggiornamenti/s bastano ${NETWORK_BUDGET.recipientBytesPerSecond / 2e4} kB per aggiornamento per esaurire il budget.
5417
+ import { defineGame } from '@caisual/kit/server';
5929
5418
 
5930
5419
  export default defineGame({
5931
5420
  tickRate: 0,
5932
5421
  onCreate(room) { room.state = { hits: 0 }; },
5933
5422
  onRestart(room) { room.state = { hits: 0 }; },
5934
5423
  onMessage(room, player, message) {
5935
- if (room.status !== 'playing' || player.role === 'spectator' || !message || message.hit !== room.state.hits) return;
5424
+ if (room.status !== 'playing' || !message || message.hit !== room.state.hits) return;
5936
5425
  // La revisione rende innocui due tocchi contemporanei sulla stessa luce.
5937
5426
  room.state.hits++;
5938
- if (room.state.hits === 8) room.end({ standings: room.players.filter((p) => p.role !== 'spectator').map((p) => ({ playerId: p.id, score: 8, rank: 1 })), winners: room.players.filter((p) => p.role !== 'spectator').map((p) => p.id), unit: 'points', lights: 8 }, { rematch: true });
5427
+ if (room.state.hits === 8) room.end({ standings: room.players.map((p) => ({ playerId: p.id, score: 8, rank: 1 })), winners: room.players.map((p) => p.id), unit: 'points', lights: 8 }, { rematch: true });
5939
5428
  },
5940
5429
  });
5941
5430
  `;
5942
5431
 
5943
5432
  // src/arcade/index.html.txt
5944
- var index_html_default = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Beacon arena</title>\n<style>\nhtml,body{margin:0;width:100%;height:100%;overflow:hidden;background:#000000;color:#ffffff;font:15px system-ui}canvas{display:block;width:100%;height:100dvh;touch-action:none;outline:none}\n#hud{position:absolute;width:180px;box-sizing:border-box;padding:10px 12px;border:1px solid #808080;background:#000000}#hud strong,#hud span{display:block}#hud span{font-size:12px;margin:4px 0;color:#ffffff}button{font:inherit;border:0;background:#ffffff;color:#000000;padding:7px 16px;touch-action:none}button:disabled{opacity:.5}\n</style></head><body><canvas tabindex="0"></canvas><div id="hud"><strong id="score"></strong><span id="hint"></span><button id="pulse"></button></div><script type="module" src="./game.js"></script></body></html>\n';
5433
+ var index_html_default = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Beacon arena</title>\n<style>\n:root{--safe-top:env(safe-area-inset-top,0px);--safe-right:env(safe-area-inset-right,0px);--safe-bottom:env(safe-area-inset-bottom,0px);--safe-left:env(safe-area-inset-left,0px)}\nhtml,body{margin:0;width:100%;height:100%;overflow:hidden;background:#000000;color:#ffffff;font:15px system-ui}canvas{display:block;width:100%;height:100dvh;touch-action:none;outline:none}\n#hud{position:absolute;top:calc(var(--safe-top) + 12px);left:calc(var(--safe-left) + 12px);width:180px;max-width:calc(100% - var(--safe-left) - var(--safe-right) - 24px);box-sizing:border-box;padding:10px 12px;border:1px solid #808080;background:#000000}#hud[hidden]{display:none}#hud strong,#hud span{display:block}#hud span{font-size:12px;margin:4px 0;color:#ffffff}button{font:inherit;border:0;background:#ffffff;color:#000000;padding:7px 16px;touch-action:none}button:disabled{opacity:.5}\n</style></head><body><canvas tabindex="0"></canvas><div id="hud" hidden><strong id="score"></strong><span id="hint"></span><button id="pulse"></button></div><script type="module" src="./game.js"></script></body></html>\n';
5945
5434
 
5946
5435
  // src/arcade/game.js.txt
5947
- var game_js_default = "import { caisual } from '/__caisual/kit/v1.js';\nimport { RULES, entity, stepEntity, reconcile, beacon, interpolate, hudRect } from './physics.js';\nconst c = await caisual.connect(), t = await c.text();\ndocument.documentElement.lang = c.player.language; document.title = t('title');\nconst canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), hud = document.querySelector('#hud');\nconst score = document.querySelector('#score'), hint = document.querySelector('#hint'), button = document.querySelector('#pulse');\ncanvas.setAttribute('aria-label', t('controls')); button.textContent = t('pulse'); hint.textContent = t('hint');\nlet view = { inputBlocked: true, reservedRects: [], safeArea: {} }, session = { kind: 'idle' }, room = null, state = null;\nlet stops = [], pending = [], samples = [], predicted = null, seq = 0, actionSeq = 0, action = null, round = null;\nlet accumulator = 0, lastFrame = performance.now(), lastSend = 0, lastPulse = -Infinity, visual = null, offset = { x: 0, y: 0 };\nlet rendered = [];\nlet keys = new Set(), pointer = null, layout = { x: 0, y: 0, scale: 1 }, width = innerWidth, height = innerHeight;\nconst active = () => session.kind === 'room' && room?.status === 'playing' && room.connection === 'connected' && !view.inputBlocked;\nfunction clearControls() { keys.clear(); pointer = null; }\nfunction read(next, tick, at = room.serverTime()) {\n if (!next?.entities) return;\n const newRound = next.round !== round;\n state = next;\n if (newRound) { round = next.round; pending = []; samples = []; predicted = visual = null; offset = { x: 0, y: 0 }; seq = actionSeq = 0; action = null; accumulator = 0; clearControls(); }\n const mine = state.entities[room.you];\n if (mine) {\n seq = Math.max(seq, mine.ack); actionSeq = Math.max(actionSeq, mine.actionAck);\n if (action && mine.actionAck >= action.seq) action = null;\n const before = predicted;\n ({ predicted, pending } = reconcile(mine, pending));\n // La correzione cambia subito la simulazione; solo il disegno assorbe lo scarto in pochi fotogrammi.\n if (before && !newRound) { offset.x += before.x - predicted.x; offset.y += before.y - predicted.y; }\n }\n samples.push({ at, entities: structuredClone(next.entities) });\n samples = samples.filter(sample => at - sample.at < 2500).slice(-120);\n}\nfunction attach(next) {\n if (next.room && next.room === room) { session = next; return; }\n stops.forEach(stop => stop()); stops = []; session = next; room = next.room ?? null;\n state = null; round = null; pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n if (room) {\n read(room.state);\n stops.push(room.onState(read), room.onConnection(connection => {\n pending = []; action = null; accumulator = 0; offset = { x: 0, y: 0 }; clearControls();\n const mine = room.state?.entities?.[room.you];\n if (mine) { predicted = { ...mine }; seq = mine.ack; }\n // Un valore neutro sostituisce anche l'ultimo input conservato dal kit durante la riconnessione.\n if (session.kind === 'room') room.input({ type: 'move', round, commands: [] });\n }), room.onStatus(() => { clearControls(); }));\n }\n}\nfunction placeHud() {\n hud.style.width = Math.max(80, Math.min(180, width - (view.safeArea.left || 0) - (view.safeArea.right || 0) - 24)) + 'px';\n const rect = hudRect(width, height, view.safeArea, view.reservedRects, hud.offsetWidth, hud.offsetHeight);\n hud.style.visibility = rect && !view.inputBlocked ? 'visible' : 'hidden';\n if (rect) { hud.style.left = rect.x + 'px'; hud.style.top = rect.y + 'px'; }\n}\nfunction resize() {\n width = innerWidth; height = innerHeight;\n const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n const safe = view.safeArea;\n const availableWidth = width - (safe.left || 0) - (safe.right || 0), availableHeight = height - (safe.top || 0) - (safe.bottom || 0);\n const scale = Math.max(.05, Math.min((availableWidth - 24) / RULES.width, (availableHeight - 24) / RULES.height));\n layout = { scale, x: (safe.left || 0) + (availableWidth - RULES.width * scale) / 2, y: (safe.top || 0) + (availableHeight - RULES.height * scale) / 2 };\n placeHud();\n}\nfunction control() {\n if (!active()) return { x: 0, y: 0 };\n if (pointer && predicted) {\n const dx = pointer.x - predicted.x, dy = pointer.y - predicted.y, length = Math.hypot(dx, dy);\n return length < 8 ? { x: 0, y: 0 } : { x: dx / Math.max(36, length), y: dy / Math.max(36, length) };\n }\n return { x: Number(keys.has('ArrowRight') || keys.has('KeyD')) - Number(keys.has('ArrowLeft') || keys.has('KeyA')),\n y: Number(keys.has('ArrowDown') || keys.has('KeyS')) - Number(keys.has('ArrowUp') || keys.has('KeyW')) };\n}\nfunction pulse() {\n const now = performance.now();\n if (!active() || now - lastPulse < 650 || action) return;\n action = { type: 'pulse', round, seq: ++actionSeq }; lastPulse = now;\n try { room.send(action); } catch { action = null; }\n}\nbutton.addEventListener('pointerdown', event => { event.preventDefault(); pulse(); });\nbutton.addEventListener('click', pulse);\ncanvas.addEventListener('pointerdown', event => { if (!active()) return; canvas.focus(); canvas.setPointerCapture(event.pointerId); pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointermove', event => { if (pointer) pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointerup', () => { pointer = null; }); canvas.addEventListener('pointercancel', clearControls);\naddEventListener('keydown', event => { if (!active() || event.target.closest?.('input,select,textarea')) return; if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','KeyW','KeyA','KeyS','KeyD','Space'].includes(event.code)) { event.preventDefault(); keys.add(event.code); if (event.code === 'Space' && !event.repeat) pulse(); } });\naddEventListener('keyup', event => keys.delete(event.code)); addEventListener('blur', clearControls); document.addEventListener('visibilitychange', clearControls);\nc.overlay.onChange(next => { view = next; if (view.inputBlocked) clearControls(); resize(); });\nc.session.onChange(attach); addEventListener('resize', resize); resize(); c.session.ready();\nfunction frame(now) {\n const dt = Math.min(.1, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now;\n if (session.kind === 'room' && room?.status === 'playing' && room.connection === 'connected' && predicted) {\n accumulator += dt;\n while (accumulator + 1e-9 >= RULES.step) {\n accumulator -= RULES.step;\n // Il limite interrompe la previsione dopo un lungo silenzio invece di accumulare secondi di comandi arretrati.\n if (pending.length >= RULES.history) continue;\n const command = { seq: ++seq, ...control() }; pending.push(command); stepEntity(predicted, command);\n }\n const period = 1000 / Math.min(12, room.tickRate || 12);\n if (now - lastSend >= period) {\n lastSend = now;\n room.input({ type: 'move', round, commands: pending.slice(-RULES.history) });\n if (action && now - lastPulse >= 300) { try { room.send(action); lastPulse = now; } catch {} }\n }\n }\n const decay = Math.exp(-16 * dt); offset.x *= decay; offset.y *= decay;\n visual = predicted ? { ...predicted, x: predicted.x + offset.x, y: predicted.y + offset.y } : null;\n ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, width, height); ctx.save(); ctx.translate(layout.x, layout.y); ctx.scale(layout.scale, layout.scale);\n ctx.fillStyle = '#808080'; ctx.fillRect(0, 0, RULES.width, RULES.height);\n ctx.strokeStyle = '#ffffff0b'; ctx.lineWidth = 1;\n for (let x = 0; x < RULES.width; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, RULES.height); ctx.stroke(); }\n for (let y = 0; y < RULES.height; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(RULES.width, y); ctx.stroke(); }\n const target = beacon(state?.step ?? 0); ctx.fillStyle = '#ffffff1c'; ctx.beginPath(); ctx.arc(target.x, target.y, 90, 0, Math.PI * 2); ctx.fill();\n ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(target.x, target.y, 12 + Math.sin(now / 220) * 2, 0, Math.PI * 2); ctx.fill();\n const delay = room ? Math.max(100, (room.latency ?? 0) / 2 + 2000 / Math.max(1, room.tickRate)) : 100;\n // Il buffer usa il tempo dei campioni; agli spettatori sottraiamo anche il ritardo dichiarato dalla stanza.\n const at = room ? room.serverTime() - delay - (session.kind === 'watch' ? room.delayMs : 0) : 0;\n const bodies = state ? Object.values(state.entities) : [entity('demo', 0), entity('demo2', 1)];\n rendered = [];\n bodies.forEach((body, index) => {\n const own = session.kind === 'room' && body.id === room.you;\n const shown = own && visual ? visual : interpolate(samples, at, body.id) ?? body;\n rendered.push({ id: body.id, x: shown.x, y: shown.y });\n const color = ['#ff0000', '#0066ff', '#ffff00', '#00cc00'][index % 4];\n ctx.fillStyle = color; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius, 0, Math.PI * 2); ctx.fill();\n ctx.strokeStyle = own ? '#ffffff' : color; ctx.lineWidth = own ? 3 : 1; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius + 6 + (body.flash ? (18 - body.flash) * 3 : 0), 0, Math.PI * 2); ctx.stroke();\n ctx.fillStyle = '#ffffff'; ctx.font = '14px system-ui'; ctx.textAlign = 'center'; ctx.fillText(own ? t('you') : String(index + 1), shown.x, shown.y - 32);\n });\n ctx.restore();\n score.textContent = t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: Math.max(0, Math.ceil(RULES.seconds - (state?.step ?? 0) * RULES.step)) });\n hint.textContent = t(session.kind === 'watch' ? 'watching' : 'hint'); button.hidden = session.kind === 'watch'; button.disabled = !active() || !!action;\n placeHud(); requestAnimationFrame(frame);\n}\n// La sonda esiste solo in sviluppo per misurare previsione, geometria e stato senza creare una seconda connessione.\nif (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c, get motion() { return { predicted, visual, pending: pending.length, samples: samples.length, rendered, layout }; } };\nrequestAnimationFrame(frame);\n";
5436
+ var game_js_default = "import { caisual } from '/__caisual/kit/v1.js';\nimport { createMenu } from './menu.js';\nimport { RULES, entity, stepEntity, reconcile, beacon, interpolate } from './physics.js';\nconst c = await caisual.connect(), t = await c.text();\ndocument.documentElement.lang = c.player.language; document.title = t('title');\nconst canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), hud = document.querySelector('#hud');\nconst score = document.querySelector('#score'), hint = document.querySelector('#hint'), button = document.querySelector('#pulse');\ncanvas.setAttribute('aria-label', t('controls')); button.textContent = t('pulse'); hint.textContent = t('hint');\nlet room = null, state = null;\nlet stops = [], pending = [], samples = [], predicted = null, seq = 0, actionSeq = 0, action = null, round = null;\nlet accumulator = 0, lastFrame = performance.now(), lastSend = 0, lastPulse = -Infinity, visual = null, offset = { x: 0, y: 0 };\nlet rendered = [];\nlet keys = new Set(), pointer = null, layout = { x: 0, y: 0, scale: 1 }, width = innerWidth, height = innerHeight;\nconst active = () => room !== null && room.status === 'playing' && room.connection === 'connected';\nfunction clearControls() { keys.clear(); pointer = null; }\nfunction read(next, tick, at = room.serverTime()) {\n if (!next?.entities) return;\n const newRound = next.round !== round;\n state = next;\n if (newRound) { round = next.round; pending = []; samples = []; predicted = visual = null; offset = { x: 0, y: 0 }; seq = actionSeq = 0; action = null; accumulator = 0; clearControls(); }\n const mine = state.entities[room.you];\n if (mine) {\n seq = Math.max(seq, mine.ack); actionSeq = Math.max(actionSeq, mine.actionAck);\n if (action && mine.actionAck >= action.seq) action = null;\n const before = predicted;\n ({ predicted, pending } = reconcile(mine, pending));\n // La correzione cambia subito la simulazione; solo il disegno assorbe lo scarto in pochi fotogrammi.\n if (before && !newRound) { offset.x += before.x - predicted.x; offset.y += before.y - predicted.y; }\n }\n samples.push({ at, entities: structuredClone(next.entities) });\n samples = samples.filter(sample => at - sample.at < 2500).slice(-120);\n}\nfunction attach(next) {\n stops.forEach(stop => stop()); stops = []; room = next;\n state = null; round = null; pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n read(room.state);\n stops.push(room.onState(read), room.onConnection(() => {\n pending = []; action = null; accumulator = 0; offset = { x: 0, y: 0 }; clearControls();\n const mine = room.state?.entities?.[room.you];\n if (mine) { predicted = { ...mine }; seq = mine.ack; }\n // Un valore neutro sostituisce anche l'ultimo input conservato dal kit durante la riconnessione.\n if (room) room.input({ type: 'move', round, commands: [] });\n }), room.onStatus(() => { clearControls(); }));\n}\nfunction detach() {\n stops.forEach(stop => stop()); stops = []; room = null; state = null; round = null;\n pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n}\nfunction resize() {\n width = innerWidth; height = innerHeight;\n const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n // Il campo occupa tutta la finestra: il margine serve solo a non finire sotto la tacca.\n const style = getComputedStyle(document.documentElement);\n const inset = side => parseFloat(style.getPropertyValue('--safe-' + side)) || 0;\n const availableWidth = width - inset('left') - inset('right'), availableHeight = height - inset('top') - inset('bottom');\n const scale = Math.max(.05, Math.min((availableWidth - 24) / RULES.width, (availableHeight - 24) / RULES.height));\n layout = { scale, x: inset('left') + (availableWidth - RULES.width * scale) / 2, y: inset('top') + (availableHeight - RULES.height * scale) / 2 };\n}\nfunction control() {\n if (!active()) return { x: 0, y: 0 };\n if (pointer && predicted) {\n const dx = pointer.x - predicted.x, dy = pointer.y - predicted.y, length = Math.hypot(dx, dy);\n return length < 8 ? { x: 0, y: 0 } : { x: dx / Math.max(36, length), y: dy / Math.max(36, length) };\n }\n return { x: Number(keys.has('ArrowRight') || keys.has('KeyD')) - Number(keys.has('ArrowLeft') || keys.has('KeyA')),\n y: Number(keys.has('ArrowDown') || keys.has('KeyS')) - Number(keys.has('ArrowUp') || keys.has('KeyW')) };\n}\nfunction pulse() {\n const now = performance.now();\n if (!active() || now - lastPulse < 650 || action) return;\n action = { type: 'pulse', round, seq: ++actionSeq }; lastPulse = now;\n try { room.send(action); } catch { action = null; }\n}\nbutton.addEventListener('pointerdown', event => { event.preventDefault(); pulse(); });\nbutton.addEventListener('click', pulse);\ncanvas.addEventListener('pointerdown', event => { if (!active()) return; canvas.focus(); canvas.setPointerCapture(event.pointerId); pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointermove', event => { if (pointer) pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointerup', () => { pointer = null; }); canvas.addEventListener('pointercancel', clearControls);\naddEventListener('keydown', event => { if (!active() || event.target.closest?.('input,select,textarea')) return; if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','KeyW','KeyA','KeyS','KeyD','Space'].includes(event.code)) { event.preventDefault(); keys.add(event.code); if (event.code === 'Space' && !event.repeat) pulse(); } });\naddEventListener('keyup', event => keys.delete(event.code)); addEventListener('blur', clearControls); document.addEventListener('visibilitychange', clearControls);\naddEventListener('resize', resize); resize();\n// Menu, lobby e risultato li disegna il gioco: la piattaforma da' solo le funzioni.\ncreateMenu({\n c, t, online: true, solo: false, mode: 'arena',\n resultText: () => t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: 0 }),\n onRoom: attach,\n onExit: detach,\n});\nfunction frame(now) {\n const dt = Math.min(.1, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now;\n if (active() && predicted) {\n accumulator += dt;\n while (accumulator + 1e-9 >= RULES.step) {\n accumulator -= RULES.step;\n // Il limite interrompe la previsione dopo un lungo silenzio invece di accumulare secondi di comandi arretrati.\n if (pending.length >= RULES.history) continue;\n const command = { seq: ++seq, ...control() }; pending.push(command); stepEntity(predicted, command);\n }\n const period = 1000 / Math.min(12, room.tickRate || 12);\n if (now - lastSend >= period) {\n lastSend = now;\n room.input({ type: 'move', round, commands: pending.slice(-RULES.history) });\n if (action && now - lastPulse >= 300) { try { room.send(action); lastPulse = now; } catch {} }\n }\n }\n const decay = Math.exp(-16 * dt); offset.x *= decay; offset.y *= decay;\n visual = predicted ? { ...predicted, x: predicted.x + offset.x, y: predicted.y + offset.y } : null;\n ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, width, height); ctx.save(); ctx.translate(layout.x, layout.y); ctx.scale(layout.scale, layout.scale);\n ctx.fillStyle = '#808080'; ctx.fillRect(0, 0, RULES.width, RULES.height);\n ctx.strokeStyle = '#ffffff0b'; ctx.lineWidth = 1;\n for (let x = 0; x < RULES.width; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, RULES.height); ctx.stroke(); }\n for (let y = 0; y < RULES.height; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(RULES.width, y); ctx.stroke(); }\n const target = beacon(state?.step ?? 0); ctx.fillStyle = '#ffffff1c'; ctx.beginPath(); ctx.arc(target.x, target.y, 90, 0, Math.PI * 2); ctx.fill();\n ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(target.x, target.y, 12 + Math.sin(now / 220) * 2, 0, Math.PI * 2); ctx.fill();\n const delay = room ? Math.max(100, (room.latency ?? 0) / 2 + 2000 / Math.max(1, room.tickRate)) : 100;\n // Il buffer usa il tempo dei campioni, cosi' gli altri corpi non saltano fra due aggiornamenti.\n const at = room ? room.serverTime() - delay : 0;\n const bodies = state ? Object.values(state.entities) : [entity('demo', 0), entity('demo2', 1)];\n rendered = [];\n bodies.forEach((body, index) => {\n const own = room !== null && body.id === room.you;\n const shown = own && visual ? visual : interpolate(samples, at, body.id) ?? body;\n rendered.push({ id: body.id, x: shown.x, y: shown.y });\n const color = ['#ff0000', '#0066ff', '#ffff00', '#00cc00'][index % 4];\n ctx.fillStyle = color; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius, 0, Math.PI * 2); ctx.fill();\n ctx.strokeStyle = own ? '#ffffff' : color; ctx.lineWidth = own ? 3 : 1; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius + 6 + (body.flash ? (18 - body.flash) * 3 : 0), 0, Math.PI * 2); ctx.stroke();\n ctx.fillStyle = '#ffffff'; ctx.font = '14px system-ui'; ctx.textAlign = 'center'; ctx.fillText(own ? t('you') : String(index + 1), shown.x, shown.y - 32);\n });\n ctx.restore();\n score.textContent = t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: Math.max(0, Math.ceil(RULES.seconds - (state?.step ?? 0) * RULES.step)) });\n hud.hidden = !active(); button.disabled = !active() || !!action;\n requestAnimationFrame(frame);\n}\n// La sonda esiste solo in sviluppo per misurare previsione, geometria e stato senza creare una seconda connessione.\nif (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c, get room() { return room; }, get playing() { return active(); }, get motion() { return { predicted, visual, pending: pending.length, samples: samples.length, rendered, layout }; } };\nrequestAnimationFrame(frame);\n";
5948
5437
 
5949
5438
  // src/arcade/physics.js.txt
5950
- var physics_js_default = "export const RULES = Object.freeze({ step: 1 / 60, width: 800, height: 600, radius: 18, speed: 220, seconds: 45, history: 60 });\nexport const clamp = (n, min, max) => Math.max(min, Math.min(max, n));\nexport function entity(id, index) {\n return { id, x: 220 + index % 2 * 360, y: 200 + Math.floor(index / 2) * 200, vx: 0, vy: 0, ack: 0, actionAck: 0, score: 0, cooldown: 0, flash: 0, queue: [] };\n}\nexport function stepEntity(body, control = { x: 0, y: 0 }) {\n const length = Math.max(1, Math.hypot(control.x, control.y));\n const blend = 1 - Math.exp(-18 * RULES.step);\n body.vx += (control.x / length * RULES.speed - body.vx) * blend;\n body.vy += (control.y / length * RULES.speed - body.vy) * blend;\n body.x = clamp(body.x + body.vx * RULES.step, RULES.radius, RULES.width - RULES.radius);\n body.y = clamp(body.y + body.vy * RULES.step, RULES.radius, RULES.height - RULES.radius);\n}\nexport function reconcile(authoritative, pending) {\n // Le conferme eliminano anche i comandi ritrasmessi, cosi' un movimento non viene applicato due volte.\n const remaining = pending.filter(command => command.seq > authoritative.ack).slice(-RULES.history);\n const predicted = { ...authoritative, queue: [] };\n for (const command of remaining) stepEntity(predicted, command);\n return { predicted, pending: remaining };\n}\nexport function beacon(step) {\n const places = [[400, 300], [170, 150], [630, 450], [630, 150], [170, 450]];\n const [x, y] = places[Math.floor(step * RULES.step / 5) % places.length];\n return { x, y };\n}\nexport function acceptControls(body, commands) {\n if (!Array.isArray(commands) || commands.length > RULES.history) return;\n const queued = new Map(body.queue.map(command => [command.seq, command]));\n for (const command of commands) {\n if (!command || !Number.isSafeInteger(command.seq) || command.seq <= body.ack || command.seq > body.ack + 600 ||\n !Number.isFinite(command.x) || !Number.isFinite(command.y) || Math.abs(command.x) > 1 || Math.abs(command.y) > 1) continue;\n if (!queued.has(command.seq)) queued.set(command.seq, { seq: command.seq, x: command.x, y: command.y });\n }\n // Il limite contiene memoria e ritardo; il server consuma al massimo un comando per passo, mai tempo inviato dal browser.\n body.queue = [...queued.values()].sort((a, b) => a.seq - b.seq).slice(-RULES.history);\n}\nexport function advance(state, deltaSeconds) {\n // Accumulare il tempo mantiene la stessa velocita' anche quando cambia la frequenza effettiva della stanza.\n state.accumulator += clamp(deltaSeconds, 0, .25);\n while (state.accumulator + 1e-9 >= RULES.step && state.step < RULES.seconds / RULES.step) {\n state.accumulator -= RULES.step; state.step++;\n for (const body of Object.values(state.entities)) {\n const command = body.queue.shift();\n stepEntity(body, command);\n if (command) body.ack = command.seq;\n body.cooldown = Math.max(0, body.cooldown - 1);\n body.flash = Math.max(0, body.flash - 1);\n }\n }\n}\nexport function pulse(state, body, seq) {\n if (!Number.isSafeInteger(seq) || seq <= body.actionAck || seq > body.actionAck + 600) return;\n body.actionAck = seq;\n // Una conferma vale anche per un tentativo rifiutato, per evitare ritrasmissioni infinite durante il recupero.\n if (body.cooldown > 0) return;\n body.cooldown = 36; body.flash = 18;\n const target = beacon(state.step);\n if (Math.hypot(body.x - target.x, body.y - target.y) <= 90) body.score++;\n}\nexport function standings(entities) {\n const order = Object.values(entities).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return order.map((body, i) => ({ playerId: body.id, score: body.score, rank: order.findIndex(other => other.score === body.score) + 1 }));\n}\nexport function interpolate(samples, at, id) {\n if (!samples.length) return null;\n let before = samples[0], after = samples.at(-1);\n for (const sample of samples) { if (sample.at <= at) before = sample; if (sample.at >= at) { after = sample; break; } }\n const a = before.entities[id], b = after.entities[id];\n if (!a || !b) return b ?? a ?? null;\n const alpha = clamp((at - before.at) / Math.max(1, after.at - before.at), 0, 1);\n return { ...b, x: a.x + (b.x - a.x) * alpha, y: a.y + (b.y - a.y) * alpha };\n}\nexport function hudRect(width, height, safe, reserved, hudWidth, hudHeight) {\n const margin = 12, left = (safe.left || 0) + margin, top = (safe.top || 0) + margin;\n const right = width - (safe.right || 0) - margin, bottom = height - (safe.bottom || 0) - margin;\n const w = Math.min(hudWidth, right - left);\n for (let y = top; y + hudHeight <= bottom; y += 8) {\n const rect = { x: left, y, width: w, height: hudHeight };\n if (reserved.every(r => rect.x + w + 8 <= r.x || rect.x >= r.x + r.width + 8 || y + hudHeight + 8 <= r.y || y >= r.y + r.height + 8)) return rect;\n }\n return null;\n}\n";
5439
+ var physics_js_default = "export const RULES = Object.freeze({ step: 1 / 60, width: 800, height: 600, radius: 18, speed: 220, seconds: 45, history: 60 });\nexport const clamp = (n, min, max) => Math.max(min, Math.min(max, n));\nexport function entity(id, index) {\n return { id, x: 220 + index % 2 * 360, y: 200 + Math.floor(index / 2) * 200, vx: 0, vy: 0, ack: 0, actionAck: 0, score: 0, cooldown: 0, flash: 0, queue: [] };\n}\nexport function stepEntity(body, control = { x: 0, y: 0 }) {\n const length = Math.max(1, Math.hypot(control.x, control.y));\n const blend = 1 - Math.exp(-18 * RULES.step);\n body.vx += (control.x / length * RULES.speed - body.vx) * blend;\n body.vy += (control.y / length * RULES.speed - body.vy) * blend;\n body.x = clamp(body.x + body.vx * RULES.step, RULES.radius, RULES.width - RULES.radius);\n body.y = clamp(body.y + body.vy * RULES.step, RULES.radius, RULES.height - RULES.radius);\n}\nexport function reconcile(authoritative, pending) {\n // Le conferme eliminano anche i comandi ritrasmessi, cosi' un movimento non viene applicato due volte.\n const remaining = pending.filter(command => command.seq > authoritative.ack).slice(-RULES.history);\n const predicted = { ...authoritative, queue: [] };\n for (const command of remaining) stepEntity(predicted, command);\n return { predicted, pending: remaining };\n}\nexport function beacon(step) {\n const places = [[400, 300], [170, 150], [630, 450], [630, 150], [170, 450]];\n const [x, y] = places[Math.floor(step * RULES.step / 5) % places.length];\n return { x, y };\n}\nexport function acceptControls(body, commands) {\n if (!Array.isArray(commands) || commands.length > RULES.history) return;\n const queued = new Map(body.queue.map(command => [command.seq, command]));\n for (const command of commands) {\n if (!command || !Number.isSafeInteger(command.seq) || command.seq <= body.ack || command.seq > body.ack + 600 ||\n !Number.isFinite(command.x) || !Number.isFinite(command.y) || Math.abs(command.x) > 1 || Math.abs(command.y) > 1) continue;\n if (!queued.has(command.seq)) queued.set(command.seq, { seq: command.seq, x: command.x, y: command.y });\n }\n // Il limite contiene memoria e ritardo; il server consuma al massimo un comando per passo, mai tempo inviato dal browser.\n body.queue = [...queued.values()].sort((a, b) => a.seq - b.seq).slice(-RULES.history);\n}\nexport function advance(state, deltaSeconds) {\n // Accumulare il tempo mantiene la stessa velocita' anche quando cambia la frequenza effettiva della stanza.\n state.accumulator += clamp(deltaSeconds, 0, .25);\n while (state.accumulator + 1e-9 >= RULES.step && state.step < RULES.seconds / RULES.step) {\n state.accumulator -= RULES.step; state.step++;\n for (const body of Object.values(state.entities)) {\n const command = body.queue.shift();\n stepEntity(body, command);\n if (command) body.ack = command.seq;\n body.cooldown = Math.max(0, body.cooldown - 1);\n body.flash = Math.max(0, body.flash - 1);\n }\n }\n}\nexport function pulse(state, body, seq) {\n if (!Number.isSafeInteger(seq) || seq <= body.actionAck || seq > body.actionAck + 600) return;\n body.actionAck = seq;\n // Una conferma vale anche per un tentativo rifiutato, per evitare ritrasmissioni infinite durante il recupero.\n if (body.cooldown > 0) return;\n body.cooldown = 36; body.flash = 18;\n const target = beacon(state.step);\n if (Math.hypot(body.x - target.x, body.y - target.y) <= 90) body.score++;\n}\nexport function standings(entities) {\n const order = Object.values(entities).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return order.map((body, i) => ({ playerId: body.id, score: body.score, rank: order.findIndex(other => other.score === body.score) + 1 }));\n}\nexport function interpolate(samples, at, id) {\n if (!samples.length) return null;\n let before = samples[0], after = samples.at(-1);\n for (const sample of samples) { if (sample.at <= at) before = sample; if (sample.at >= at) { after = sample; break; } }\n const a = before.entities[id], b = after.entities[id];\n if (!a || !b) return b ?? a ?? null;\n const alpha = clamp((at - before.at) / Math.max(1, after.at - before.at), 0, 1);\n return { ...b, x: a.x + (b.x - a.x) * alpha, y: a.y + (b.y - a.y) * alpha };\n}\n";
5951
5440
 
5952
5441
  // src/arcade/server.js.txt
5953
- var server_js_default = "import { defineGame } from '@caisual/kit/server';\nimport { RULES, entity, acceptControls, advance, pulse, standings } from './client/physics.js';\nfunction reset(room) {\n room.state = { round: (room.state?.round ?? 0) + 1, step: 0, accumulator: 0, entities: {} };\n}\nexport default defineGame({\n tickRate: 30,\n onCreate: reset,\n onRestart: reset,\n onStart(room) {\n room.state.entities = Object.fromEntries(room.players.filter(p => p.role !== 'spectator').map((p, i) => [p.id, entity(p.id, i)]));\n },\n onMessage(room, player, message) {\n const body = room.state.entities[player.id];\n if (room.status !== 'playing' || !player.connected || !body || message?.round !== room.state.round) return;\n if (message.type === 'move') acceptControls(body, message.commands);\n if (message.type === 'pulse') pulse(room.state, body, message.seq);\n },\n onConnection(room, player, connected) {\n // Dopo una caduta scartiamo il movimento arretrato: il rientro riparte dallo stato autorevole.\n if (!connected && room.state.entities[player.id]) room.state.entities[player.id].queue = [];\n },\n onLeave(room, player) { if (room.state.entities[player.id]) room.state.entities[player.id].queue = []; },\n onTick(room, deltaSeconds) {\n if (room.status !== 'playing') return;\n advance(room.state, deltaSeconds);\n if (room.state.step >= RULES.seconds / RULES.step) {\n const rows = standings(room.state.entities), winners = rows.filter(row => row.rank === 1).map(row => row.playerId);\n room.end({ standings: rows, winners, draw: winners.length === rows.length && rows.length > 1, unit: 'points' }, { rematch: { keepSetup: true, autoStart: true } });\n }\n },\n});\n";
5442
+ var server_js_default = "import { defineGame } from '@caisual/kit/server';\nimport { RULES, entity, acceptControls, advance, pulse, standings } from './client/physics.js';\nfunction reset(room) {\n room.state = { round: (room.state?.round ?? 0) + 1, step: 0, accumulator: 0, entities: {} };\n}\nexport default defineGame({\n tickRate: 30,\n onCreate: reset,\n onRestart: reset,\n onStart(room) {\n room.state.entities = Object.fromEntries(room.players.map((p, i) => [p.id, entity(p.id, i)]));\n },\n onMessage(room, player, message) {\n const body = room.state.entities[player.id];\n if (room.status !== 'playing' || !player.connected || !body || message?.round !== room.state.round) return;\n if (message.type === 'move') acceptControls(body, message.commands);\n if (message.type === 'pulse') pulse(room.state, body, message.seq);\n },\n onConnection(room, player, connected) {\n // Dopo una caduta scartiamo il movimento arretrato: il rientro riparte dallo stato autorevole.\n if (!connected && room.state.entities[player.id]) room.state.entities[player.id].queue = [];\n },\n onLeave(room, player) { if (room.state.entities[player.id]) room.state.entities[player.id].queue = []; },\n onTick(room, deltaSeconds) {\n if (room.status !== 'playing') return;\n advance(room.state, deltaSeconds);\n if (room.state.step >= RULES.seconds / RULES.step) {\n const rows = standings(room.state.entities), winners = rows.filter(row => row.rank === 1).map(row => row.playerId);\n room.end({ standings: rows, winners, draw: winners.length === rows.length && rows.length > 1, unit: 'points' }, { rematch: { keepSetup: true } });\n }\n },\n});\n";
5954
5443
 
5955
5444
  // src/arcade/physics.test.mjs.txt
5956
- var physics_test_mjs_default = "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { RULES, entity, stepEntity, reconcile, advance, acceptControls, pulse, standings, interpolate, hudRect } from '../client/physics.js';\n\ntest('fixed steps keep movement identical at changing server frequencies', () => {\n const run = hz => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n acceptControls(body, Array.from({ length: 60 }, (_, i) => ({ seq: i + 1, x: 1, y: .5 })));\n for (let i = 0; i < hz; i++) advance(state, 1 / hz);\n return body;\n };\n for (const hz of [60, 30, 20, 10, 5]) assert.deepEqual(run(hz), run(60));\n});\n\ntest('reconciliation replays only commands after the applied acknowledgement', () => {\n const body = entity('a', 0), pending = Array.from({ length: 24 }, (_, i) => ({ seq: i + 1, x: i < 12 ? 1 : -1, y: .4 }));\n const expected = { ...body };\n pending.forEach(command => stepEntity(expected, command));\n pending.slice(0, 9).forEach(command => stepEntity(body, command)); body.ack = 9;\n const result = reconcile(body, pending);\n assert.equal(result.pending.length, 15); assert.equal(result.predicted.x, expected.x); assert.equal(result.predicted.y, expected.y);\n const again = reconcile(body, result.pending); assert.deepEqual(again, result);\n assert.equal(body.ack, 9);\n});\n\ntest('duplicate, missing, malformed and excessive commands cannot speed up the server', () => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n const commands = Array.from({ length: 60 }, (_, i) => ({ seq: i + 1, x: 1, y: 1 }));\n acceptControls(body, commands); acceptControls(body, commands);\n acceptControls(body, [{ seq: 61, x: Infinity, y: 0 }, { seq: 5000, x: 0, y: 1 }, { seq: 3, x: 999, y: 0 }]);\n assert.equal(body.queue.length, 60);\n advance(state, RULES.step); assert.equal(body.ack, 1);\n assert.ok(Math.hypot(body.vx, body.vy) <= RULES.speed);\n for (let i = 0; i < 59; i++) advance(state, RULES.step);\n assert.equal(body.ack, 60);\n acceptControls(body, commands); assert.equal(body.queue.length, 0);\n const previous = body.vx; advance(state, RULES.step); assert.ok(body.vx < previous);\n acceptControls(body, [{ seq: 64, x: -1, y: 0 }]); advance(state, RULES.step); assert.equal(body.ack, 64);\n});\n\ntest('pulse scores only near the beacon, at server speed, and duplicate actions are harmless', () => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n pulse(state, body, 1); assert.equal(body.score, 0);\n body.x = 400; body.y = 300; body.cooldown = 0;\n pulse(state, body, 2); pulse(state, body, 2); pulse(state, body, 3);\n assert.equal(body.score, 1); assert.equal(body.actionAck, 3);\n for (let i = 0; i < 36; i++) advance(state, RULES.step);\n pulse(state, body, 4); assert.equal(body.score, 2);\n assert.deepEqual(standings({ a: body, b: { ...body, id: 'b' } }).map(row => row.rank), [1, 1]);\n});\n\ntest('remote interpolation uses sample times and holds at the buffer edges', () => {\n const samples = [{ at: 1000, entities: { a: { x: 10, y: 20 } } }, { at: 1100, entities: { a: { x: 30, y: 40 } } }];\n assert.equal(interpolate(samples, 1050, 'a').x, 20);\n assert.equal(interpolate(samples, 2000, 'a').x, 30);\n assert.equal(interpolate(samples, 0, 'a').x, 10);\n});\n\ntest('HUD stays inside phone safe areas and outside overlay rectangles', () => {\n const reserved = [{ x: 190, y: 44, width: 188, height: 44 }, { x: 12, y: 700, width: 366, height: 100 }];\n const rect = hudRect(390, 844, { top: 44, bottom: 34, left: 0, right: 0 }, reserved, 180, 130);\n assert.ok(rect.y >= 44 && rect.y + rect.height <= 810);\n assert.ok(reserved.every(r => rect.x + rect.width <= r.x || rect.x >= r.x + r.width || rect.y + rect.height <= r.y || rect.y >= r.y + r.height));\n assert.equal(hudRect(100, 100, {}, [{ x: 0, y: 0, width: 100, height: 100 }], 80, 40), null);\n});\n";
5445
+ var physics_test_mjs_default = "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { RULES, entity, stepEntity, reconcile, advance, acceptControls, pulse, standings, interpolate } from '../client/physics.js';\n\ntest('fixed steps keep movement identical at changing server frequencies', () => {\n const run = hz => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n acceptControls(body, Array.from({ length: 60 }, (_, i) => ({ seq: i + 1, x: 1, y: .5 })));\n for (let i = 0; i < hz; i++) advance(state, 1 / hz);\n return body;\n };\n for (const hz of [60, 30, 20, 10, 5]) assert.deepEqual(run(hz), run(60));\n});\n\ntest('reconciliation replays only commands after the applied acknowledgement', () => {\n const body = entity('a', 0), pending = Array.from({ length: 24 }, (_, i) => ({ seq: i + 1, x: i < 12 ? 1 : -1, y: .4 }));\n const expected = { ...body };\n pending.forEach(command => stepEntity(expected, command));\n pending.slice(0, 9).forEach(command => stepEntity(body, command)); body.ack = 9;\n const result = reconcile(body, pending);\n assert.equal(result.pending.length, 15); assert.equal(result.predicted.x, expected.x); assert.equal(result.predicted.y, expected.y);\n const again = reconcile(body, result.pending); assert.deepEqual(again, result);\n assert.equal(body.ack, 9);\n});\n\ntest('duplicate, missing, malformed and excessive commands cannot speed up the server', () => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n const commands = Array.from({ length: 60 }, (_, i) => ({ seq: i + 1, x: 1, y: 1 }));\n acceptControls(body, commands); acceptControls(body, commands);\n acceptControls(body, [{ seq: 61, x: Infinity, y: 0 }, { seq: 5000, x: 0, y: 1 }, { seq: 3, x: 999, y: 0 }]);\n assert.equal(body.queue.length, 60);\n advance(state, RULES.step); assert.equal(body.ack, 1);\n assert.ok(Math.hypot(body.vx, body.vy) <= RULES.speed);\n for (let i = 0; i < 59; i++) advance(state, RULES.step);\n assert.equal(body.ack, 60);\n acceptControls(body, commands); assert.equal(body.queue.length, 0);\n const previous = body.vx; advance(state, RULES.step); assert.ok(body.vx < previous);\n acceptControls(body, [{ seq: 64, x: -1, y: 0 }]); advance(state, RULES.step); assert.equal(body.ack, 64);\n});\n\ntest('pulse scores only near the beacon, at server speed, and duplicate actions are harmless', () => {\n const body = entity('a', 0), state = { step: 0, accumulator: 0, entities: { a: body } };\n pulse(state, body, 1); assert.equal(body.score, 0);\n body.x = 400; body.y = 300; body.cooldown = 0;\n pulse(state, body, 2); pulse(state, body, 2); pulse(state, body, 3);\n assert.equal(body.score, 1); assert.equal(body.actionAck, 3);\n for (let i = 0; i < 36; i++) advance(state, RULES.step);\n pulse(state, body, 4); assert.equal(body.score, 2);\n assert.deepEqual(standings({ a: body, b: { ...body, id: 'b' } }).map(row => row.rank), [1, 1]);\n});\n\ntest('remote interpolation uses sample times and holds at the buffer edges', () => {\n const samples = [{ at: 1000, entities: { a: { x: 10, y: 20 } } }, { at: 1100, entities: { a: { x: 30, y: 40 } } }];\n assert.equal(interpolate(samples, 1050, 'a').x, 20);\n assert.equal(interpolate(samples, 2000, 'a').x, 30);\n assert.equal(interpolate(samples, 0, 'a').x, 10);\n});\n";
5957
5446
 
5958
5447
  // src/arcade/server.test.mjs.txt
5959
- var server_test_mjs_default = "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport game from '../server.js';\nimport { RULES } from '../client/physics.js';\nfunction fixture() {\n const endings = [], room = { status: 'playing', players: [{ id: 'a', connected: true }, { id: 'b', connected: true }],\n end(result, options) { endings.push({ result, options }); room.status = 'finished'; } };\n game.onCreate(room); game.onStart(room); return { room, endings };\n}\ntest('server ignores forged state and previous-round input, and clears controls on drop', () => {\n const { room } = fixture(), player = room.players[0];\n for (const message of [null, { type: 'score', score: 999 }, { type: 'move', round: 0, commands: [{ seq: 1, x: 1, y: 0 }] }]) game.onMessage(room, player, message);\n assert.equal(room.state.entities.a.score, 0); assert.equal(room.state.entities.a.queue.length, 0);\n game.onMessage(room, player, { type: 'move', round: 1, commands: [{ seq: 1, x: 1, y: 0 }] });\n assert.equal(room.state.entities.a.ack, 0);\n game.onTick(room, RULES.step); assert.equal(room.state.entities.a.ack, 1);\n game.onMessage(room, player, { type: 'move', round: 1, commands: [{ seq: 2, x: 1, y: 0 }] });\n game.onConnection(room, player, false); assert.equal(room.state.entities.a.queue.length, 0);\n});\ntest('one complete match returns standings, then resets scores and acknowledgements for a fast rematch', () => {\n const { room, endings } = fixture(); room.state.entities.a.score = 3;\n for (let i = 0; i < RULES.seconds * 30 + 10; i++) game.onTick(room, 1 / 30);\n assert.equal(endings.length, 1); assert.deepEqual(endings[0].result.winners, ['a']);\n assert.deepEqual(endings[0].options, { rematch: { keepSetup: true, autoStart: true } });\n game.onRestart(room); room.status = 'playing'; game.onStart(room);\n assert.equal(room.state.round, 2); assert.equal(room.state.entities.a.score, 0); assert.equal(room.state.entities.a.ack, 0);\n});\n";
5448
+ var server_test_mjs_default = "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport game from '../server.js';\nimport { RULES } from '../client/physics.js';\nfunction fixture() {\n const endings = [], room = { status: 'playing', players: [{ id: 'a', connected: true }, { id: 'b', connected: true }],\n end(result, options) { endings.push({ result, options }); room.status = 'finished'; } };\n game.onCreate(room); game.onStart(room); return { room, endings };\n}\ntest('server ignores forged state and previous-round input, and clears controls on drop', () => {\n const { room } = fixture(), player = room.players[0];\n for (const message of [null, { type: 'score', score: 999 }, { type: 'move', round: 0, commands: [{ seq: 1, x: 1, y: 0 }] }]) game.onMessage(room, player, message);\n assert.equal(room.state.entities.a.score, 0); assert.equal(room.state.entities.a.queue.length, 0);\n game.onMessage(room, player, { type: 'move', round: 1, commands: [{ seq: 1, x: 1, y: 0 }] });\n assert.equal(room.state.entities.a.ack, 0);\n game.onTick(room, RULES.step); assert.equal(room.state.entities.a.ack, 1);\n game.onMessage(room, player, { type: 'move', round: 1, commands: [{ seq: 2, x: 1, y: 0 }] });\n game.onConnection(room, player, false); assert.equal(room.state.entities.a.queue.length, 0);\n});\ntest('one complete match returns standings, then resets scores and acknowledgements for a fast rematch', () => {\n const { room, endings } = fixture(); room.state.entities.a.score = 3;\n for (let i = 0; i < RULES.seconds * 30 + 10; i++) game.onTick(room, 1 / 30);\n assert.equal(endings.length, 1); assert.deepEqual(endings[0].result.winners, ['a']);\n assert.deepEqual(endings[0].options, { rematch: { keepSetup: true } });\n game.onRestart(room); room.status = 'playing'; game.onStart(room);\n assert.equal(room.state.round, 2); assert.equal(room.state.entities.a.score, 0); assert.equal(room.state.entities.a.ack, 0);\n});\n";
5449
+
5450
+ // src/menu.js.txt
5451
+ var menu_js_default = `// Il menu del gioco. La piattaforma non disegna piu' nulla sopra al gioco:
5452
+ // solo/online, stanza, invito, pronto, rivincita stanno qui, con le funzioni
5453
+ // del kit. Nessuno ospita e nessuno preme "inizia": quando tutti i presenti
5454
+ // sono pronti la partita parte da sola. Una stanza creata aspetta sempre in lobby. Copia questo file e ricoloralo: lo
5455
+ // stile e' tuo, i pochi attributi data-action servono anche ai test del browser.
5456
+ const WORDS = {
5457
+ solo: 'Play solo', online: 'Play online', create: 'Create room', join: 'Join with code',
5458
+ code: 'Room code', enter: 'Enter', invite: 'Copy invite', copied: 'Link copied',
5459
+ players: 'Players', ready: 'Ready', notReady: 'Not ready',
5460
+ leave: 'Leave', again: 'Play again', back: 'Menu', working: 'One moment', you: 'you',
5461
+ over: 'Round over', closed: 'The room is closed',
5462
+ };
5463
+
5464
+ const STYLE = \`
5465
+ #menu{position:fixed;inset:0;display:grid;place-items:center;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));background:#000000e6;color:#ffffff;font:16px/1.4 system-ui;z-index:10}
5466
+ #menu[hidden]{display:none}
5467
+ #menu .panel{width:min(100%,420px);display:grid;gap:12px}
5468
+ #menu h1{margin:0;font-size:24px;font-weight:700}
5469
+ #menu button{font:inherit;min-height:44px;padding:10px 16px;border:1px solid #ffffff;background:#000000;color:#ffffff;cursor:pointer}
5470
+ #menu button:hover:not(:disabled){background:#ffffff;color:#000000}
5471
+ #menu button:disabled{opacity:.45;cursor:default}
5472
+ #menu input{font:inherit;min-height:44px;padding:10px;width:100%;box-sizing:border-box;border:1px solid #ffffff;background:#000000;color:#ffffff;text-transform:uppercase;letter-spacing:.12em}
5473
+ #menu ul{list-style:none;margin:0;padding:0;display:grid;gap:6px;max-height:40vh;overflow:auto}
5474
+ #menu li{display:flex;gap:8px;justify-content:space-between;border:1px solid #808080;padding:8px}
5475
+ #menu .code{font-size:28px;letter-spacing:.2em;font-variant-numeric:tabular-nums}
5476
+ #menu .row{display:flex;gap:8px;flex-wrap:wrap}
5477
+ #menu .row>*{flex:1}
5478
+ #menu p{margin:0}
5479
+ #menu .note{color:#c0c0c0;font-size:14px;min-height:20px}
5480
+ \`;
5481
+
5482
+ export function createMenu(input) {
5483
+ const { c, t } = input;
5484
+ const word = (key) => {
5485
+ const value = t(\`menu.\${key}\`);
5486
+ return value === \`menu.\${key}\` ? WORDS[key] : value;
5487
+ };
5488
+ const style = document.createElement('style');
5489
+ style.textContent = STYLE;
5490
+ const root = document.createElement('div');
5491
+ root.id = 'menu';
5492
+ document.head.append(style);
5493
+ document.body.append(root);
5494
+
5495
+ let view = 'home', room = null, stops = [], note = '', joining = false, result = '';
5496
+ const clear = () => { stops.forEach((stop) => stop()); stops = []; };
5497
+ const escape = (value) => String(value).replace(/[&<>"]/g, (character) => (
5498
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[character]
5499
+ ));
5500
+ const you = () => room?.players.find((player) => player.id === room.you);
5501
+ const button = (action, key, extra = '') => \`<button data-action="\${action}"\${extra}>\${escape(word(key))}</button>\`;
5502
+
5503
+ function render() {
5504
+ if (view === 'playing') { root.hidden = true; return; }
5505
+ root.hidden = false;
5506
+ if (view === 'home') {
5507
+ root.innerHTML = \`<div class="panel">
5508
+ <h1>\${escape(t('title'))}</h1>
5509
+ \${input.solo === false ? '' : button('solo', 'solo')}
5510
+ \${input.online ? \`\${button('create', 'create', joining ? ' disabled' : '')}
5511
+ <form data-form="join" class="row">
5512
+ <input data-control="code" name="code" maxlength="7" autocomplete="off" aria-label="\${escape(word('code'))}" placeholder="\${escape(word('code'))}">
5513
+ <button type="submit" data-action="join"\${joining ? ' disabled' : ''}>\${escape(word('enter'))}</button>
5514
+ </form>\` : ''}
5515
+ <p class="note" role="status">\${escape(note)}</p>
5516
+ </div>\`;
5517
+ return;
5518
+ }
5519
+ if (view === 'result') {
5520
+ root.innerHTML = \`<div class="panel">
5521
+ <h1>\${escape(result)}</h1>
5522
+ <div class="row">\${room ? button('again', 'again') : ''}\${button('back', 'back')}</div>
5523
+ <p class="note" role="status">\${escape(note)}</p>
5524
+ </div>\`;
5525
+ return;
5526
+ }
5527
+ const players = room?.players ?? [];
5528
+ const mine = you();
5529
+ root.innerHTML = \`<div class="panel">
5530
+ <p class="code" data-room-code>\${escape(room?.code ?? '')}</p>
5531
+ \${button('copy', 'invite')}
5532
+ <p>\${escape(word('players'))} \${players.length}</p>
5533
+ <ul>\${players.map((player) => \`<li><span>\${escape(player.name)}\${player.id === room.you ? \` (\${escape(word('you'))})\` : ''}</span><span data-ready="\${player.ready}">\${escape(word(player.ready ? 'ready' : 'notReady'))}</span></li>\`).join('')}</ul>
5534
+ <div class="row">
5535
+ \${button('ready', 'ready', mine?.ready ? ' aria-pressed="true"' : ' aria-pressed="false"')}
5536
+ </div>
5537
+ \${button('leave', 'leave')}
5538
+ <p class="note" role="status">\${escape(note)}</p>
5539
+ </div>\`;
5540
+ }
5541
+
5542
+ function fail(error) {
5543
+ joining = false;
5544
+ note = error?.message ?? String(error);
5545
+ render();
5546
+ }
5547
+
5548
+ function attach(next) {
5549
+ clear();
5550
+ room = next;
5551
+ input.onRoom?.(next);
5552
+ const sync = () => {
5553
+ // Il menu si fa da parte quando si gioca e torna per il risultato.
5554
+ if (room.status === 'playing' || room.status === 'countdown') view = 'playing';
5555
+ else if (room.status === 'finished' || room.status === 'ended') {
5556
+ // Il testo del risultato lo scrive il gioco, che conosce il suo punteggio.
5557
+ result = input.resultText?.(room) ?? word('over');
5558
+ view = 'result';
5559
+ } else view = 'room';
5560
+ if (room.connection === 'closed') {
5561
+ // La stanza non esiste piu': resta solo il ritorno al menu.
5562
+ room = null; clear(); result = word('closed'); view = 'result';
5563
+ }
5564
+ render();
5565
+ };
5566
+ stops = [next.onPlayers(sync), next.onStatus(sync), next.onConnection(sync)];
5567
+ joining = false; note = ''; sync();
5568
+ }
5569
+
5570
+ root.addEventListener('click', (event) => {
5571
+ const action = event.target.closest?.('[data-action]')?.dataset.action;
5572
+ if (!action || action === 'join') return;
5573
+ // Da soli lo stato vive nel browser: non serve aprire una stanza.
5574
+ if (action === 'solo') { view = 'playing'; render(); input.onSolo?.(); return; }
5575
+ if (action === 'create') {
5576
+ joining = true; note = word('working'); render();
5577
+ c.room.create({ mode: input.mode ?? null }).then(attach, fail);
5578
+ return;
5579
+ }
5580
+ if (action === 'copy') {
5581
+ const invite = room?.invite();
5582
+ if (!invite) return;
5583
+ void Promise.resolve()
5584
+ .then(() => navigator.clipboard.writeText(invite.url))
5585
+ .then(() => { note = word('copied'); render(); }, () => { note = invite.url; render(); });
5586
+ return;
5587
+ }
5588
+ if (action === 'ready') { room?.ready(!you()?.ready); return; }
5589
+ if (action === 'again') { try { room?.restart(); } catch (error) { fail(error); } return; }
5590
+ if (action === 'leave' || action === 'back') {
5591
+ clear(); room?.leave(); room = null; view = 'home'; note = ''; render(); input.onExit?.();
5592
+ }
5593
+ });
5594
+
5595
+ root.addEventListener('submit', (event) => {
5596
+ event.preventDefault();
5597
+ const field = root.querySelector('[data-control="code"]');
5598
+ const code = (field?.value ?? '').toUpperCase().replace(/[\\s-]/g, '');
5599
+ if (code.length !== 6) { note = word('code'); render(); return; }
5600
+ joining = true; note = word('working'); render();
5601
+ c.room.join(code).then(attach, fail);
5602
+ });
5603
+
5604
+ render();
5605
+ // Un invito nel link entra subito: il giocatore ha cliccato il link dell'amico.
5606
+ if (input.online && c.room.invited) {
5607
+ joining = true; note = word('working'); render();
5608
+ c.room.join(c.room.invited).then(attach, fail);
5609
+ }
5610
+ return {
5611
+ get room() { return room; },
5612
+ open(message = '') { clear(); room = null; view = 'home'; note = message; render(); },
5613
+ result(text) { result = text; view = 'result'; render(); },
5614
+ hide() { view = 'playing'; render(); },
5615
+ };
5616
+ }
5617
+ `;
5960
5618
 
5961
5619
  // src/arcade.ts
5962
5620
  function arcadeManifest(id, name) {
@@ -5964,21 +5622,16 @@ function arcadeManifest(id, name) {
5964
5622
  manifest: 1,
5965
5623
  id,
5966
5624
  name,
5967
- description: { en: "Score near the beacon in a 45-second round for 2 to 4 players.", it: "Segna vicino al faro in un round di 45 secondi da 2 a 4 giocatori." },
5625
+ description: { en: "Chase the beacon. Score with friends. You have 45 seconds.", it: "Insegui il faro. Segna con gli amici. Hai 45 secondi." },
5968
5626
  cover: "cover.png",
5969
5627
  card: "card.png",
5970
5628
  icon: "icon.png",
5971
5629
  platform: "both",
5972
5630
  languages: ["en", "it"],
5973
- overlay: { version: 1, accent: "#ffffff" },
5974
5631
  players: { min: 2, max: 4 },
5975
5632
  lobby: true,
5976
- spectators: { delayMs: 3e3 },
5977
5633
  modes: [{
5978
5634
  id: "arena",
5979
- execution: "room",
5980
- label: { en: "Beacon arena", it: "Arena del faro" },
5981
- instructions: { en: "Move with arrows or drag and pulse near the beacon to score the most points in 45 seconds.", it: "Muoviti con frecce o trascina e attiva impulsi vicino al faro per segnare piu punti in 45 secondi." },
5982
5635
  matchmaking: { key: ["pool"], defaults: { pool: "v1" }, timeoutMs: 12e3 }
5983
5636
  }]
5984
5637
  };
@@ -5986,12 +5639,60 @@ function arcadeManifest(id, name) {
5986
5639
  var arcadeFiles = {
5987
5640
  "client/index.html": index_html_default,
5988
5641
  "client/game.js": game_js_default,
5642
+ "client/menu.js": menu_js_default,
5989
5643
  "client/physics.js": physics_js_default,
5990
5644
  "server.js": server_js_default,
5991
5645
  "tests/physics.test.mjs": physics_test_mjs_default,
5992
5646
  "tests/server.test.mjs": server_test_mjs_default,
5993
- "client/i18n/en.json": JSON.stringify({ title: "Beacon arena", controls: "Move with arrows, WASD or drag and press Space to pulse near the beacon.", pulse: "Pulse", hint: "Arrows or drag to move; Space or Pulse to score near the beacon.", you: "You", score: "{n} points \xB7 {seconds}s", watching: "Watching the arena" }, null, 2) + "\n",
5994
- "client/i18n/it.json": JSON.stringify({ title: "Arena del faro", controls: "Muoviti con frecce, WASD o trascina e premi Spazio per un impulso vicino al faro.", pulse: "Impulso", hint: "Frecce o trascina per muoverti; Spazio o Impulso per segnare vicino al faro.", you: "Tu", score: "{n} punti \xB7 {seconds}s", watching: "Arena in osservazione" }, null, 2) + "\n"
5647
+ // Le chiavi menu.* sostituiscono le parole inglesi del menu del gioco.
5648
+ "client/i18n/en.json": JSON.stringify({
5649
+ title: "Beacon arena",
5650
+ controls: "Move with arrows, WASD or drag and press Space to pulse near the beacon.",
5651
+ pulse: "Pulse",
5652
+ hint: "Arrows or drag to move; Space or Pulse to score near the beacon.",
5653
+ you: "You",
5654
+ score: "{n} points \xB7 {seconds}s",
5655
+ "menu.create": "Create room",
5656
+ "menu.join": "Join with code",
5657
+ "menu.code": "Room code",
5658
+ "menu.enter": "Enter",
5659
+ "menu.invite": "Copy invite",
5660
+ "menu.copied": "Link copied",
5661
+ "menu.players": "Players",
5662
+ "menu.ready": "Ready",
5663
+ "menu.notReady": "Not ready",
5664
+ "menu.leave": "Leave",
5665
+ "menu.again": "Play again",
5666
+ "menu.back": "Menu",
5667
+ "menu.working": "One moment",
5668
+ "menu.you": "you",
5669
+ "menu.over": "Round over",
5670
+ "menu.closed": "The room is closed"
5671
+ }, null, 2) + "\n",
5672
+ "client/i18n/it.json": JSON.stringify({
5673
+ title: "Arena del faro",
5674
+ controls: "Muoviti con frecce, WASD o trascina e premi Spazio per un impulso vicino al faro.",
5675
+ pulse: "Impulso",
5676
+ hint: "Frecce o trascina per muoverti; Spazio o Impulso per segnare vicino al faro.",
5677
+ you: "Tu",
5678
+ score: "{n} punti \xB7 {seconds}s",
5679
+ "menu.create": "Crea stanza",
5680
+ "menu.join": "Entra con codice",
5681
+ "menu.code": "Codice stanza",
5682
+ "menu.enter": "Entra",
5683
+ "menu.invite": "Copia invito",
5684
+ "menu.copied": "Link copiato",
5685
+ "menu.players": "Giocatori",
5686
+ "menu.ready": "Pronto",
5687
+ "menu.notReady": "Non pronto",
5688
+ "menu.leave": "Esci",
5689
+ "menu.again": "Gioca ancora",
5690
+ "menu.back": "Menu",
5691
+ "menu.working": "Un momento",
5692
+ "menu.you": "tu",
5693
+ "menu.over": "Giro finito",
5694
+ "menu.closed": "La stanza e chiusa"
5695
+ }, null, 2) + "\n"
5995
5696
  };
5996
5697
 
5997
5698
  // src/browser.spec.mjs.txt
@@ -6009,7 +5710,7 @@ const require = createRequire(import.meta.url);
6009
5710
  const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
6010
5711
  const manifest = JSON.parse(await readFile('caisual.json', 'utf8'));
6011
5712
  const arcade = manifest.modes.some(mode => mode.id === 'arena');
6012
- const mode = manifest.modes.find(mode => mode.execution === 'room');
5713
+ const mode = manifest.modes.find(mode => (mode.players ?? manifest.players ?? { max: 1 }).max > 1);
6013
5714
  const count = Number(process.env.PLAYERS || (mode ? 2 : 1));
6014
5715
  const network = process.env.NETWORK === 'degraded' ? ['--latency', '120', '--jitter', '40', '--loss', '2'] : [];
6015
5716
 
@@ -6022,7 +5723,7 @@ async function until(read, label, timeout = 15000) {
6022
5723
  // I riquadri fuori vista possono sospendere il disegno, ma lo stato di rete deve restare osservabile.
6023
5724
  const waitState = (frame, check, value = null, options = {}) => frame.waitForFunction(check, value, { polling: 50, ...options });
6024
5725
 
6025
- test('full game, distinct guests and standard overlay in Chromium', { timeout: 120000 }, async () => {
5726
+ test('full game, distinct guests and the menu drawn by the game in Chromium', { timeout: 120000 }, async () => {
6026
5727
  const probe = createServer(); probe.listen(0, '127.0.0.1'); await once(probe, 'listening');
6027
5728
  const port = probe.address().port; await new Promise(done => probe.close(done));
6028
5729
  const cli = process.env.CAISUAL_CLI || require.resolve('@caisual/cli/dist/caisual.mjs');
@@ -6035,67 +5736,53 @@ test('full game, distinct guests and standard overlay in Chromium', { timeout: 1
6035
5736
  browser = await chromium.launch({ headless: !process.env.HEADED });
6036
5737
  page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
6037
5738
  const errors = []; page.on('pageerror', error => errors.push(error.message));
6038
- page.on('console', message => {
6039
- // I salvataggi assenti sono risposte previste dell'API, non errori del gioco.
6040
- const emptySave = /\\/api\\/kit\\/saves\\/(caisual-session-v1|resume)$/.test(message.location().url) && message.text() === 'Failed to load resource: the server responded with a status of 404 (Not Found)';
6041
- if (message.type() === 'error' && !emptySave) errors.push(message.text());
6042
- });
5739
+ page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); });
6043
5740
  await page.goto('http://localhost:' + port + '/__caisual/players?n=' + count + '&lang=' + (process.env.LANGUAGE || 'en'));
6044
- const hosts = [], games = [];
5741
+ const games = [];
6045
5742
  for (let i = 1; i <= count; i++) {
6046
5743
  const hostElement = await page.locator('section[data-player="' + i + '"] > iframe').elementHandle();
6047
- const host = await hostElement.contentFrame(); hosts.push(host);
6048
- const gameElement = await host.locator('#game').elementHandle(); const game = await gameElement.contentFrame(); games.push(game);
6049
- await waitState(game, () => !!window.caisualDebug?.c.session.current);
5744
+ const host = await hostElement.contentFrame();
5745
+ const gameElement = await host.locator('#game').elementHandle(); const game = await gameElement.contentFrame();
5746
+ games.push(game);
5747
+ await waitState(game, () => !!window.caisualDebug?.c);
6050
5748
  }
6051
5749
  const identities = await Promise.all(games.map(game => game.evaluate(() => window.caisualDebug.c.player.id)));
6052
5750
  assert.equal(new Set(identities).size, count);
6053
5751
  if (mode) {
6054
- for (const host of hosts) {
6055
- const tab = host.locator('[data-action="mode:multiplayer"]');
6056
- if (await tab.count()) await tab.click();
6057
- }
6058
- const select = hosts[0].locator('[data-control="mode"]');
6059
- if (await select.count()) await select.selectOption(mode.id);
6060
- await hosts[0].locator('[data-action="play"]').click();
6061
- await until(() => hosts[0].evaluate(() => !!window.caisualDev.roomCode), 'room code');
6062
- const code = await hosts[0].evaluate(() => window.caisualDev.roomCode);
5752
+ // La stanza, l'invito e il pronto sono bottoni del gioco: il sito non disegna nulla.
5753
+ await games[0].locator('[data-action="create"]').click();
5754
+ await until(() => games[0].locator('[data-room-code]').textContent().then(text => /^[A-Z0-9]{6}$/.test(text.trim())), 'room code');
5755
+ const code = (await games[0].locator('[data-room-code]').textContent()).trim();
6063
5756
  for (let i = 1; i < count; i++) {
6064
- await hosts[i].locator('[data-action="panel:join"]').click();
6065
- await hosts[i].locator('[data-control="code"]').fill(code);
6066
- await hosts[i].locator('[data-form="join"] button[type="submit"]').click();
5757
+ await games[i].locator('[data-control="code"]').fill(code);
5758
+ await games[i].locator('[data-form="join"] button[type="submit"]').click();
6067
5759
  }
6068
- for (const game of games) await waitState(game, n => window.caisualDebug.c.session.current.room?.players.length === n, count);
6069
- for (const host of hosts) await host.locator('[data-action="ready"]').click();
6070
- await hosts[0].locator('[data-action="start"]').click();
6071
- } else for (const host of hosts) await host.locator('[data-action="play"]').click();
6072
- for (const game of games) await waitState(game, () => {
6073
- const c = window.caisualDebug.c, session = c.session.current;
6074
- let view; const stop = c.overlay.onChange(value => view = value); stop();
6075
- return (session.room?.status ?? session.status) === 'playing' && !view.inputBlocked;
6076
- });
6077
- // Gli input attraversano il canvas vero, cosi' la prova scopre anche problemi di focus e overlay.
5760
+ for (const game of games) await waitState(game, n => window.caisualDebug.room?.players.length === n, count);
5761
+ // Niente bottone di inizio: con tutti pronti la partita parte da sola.
5762
+ for (const game of games) await game.locator('[data-action="ready"]').click();
5763
+ } else await games[0].locator('[data-action="solo"]').click();
5764
+ for (const game of games) await waitState(game, () => window.caisualDebug.playing === true);
5765
+ // Gli input attraversano il canvas vero, cosi' la prova scopre anche problemi di focus.
6078
5766
  for (const game of games) {
6079
5767
  if (arcade) await game.locator('canvas').press('ArrowRight', { delay: 300 });
6080
5768
  else await game.locator('canvas').press('Space');
6081
5769
  }
6082
5770
  if (arcade) {
6083
5771
  await until(async () => (await games[0].evaluate(() => {
6084
- const r = window.caisualDebug.c.session.current.room; return r.state.entities[r.you].ack;
5772
+ const r = window.caisualDebug.room; return r.state.entities[r.you].ack;
6085
5773
  })) > 10, 'server acknowledgement');
6086
5774
  const measurement = await games[0].evaluate(async () => {
6087
- const { c } = window.caisualDebug, canvas = document.querySelector('canvas'), start = window.caisualDebug.motion.visual.x;
5775
+ const canvas = document.querySelector('canvas'), start = window.caisualDebug.motion.visual.x;
6088
5776
  canvas.dispatchEvent(new KeyboardEvent('keydown', { code: 'ArrowLeft', bubbles: true }));
6089
5777
  await new Promise(done => setTimeout(done, 65));
6090
5778
  canvas.dispatchEvent(new KeyboardEvent('keyup', { code: 'ArrowLeft', bubbles: true }));
6091
- return { movement: Math.abs(window.caisualDebug.motion.visual.x - start), pending: window.caisualDebug.motion.pending, latency: c.session.current.room.latency };
5779
+ return { movement: Math.abs(window.caisualDebug.motion.visual.x - start), pending: window.caisualDebug.motion.pending, latency: window.caisualDebug.room.latency };
6092
5780
  });
6093
5781
  assert.ok(measurement.movement > .5, 'local prediction responds before a delayed acknowledgement');
6094
5782
  console.log('Prediction:', JSON.stringify(measurement));
6095
- }
6096
- if (arcade) {
5783
+
6097
5784
  const game = games[0];
6098
- await until(() => game.evaluate(() => window.caisualDebug.c.session.current.room.latency !== null), 'first round-trip measurement');
5785
+ await until(() => game.evaluate(() => window.caisualDebug.room.latency !== null), 'first round-trip measurement');
6099
5786
  await game.locator('canvas').scrollIntoViewIfNeeded();
6100
5787
  const remoteMotion = games[1].evaluate(async id => {
6101
5788
  const points = [], end = performance.now() + 3200;
@@ -6110,8 +5797,8 @@ test('full game, distinct guests and standard overlay in Chromium', { timeout: 1
6110
5797
  }, identities[0]);
6111
5798
  for (let attempt = 0; attempt < 3; attempt++) {
6112
5799
  const target = await game.evaluate(async () => {
6113
- const { beacon } = await import('./physics.js'), { c, motion } = window.caisualDebug;
6114
- const point = beacon(c.session.current.room.state.step);
5800
+ const { beacon } = await import('./physics.js'), { room, motion } = window.caisualDebug;
5801
+ const point = beacon(room.state.step);
6115
5802
  return { x: motion.layout.x + point.x * motion.layout.scale, y: motion.layout.y + point.y * motion.layout.scale };
6116
5803
  });
6117
5804
  const box = await game.locator('canvas').boundingBox();
@@ -6133,62 +5820,36 @@ test('full game, distinct guests and standard overlay in Chromium', { timeout: 1
6133
5820
  console.log('Motion:', JSON.stringify({ frames: samples.length, maxStep: Math.max(...jumps.map(p => p.distance)), maxPending: Math.max(...samples.map(p => p.pending)) }));
6134
5821
  await game.locator('#pulse').click();
6135
5822
  await page.waitForTimeout(650);
6136
- if (await game.evaluate(() => { const r = window.caisualDebug.c.session.current.room; return r.state.entities[r.you].score > 0; })) break;
5823
+ if (await game.evaluate(() => { const r = window.caisualDebug.room; return r.state.entities[r.you].score > 0; })) break;
6137
5824
  }
6138
5825
  const remoteSamples = await remoteMotion;
6139
5826
  const remoteJumps = remoteSamples.slice(1).map((p, i) => ({ dt: (p.at - remoteSamples[i].at) / 1000, distance: Math.hypot(p.x - remoteSamples[i].x, p.y - remoteSamples[i].y) }));
6140
5827
  assert.ok(remoteJumps.some(p => p.distance > .1), 'the other player sees movement');
6141
5828
  assert.ok(remoteJumps.every(p => p.distance < 220 * p.dt + 8), 'remote interpolation stays continuous');
6142
- console.log('Remote:', JSON.stringify({ frames: remoteSamples.length, maxStep: Math.max(...remoteJumps.map(p => p.distance)), latency: await game.evaluate(() => window.caisualDebug.c.session.current.room.latency) }));
6143
- assert.ok(await game.evaluate(() => { const r = window.caisualDebug.c.session.current.room; return r.state.entities[r.you].score > 0; }), 'a real pulse scores at the server-owned beacon');
5829
+ console.log('Remote:', JSON.stringify({ frames: remoteSamples.length, maxStep: Math.max(...remoteJumps.map(p => p.distance)), latency: await game.evaluate(() => window.caisualDebug.room.latency) }));
5830
+ assert.ok(await game.evaluate(() => { const r = window.caisualDebug.room; return r.state.entities[r.you].score > 0; }), 'a real pulse scores at the server-owned beacon');
6144
5831
  await mkdir('test-results', { recursive: true });
6145
5832
  await page.screenshot({ path: resolve('test-results/arena-' + (network.length ? 'degraded' : 'normal') + '.png'), fullPage: true });
6146
5833
  }
6147
- if (arcade) {
6148
- // Chromium non espone una tacca fisica, quindi gli inset noti verificano il posizionamento reale dell'HUD.
6149
- await hosts[0].locator('[data-caisual-overlay]').evaluate(element => {
6150
- const sheet = new CSSStyleSheet(); sheet.replaceSync('.safe-area-probe{padding:32px 18px 24px 12px}');
6151
- element.shadowRoot.adoptedStyleSheets = [...element.shadowRoot.adoptedStyleSheets, sheet];
6152
- window.dispatchEvent(new Event('resize'));
6153
- });
6154
- await waitState(games[0], () => {
6155
- let view; const stop = window.caisualDebug.c.overlay.onChange(value => view = value); stop(); return view.safeArea.top === 32;
6156
- });
6157
- }
6158
- for (const game of games) {
6159
- const geometry = await game.evaluate(() => {
6160
- const c = window.caisualDebug.c; let view; const stop = c.overlay.onChange(value => view = value); stop();
6161
- const hud = document.querySelector('#hud') ?? document.querySelector('#status'), rect = hud.getBoundingClientRect();
6162
- const overlap = view.reservedRects.some(r => rect.x < r.x + r.width && rect.right > r.x && rect.y < r.y + r.height && rect.bottom > r.y);
6163
- return { reserved: view.reservedRects.length, overlap, inside: rect.x >= (view.safeArea.left || 0) && rect.y >= (view.safeArea.top || 0) && rect.right <= innerWidth - (view.safeArea.right || 0) && rect.bottom <= innerHeight - (view.safeArea.bottom || 0) };
6164
- });
6165
- assert.ok(geometry.reserved > 0); assert.equal(geometry.overlap, false); assert.equal(geometry.inside, true);
6166
- }
6167
5834
  if (mode) {
6168
- await page.locator('section[data-player="1"]').getByRole('button', { name: 'Spectate', exact: true }).click();
6169
- const spectatorFrame = page.locator('section[data-player="' + (count + 1) + '"] > iframe');
6170
- await spectatorFrame.scrollIntoViewIfNeeded();
6171
- const spectatorHost = await (await spectatorFrame.elementHandle()).contentFrame();
6172
- const spectator = await (await spectatorHost.locator('#game').elementHandle()).contentFrame();
6173
- await waitState(spectator, () => window.caisualDebug?.c.session.current.kind === 'watch');
6174
- const members = await games[0].evaluate(() => window.caisualDebug.c.session.current.room.players.length); assert.equal(members, count);
5835
+ // La caduta e il rientro non devono cambiare identita' ne' perdere il posto nella stanza.
6175
5836
  await page.locator('section[data-player="1"]').getByRole('button', { name: 'Drop', exact: true }).click();
6176
- await waitState(games[0], () => window.caisualDebug.c.session.current.room.connection === 'reconnecting');
6177
- await waitState(games[0], () => window.caisualDebug.c.session.current.room.connection === 'connected', null, { timeout: 20000 });
5837
+ await waitState(games[0], () => window.caisualDebug.room.connection === 'reconnecting');
5838
+ await waitState(games[0], () => window.caisualDebug.room.connection === 'connected', null, { timeout: 20000 });
6178
5839
  assert.equal(await games[0].evaluate(() => window.caisualDebug.c.player.id), identities[0]);
6179
5840
  }
6180
5841
  if (arcade) {
6181
5842
  await page.locator('#size').selectOption('desktop');
6182
5843
  for (const game of games) await waitState(game, () => innerWidth === 960 && innerHeight === 640);
6183
- // Una corsa completa copre il risultato standard e la rivincita senza un secondo giro di lobby.
6184
- for (const game of games) await waitState(game, () => window.caisualDebug.c.session.current.room.status === 'finished', null, { timeout: 60000 });
6185
- assert.equal(await games[0].evaluate(() => window.caisualDebug.c.session.current.room.result.standings.length), count);
6186
- for (let i = 0; i < hosts.length; i++) {
5844
+ // Una corsa completa copre il risultato del gioco e la rivincita senza un secondo giro di lobby.
5845
+ for (const game of games) await waitState(game, () => window.caisualDebug.room.status === 'finished', null, { timeout: 60000 });
5846
+ assert.equal(await games[0].evaluate(() => window.caisualDebug.room.result.standings.length), count);
5847
+ for (let i = 0; i < games.length; i++) {
6187
5848
  await page.locator('section[data-player="' + (i + 1) + '"] > iframe').scrollIntoViewIfNeeded();
6188
- await hosts[i].locator('[data-action="again"]').click();
5849
+ await games[i].locator('[data-action="again"]').click();
6189
5850
  }
6190
5851
  for (const game of games) await waitState(game, () => {
6191
- const r = window.caisualDebug.c.session.current.room; return r.status === 'playing' && r.state.round === 2;
5852
+ const r = window.caisualDebug.room; return r.status === 'playing' && r.state.round === 2;
6192
5853
  }, null, { timeout: 15000 });
6193
5854
  }
6194
5855
  await mkdir('test-results', { recursive: true });
@@ -6362,7 +6023,7 @@ var ApiError = class extends Error {
6362
6023
  hints;
6363
6024
  };
6364
6025
  function help() {
6365
- return `Caisual ${"0.21.0"}
6026
+ return `Caisual ${"0.22.0"}
6366
6027
 
6367
6028
  Usage:
6368
6029
  caisual init [--multiplayer | --arcade] [folder]
@@ -6421,18 +6082,19 @@ async function init(folderArgument, multiplayer, arcade) {
6421
6082
  ...Object.fromEntries(Object.entries(JSON.parse(images_base64_default)[arcade ? "arcade" : "base"]).map(([path, base64]) => [path, Buffer.from(base64, "base64")])),
6422
6083
  "caisual.json": JSON.stringify(manifest, null, 2) + "\n",
6423
6084
  ...arcade ? arcadeFiles : {
6424
- "client/index.html": templateIndex,
6085
+ "client/index.html": templateIndex(multiplayer),
6086
+ "client/menu.js": menu_js_default,
6425
6087
  "client/i18n/en.json": JSON.stringify(templateTexts, null, 2) + "\n",
6426
6088
  ...multiplayer ? { "server.js": templateServer } : {}
6427
6089
  },
6428
6090
  "README.md": `# ${name}
6429
6091
 
6092
+ ${NETWORK_GUIDANCE}
6093
+
6430
6094
  Run npm install, then npm run dev to test the game locally.
6431
6095
 
6432
6096
  The game style is yours to choose; templates are deliberately neutral. Replace client/cover.png, client/card.png and client/icon.png before publishing: these gray images are temporary placeholders.
6433
6097
 
6434
- In caisual.json, overlay.accent is white by default: choose your own accent.
6435
-
6436
6098
  Put game text in client/i18n/ and localize description in caisual.json. Run caisual check before publishing.
6437
6099
  `,
6438
6100
  "tests/browser.spec.mjs": browser_spec_mjs_default,
@@ -6784,7 +6446,33 @@ function parseUploads(payload, files, server, wasm = []) {
6784
6446
  serverTarget
6785
6447
  };
6786
6448
  }
6787
- async function readManifest(root, warn) {
6449
+ var CAMPI_RIMOSSI2 = [
6450
+ { percorso: "overlay", motivo: "the platform no longer draws anything over the game; the game draws its own menu" },
6451
+ { percorso: "replays", motivo: "replays were removed" },
6452
+ { percorso: "modes[].label", motivo: "only the game shows mode names now" },
6453
+ { percorso: "modes[].instructions", motivo: "the game explains itself" },
6454
+ { percorso: "roles[].label", motivo: "only the game shows role names now" }
6455
+ ];
6456
+ function campiRimossi(value) {
6457
+ const manifest = object2(value);
6458
+ if (manifest === null) return [];
6459
+ const elenco = (chiave) => Array.isArray(manifest[chiave]) ? manifest[chiave].flatMap((voce) => {
6460
+ const record2 = object2(voce);
6461
+ return record2 === null ? [] : [record2];
6462
+ }) : [];
6463
+ const presenti = /* @__PURE__ */ new Set();
6464
+ for (const campo of ["overlay", "replays"]) {
6465
+ if (Object.hasOwn(manifest, campo)) presenti.add(campo);
6466
+ }
6467
+ for (const mode of elenco("modes")) {
6468
+ for (const campo of ["label", "instructions"]) if (Object.hasOwn(mode, campo)) presenti.add(`modes[].${campo}`);
6469
+ }
6470
+ for (const role of elenco("roles")) {
6471
+ if (Object.hasOwn(role, "label")) presenti.add("roles[].label");
6472
+ }
6473
+ return CAMPI_RIMOSSI2.filter((campo) => presenti.has(campo.percorso)).map((campo) => `remove ${campo.percorso}: ${campo.motivo}`);
6474
+ }
6475
+ async function readManifest(root, warn, pubblicazione = true) {
6788
6476
  const path = join4(root, "caisual.json");
6789
6477
  let source;
6790
6478
  try {
@@ -6798,7 +6486,12 @@ async function readManifest(root, warn) {
6798
6486
  } catch {
6799
6487
  throw new CliError(2, "caisual.json: must contain valid JSON.");
6800
6488
  }
6801
- const result = validaManifest(value);
6489
+ const rimossi = campiRimossi(value);
6490
+ if (rimossi.length > 0) {
6491
+ throw new CliError(2, `caisual.json uses fields the platform removed:
6492
+ ${rimossi.map((voce) => `- ${voce}`).join("\n")}`);
6493
+ }
6494
+ const result = pubblicazione ? validaManifestPubblicazione(value) : validaManifest(value);
6802
6495
  if (!result.ok) {
6803
6496
  throw new CliError(2, `caisual.json is not valid:
6804
6497
  ${result.errori.map((error) => `- ${error}`).join("\n")}`);
@@ -6847,8 +6540,7 @@ async function checkGame(root) {
6847
6540
  id: manifest.id,
6848
6541
  name: manifest.name,
6849
6542
  languages: [...manifest.languages],
6850
- modes: manifest.modes.map((mode) => mode.id),
6851
- overlay: manifest.overlay !== null
6543
+ modes: manifest.modes.map((mode) => mode.id)
6852
6544
  };
6853
6545
  await captureGameError(report.errors, () => checkGameTexts(join4(root, "client"), manifest, warn));
6854
6546
  const files = await captureGameError(report.errors, () => listClientFiles(join4(root, "client")));
@@ -6878,8 +6570,9 @@ async function checkGame(root) {
6878
6570
  }
6879
6571
  try {
6880
6572
  if (serverResult !== null && richiedeServer(manifest) && serverResult.file === null) {
6881
- report.errors.push("server.js is required by a room mode.");
6573
+ report.errors.push("server.js is required for modes with two or more players.");
6882
6574
  }
6575
+ if (!richiedeServer(manifest) && report.server?.present) report.warnings.push(AVVISO_SERVER_INUTILE);
6883
6576
  if (files !== null) {
6884
6577
  const filePaths = new Set(files.map((file) => file.path));
6885
6578
  await captureGameError(report.errors, async () => {
@@ -6921,10 +6614,14 @@ async function check(folderArgument, json) {
6921
6614
  if (report.manifest !== null) {
6922
6615
  const modes = report.manifest.modes.length === 0 ? "none" : report.manifest.modes.join(", ");
6923
6616
  process.stdout.write(
6924
- `caisual.json: ${report.manifest.id} (${report.manifest.name}), languages ${report.manifest.languages.join(", ")}, modes ${modes}, overlay ${report.manifest.overlay ? "on" : "off"}
6617
+ `caisual.json: ${report.manifest.id} (${report.manifest.name}), languages ${report.manifest.languages.join(", ")}, modes ${modes}
6925
6618
  `
6926
6619
  );
6927
6620
  }
6621
+ process.stdout.write(`${SINGLE_PLAYER_RULE}
6622
+ `);
6623
+ if (report.server !== null) process.stdout.write(`${NETWORK_GUIDANCE} Static checks do not measure traffic; use caisual dev and the publication probe.
6624
+ `);
6928
6625
  if (report.client !== null) {
6929
6626
  const largest = report.client.largest[0];
6930
6627
  process.stdout.write(
@@ -7007,6 +6704,10 @@ async function publish(folderArgument) {
7007
6704
  method: "POST",
7008
6705
  headers: { Authorization: `Bearer ${key}` }
7009
6706
  });
6707
+ if (Array.isArray(completed.warnings)) for (const warning of completed.warnings) {
6708
+ if (typeof warning === "string") process.stderr.write(`Warning: ${warning}
6709
+ `);
6710
+ }
7010
6711
  if (typeof completed.url !== "string") {
7011
6712
  throw new CliError(1, "The portal completed the version without returning the game URL.");
7012
6713
  }
@@ -7026,7 +6727,7 @@ async function publish(folderArgument) {
7026
6727
  async function gameIdFromTarget(target) {
7027
6728
  const path = resolve3(process.cwd(), target);
7028
6729
  try {
7029
- if ((await fs4.stat(path)).isDirectory()) return (await readManifest(path)).id;
6730
+ if ((await fs4.stat(path)).isDirectory()) return (await readManifest(path, void 0, false)).id;
7030
6731
  } catch (error) {
7031
6732
  if (error.code !== "ENOENT") {
7032
6733
  throw new CliError(2, `The game target could not be read: ${target}`);
@@ -7090,7 +6791,7 @@ async function gameVersions(target, to) {
7090
6791
  }
7091
6792
  var SITO = "https://caisual.com";
7092
6793
  function guidesSection() {
7093
- const guides = JSON.parse('[{"slug":"overview","title":"What Caisual is","description":"A free home for small browser games, with multiplayer built in."},{"slug":"quick-start","title":"Quick start","description":"From an empty folder to a permanent link."},{"slug":"overlay","title":"The standard overlay","description":"You make the game. Caisual draws the menu, the lobby, the invites and the results on top of it."},{"slug":"manifest","title":"The manifest","description":"caisual.json is everything the portal knows about your game."},{"slug":"rooms","title":"Rooms","description":"Server-owned state for up to 24 players."},{"slug":"voice","title":"Voice","description":"Room voice in one manifest field, with gains owned by your server."},{"slug":"matchmaking","title":"Matchmaking","description":"One call puts strangers who asked for the same thing in the same room."},{"slug":"spectators","title":"Spectators","description":"Up to 100 people watch a room on a delay, with no change to your server."},{"slug":"friends-and-parties","title":"Friends","description":"Friends, parties and one-click join, with no API to call."},{"slug":"player-identity","title":"Identity","description":"Every player has a stable id before your game draws a frame."},{"slug":"saves","title":"Saves","description":"Cloud saves and one daily seed, single player included."},{"slug":"local-development","title":"Local dev","description":"The production handshake, multiple guests and network simulation."},{"slug":"device-requirements","title":"Devices","description":"Declare what you need, then read what the machine has."},{"slug":"versions","title":"Game versions","description":"Updates, rooms, rollback and compatible player data."},{"slug":"limits-and-rules","title":"Limits","description":"Every ceiling, every rule, in one page."},{"slug":"faq","title":"FAQ","description":"Short answers, in one place."}]');
6794
+ const guides = JSON.parse(`[{"slug":"overview","title":"What Caisual is","description":"A free home for small browser games, with multiplayer built in."},{"slug":"quick-start","title":"Quick start","description":"From an empty folder to a permanent link."},{"slug":"manifest","title":"The manifest","description":"caisual.json is everything the portal knows about your game."},{"slug":"rooms","title":"Rooms","description":"Server-owned state for up to 24 players."},{"slug":"voice","title":"Voice","description":"Room voice in one manifest field, with gains owned by your server."},{"slug":"matchmaking","title":"Matchmaking","description":"One call puts strangers who asked for the same thing in the same room."},{"slug":"friends-and-parties","title":"Friends","description":"The player's friends, their party and their invitations, inside your game."},{"slug":"player-identity","title":"Identity","description":"Every player has a stable id before your game draws a frame."},{"slug":"saves","title":"Saves","description":"Cloud saves and one daily seed, single player included."},{"slug":"local-development","title":"Local dev","description":"The production handshake, multiple guests and network simulation."},{"slug":"device-requirements","title":"Devices","description":"Declare what you need, then read what the machine has."},{"slug":"versions","title":"Game versions","description":"Updates, rooms, rollback and compatible player data."},{"slug":"limits-and-rules","title":"Limits","description":"Every ceiling, every rule, in one page."},{"slug":"faq","title":"FAQ","description":"Short answers, in one place."}]`);
7094
6795
  return [
7095
6796
  "# Guides",
7096
6797
  "",
@@ -7127,14 +6828,8 @@ ${guidesSection()}`;
7127
6828
  } catch (error) {
7128
6829
  if (error.code !== "ENOENT") throw error;
7129
6830
  }
7130
- if (!/^## Caisual\s*$/m.test(agents)) {
7131
- const section = `## Caisual
7132
- Read \`.claude/skills/caisual/SKILL.md\` before creating or publishing a Caisual game.
7133
- Use the current guides at ${SITO}/publish.md and ${SITO}/kit.md; the index of every guide is at ${SITO}/llms.txt.
7134
- `;
7135
- const separator = agents === "" ? "" : agents.endsWith("\n\n") ? "" : agents.endsWith("\n") ? "\n" : "\n\n";
7136
- await fs4.writeFile(agentsPath, `${agents}${separator}${section}`, "utf8");
7137
- }
6831
+ const updated = updateAgentInstructions(agents, SITO);
6832
+ if (updated !== agents) await fs4.writeFile(agentsPath, updated, "utf8");
7138
6833
  return skillPath;
7139
6834
  }
7140
6835
  async function run(argumentsList) {
@@ -7144,7 +6839,7 @@ async function run(argumentsList) {
7144
6839
  return;
7145
6840
  }
7146
6841
  if (command === "--version" || command === "-V") {
7147
- process.stdout.write(`${"0.21.0"}
6842
+ process.stdout.write(`${"0.22.0"}
7148
6843
  `);
7149
6844
  return;
7150
6845
  }
@@ -7251,7 +6946,7 @@ async function run(argumentsList) {
7251
6946
  }
7252
6947
  if (argument === "--day" || argument.startsWith("--day=")) {
7253
6948
  const value = argument === "--day" ? argumentsAfterCommand[++index] : argument.slice("--day=".length);
7254
- if (!validBoardDay(value)) throw new CliError(1, "--day must be a real UTC date in YYYY-MM-DD format.");
6949
+ if (!validDay(value)) throw new CliError(1, "--day must be a real UTC date in YYYY-MM-DD format.");
7255
6950
  day = value;
7256
6951
  continue;
7257
6952
  }