@caisual/kit 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kit.js CHANGED
@@ -1,4 +1,4 @@
1
- // Caisual game kit v0.10.0
1
+ // Caisual game kit v0.12.0
2
2
 
3
3
  // ../contracts/src/slug.ts
4
4
  var NOMI_RISERVATI = [
@@ -102,6 +102,8 @@ var CAMPI = /* @__PURE__ */ new Set([
102
102
  "name",
103
103
  "description",
104
104
  "cover",
105
+ "card",
106
+ "icon",
105
107
  "screenshots",
106
108
  "tags",
107
109
  "languages",
@@ -221,12 +223,21 @@ function validaManifest(valore) {
221
223
  }
222
224
  const description = stringaDefault(dati, "description", "", errori);
223
225
  if (description.length > 500) errori.push("description: must be at most 500 characters.");
224
- let cover = null;
225
- if (dati.cover !== void 0 && dati.cover !== null) {
226
- if (typeof dati.cover !== "string") errori.push("cover: must be a relative file path or null.");
227
- else if (!percorsoRelativo(dati.cover)) errori.push("cover: must be a relative file path without query, fragment, or parent segments.");
228
- else cover = dati.cover;
226
+ const immagini = { cover: "", card: "", icon: "" };
227
+ const usati = /* @__PURE__ */ new Set();
228
+ for (const campo of ["cover", "card", "icon"]) {
229
+ const path = dati[campo];
230
+ if (path === void 0 || path === null) errori.push(`${campo}: is required.`);
231
+ else if (typeof path !== "string" || !percorsoRelativo(path)) errori.push(`${campo}: must be a relative file path inside client/ without query, fragment, or parent segments.`);
232
+ else {
233
+ if (!/\.(png|jpe?g|webp)$/i.test(path)) errori.push(`${campo}: must be a PNG, JPEG or WebP file.`);
234
+ const canonical = decodeURIComponent(path);
235
+ if (usati.has(canonical)) errori.push(`${campo}: each image must use a different file; cover, card and icon cannot share a path.`);
236
+ usati.add(canonical);
237
+ immagini[campo] = path;
238
+ }
229
239
  }
240
+ const { cover, card, icon } = immagini;
230
241
  const screenshots = [];
231
242
  if (dati.screenshots !== void 0) {
232
243
  if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");
@@ -256,8 +267,7 @@ function validaManifest(valore) {
256
267
  errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
257
268
  }
258
269
  const languages2 = [];
259
- if (dati.languages === void 0) languages2.push(normalizeLanguage(legacyLanguage) ?? legacyLanguage);
260
- else if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
270
+ if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
261
271
  errori.push("languages: must be a non-empty array of BCP 47 language tags.");
262
272
  } else for (const [index, raw] of dati.languages.entries()) {
263
273
  const tag = normalizeLanguage(raw);
@@ -265,6 +275,7 @@ function validaManifest(valore) {
265
275
  else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);
266
276
  else languages2.push(tag);
267
277
  }
278
+ if (!languages2.includes("en")) errori.push("languages: English is always required alongside the game's own languages.");
268
279
  const language = languages2[0] ?? legacyLanguage;
269
280
  if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
270
281
  errori.push("language: must match the first entry in languages when both are present.");
@@ -420,12 +431,14 @@ function validaManifest(valore) {
420
431
  continue;
421
432
  }
422
433
  for (const campo of Object.keys(board)) {
423
- if (!["source", "label", "periods"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
434
+ if (!["source", "label", "periods", "day"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
424
435
  }
425
436
  if (board.source !== "client" && board.source !== "server") {
426
437
  errori.push(`boards.${id2}.source: must be "client" or "server".`);
427
438
  valido = false;
428
439
  }
440
+ if (board.day !== void 0 && board.day !== "submit" && board.day !== "start") errori.push(`boards.${id2}.day: must be "submit" or "start".`);
441
+ if (board.day === "start" && board.source !== "server") errori.push(`boards.${id2}.day: start requires source "server".`);
429
442
  const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
430
443
  let periods = ["all-time"];
431
444
  if (board.periods !== void 0) {
@@ -436,6 +449,7 @@ function validaManifest(valore) {
436
449
  if (valido) Object.defineProperty(boards, id2, { value: {
437
450
  source: board.source,
438
451
  periods,
452
+ ...board.day === void 0 ? {} : { day: board.day },
439
453
  ...label === void 0 ? {} : { label }
440
454
  }, enumerable: true, configurable: true, writable: true });
441
455
  }
@@ -632,6 +646,8 @@ function validaManifest(valore) {
632
646
  name,
633
647
  description,
634
648
  cover,
649
+ card,
650
+ icon,
635
651
  screenshots,
636
652
  tags,
637
653
  languages: languages2,
@@ -786,21 +802,21 @@ async function probeDevice(globals, timeoutMs = 1500) {
786
802
  }
787
803
 
788
804
  // ../contracts/src/overlay.ts
789
- function overlayConfiguration(manifest, coverUrl = null, invite = null) {
805
+ function overlayConfiguration(manifest, coverUrl = null, invite = null, iconUrl = null) {
790
806
  const validated = validaManifest(manifest);
791
807
  if (!validated.ok) throw new Error("The overlay manifest is invalid.");
792
- return { manifest: validated.manifest, coverUrl, invite };
808
+ return { manifest: validated.manifest, coverUrl, iconUrl, invite };
793
809
  }
794
810
  function record(value) {
795
811
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
796
812
  }
797
813
  function validOverlayHello(value) {
798
814
  const hello = record(value), config = record(hello?.configuration);
799
- return hello?.v === 1 && typeof hello.epoch === "string" && hello.epoch.length > 0 && hello.epoch.length <= 128 && config !== null && (config.coverUrl === null || typeof config.coverUrl === "string") && (config.invite === null || typeof config.invite === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(config.invite)) && validaManifest(config.manifest).ok;
815
+ return hello?.v === 1 && typeof hello.epoch === "string" && hello.epoch.length > 0 && hello.epoch.length <= 128 && config !== null && (config.coverUrl === null || typeof config.coverUrl === "string") && (config.iconUrl === null || typeof config.iconUrl === "string") && (config.invite === null || typeof config.invite === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(config.invite)) && validaManifest(config.manifest).ok;
800
816
  }
801
817
  function normalizeOverlayHello(value) {
802
818
  if (!validOverlayHello(value)) return null;
803
- return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite) };
819
+ return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite, value.configuration.iconUrl) };
804
820
  }
805
821
  function validSafeArea(value) {
806
822
  const area = record(value);
@@ -868,6 +884,32 @@ function validBoardDay(value) {
868
884
  // ../contracts/src/room-limits.ts
869
885
  var MESSAGGI_GIOCO_AL_SECONDO = 20;
870
886
 
887
+ // ../contracts/src/match-result.ts
888
+ function readMatchResult(value, playerIds) {
889
+ const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
890
+ const result = object(value);
891
+ if (!result || !Array.isArray(result.standings)) return null;
892
+ const known = new Set(playerIds), seen = /* @__PURE__ */ new Set();
893
+ const standings = [];
894
+ for (const item of result.standings) {
895
+ const row = object(item);
896
+ if (!row || typeof row.playerId !== "string" || !known.has(row.playerId) || seen.has(row.playerId)) continue;
897
+ seen.add(row.playerId);
898
+ standings.push({
899
+ playerId: row.playerId,
900
+ ...typeof row.score === "number" && Number.isFinite(row.score) ? { score: row.score } : {},
901
+ ...typeof row.rank === "number" && Number.isSafeInteger(row.rank) && row.rank > 0 ? { rank: row.rank } : {}
902
+ });
903
+ }
904
+ if (!standings.length) return null;
905
+ return {
906
+ standings,
907
+ ...Array.isArray(result.winners) ? { winners: [...new Set(result.winners.filter((id) => typeof id === "string" && seen.has(id)))] } : {},
908
+ ...typeof result.draw === "boolean" ? { draw: result.draw } : {},
909
+ ...typeof result.unit === "string" ? { unit: result.unit } : {}
910
+ };
911
+ }
912
+
871
913
  // src/overlay/i18n.ts
872
914
  var languages = ["en", "it", "es", "fr", "de", "pt"];
873
915
  var words = {
@@ -913,6 +955,13 @@ var words = {
913
955
  ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada"],
914
956
  rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos"],
915
957
  rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche"],
958
+ won: ["You won", "Hai vinto", "Has ganado", "Vous avez gagn\xE9", "Du hast gewonnen", "Voc\xEA venceu"],
959
+ lost: ["You lost", "Hai perso", "Has perdido", "Vous avez perdu", "Du hast verloren", "Voc\xEA perdeu"],
960
+ draw: ["Draw", "Pareggio", "Empate", "\xC9galit\xE9", "Unentschieden", "Empate"],
961
+ standings: ["Standings", "Piazzamenti", "Posiciones", "R\xE9sultats", "Platzierungen", "Coloca\xE7\xF5es"],
962
+ points: ["points", "punti", "puntos", "points", "Punkte", "pontos"],
963
+ time: ["time", "tempo", "tiempo", "temps", "Zeit", "tempo"],
964
+ distance: ["distance", "distanza", "distancia", "distance", "Distanz", "dist\xE2ncia"],
916
965
  again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente"],
917
966
  newRoom: ["New room. Share the new invite.", "Nuova stanza. Condividi il nuovo invito.", "Nueva sala. Comparte la invitaci\xF3n.", "Nouvelle salle. Partagez le lien.", "Neuer Raum. Neue Einladung teilen.", "Nova sala. Compartilhe o convite."],
918
967
  watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo"],
@@ -1133,6 +1182,7 @@ function createSession(base, configuration = null, roomsAvailable = base.connect
1133
1182
  function snapshot() {
1134
1183
  const attached = current.kind === "room" || current.kind === "watch" ? current.room : null;
1135
1184
  const configured = attached?.metadata.configuration;
1185
+ const result = attached ? readMatchResult(attached.result, attached.players.map((p) => p.id)) : null;
1136
1186
  const fallback = manifest && attached && (attached.mode === null || manifest.modes.some((m) => m.id === attached.mode)) ? risolviModalita(manifest, attached.mode) : { players: { min: 1, max: 1 }, lobby: false };
1137
1187
  return {
1138
1188
  kind: pending ?? (current.kind === "idle" ? ready ? "home" : "boot" : current.kind),
@@ -1142,12 +1192,14 @@ function createSession(base, configuration = null, roomsAvailable = base.connect
1142
1192
  ready,
1143
1193
  capabilities: capabilities(),
1144
1194
  room: attached ? {
1195
+ ...attached.metadata.rematch?.keepSetup || attached.metadata.rematch?.autoStart ? { rematch: attached.metadata.rematch } : {},
1145
1196
  code: attached.code,
1146
1197
  mode: attached.mode,
1147
1198
  status: attached.status,
1148
1199
  host: attached.host,
1149
1200
  you: current.kind === "room" ? current.room.you : null,
1150
1201
  players: attached.players.map((p) => ({ id: p.id, name: p.name, guest: p.guest, role: p.role, team: p.team, ready: p.ready, connected: p.connected })),
1202
+ ...result ? { result } : {},
1151
1203
  countdownAt: attached.countdownAt,
1152
1204
  connection: attached.connection,
1153
1205
  closedCode: attached.metadata.closedCode,
@@ -1683,6 +1735,53 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
1683
1735
 
1684
1736
  // src/daily.ts
1685
1737
  var DIVISORE_UINT32 = 4294967296;
1738
+ function prossimaMezzanotteUtc(ora) {
1739
+ return (Math.floor(ora / 864e5) + 1) * 864e5;
1740
+ }
1741
+ function creaDaily(initial, now, refresh) {
1742
+ const listeners = /* @__PURE__ */ new Set();
1743
+ let current = { ...initial }, timer, pending = false;
1744
+ function schedule() {
1745
+ if (!listeners.size || timer !== void 0 || pending) return;
1746
+ timer = setTimeout(check, Math.max(0, Math.min(2147483647, current.expiresAt - now())));
1747
+ timer.unref?.();
1748
+ }
1749
+ async function check() {
1750
+ timer = void 0;
1751
+ pending = true;
1752
+ try {
1753
+ const next = await refresh(), changed = next.day !== current.day;
1754
+ current = { ...next };
1755
+ if (changed) for (const listener of [...listeners]) {
1756
+ try {
1757
+ listener({ ...next });
1758
+ } catch {
1759
+ }
1760
+ }
1761
+ } catch {
1762
+ } finally {
1763
+ pending = false;
1764
+ if (current.expiresAt <= now()) current.expiresAt = now() + 3e4;
1765
+ schedule();
1766
+ }
1767
+ }
1768
+ return {
1769
+ ...initial,
1770
+ random: creaMulberry32(initial.seed),
1771
+ rng: () => creaMulberry32(initial.seed),
1772
+ onChange(listener) {
1773
+ listeners.add(listener);
1774
+ schedule();
1775
+ return () => {
1776
+ listeners.delete(listener);
1777
+ if (!listeners.size && timer !== void 0) {
1778
+ clearTimeout(timer);
1779
+ timer = void 0;
1780
+ }
1781
+ };
1782
+ }
1783
+ };
1784
+ }
1686
1785
  function giornoUtc(ora) {
1687
1786
  return new Date(ora).toISOString().slice(0, 10);
1688
1787
  }
@@ -2936,6 +3035,7 @@ var StanzaClient = class {
2936
3035
  host: room.host,
2937
3036
  mode: room.mode,
2938
3037
  countdownAt: room.countdownAt ?? null,
3038
+ rematch: room.rematch ?? null,
2939
3039
  configuration: room.configuration ?? null,
2940
3040
  connection: "connected",
2941
3041
  closedCode: null
@@ -3336,6 +3436,7 @@ var StanzaClient = class {
3336
3436
  this.ultimoInput = null;
3337
3437
  }
3338
3438
  this.metadataChanged({
3439
+ rematch: dati.rematch ?? null,
3339
3440
  host: this.hostCorrente,
3340
3441
  countdownAt: dati.countdownAt ?? (dati.status === "countdown" ? dati.at : null),
3341
3442
  ...dati.status === "ended" ? { connection: "ended", closedCode: 4004 } : {}
@@ -3804,12 +3905,15 @@ function creaSave(archivio, ora) {
3804
3905
  };
3805
3906
  }
3806
3907
  async function creaStandalone(input, invited = null) {
3807
- const day = giornoUtc(input.ora());
3908
+ const startedAt = input.ora(), day = giornoUtc(startedAt);
3808
3909
  const seed = await calcolaSeed(input.hostname, day, input.subtle);
3809
3910
  return {
3810
3911
  connected: false,
3811
3912
  player: { id: "local", name: "Guest", guest: true },
3812
- daily: { day, seed, random: creaMulberry32(seed), rng: () => creaMulberry32(seed) },
3913
+ daily: creaDaily({ day, seed, expiresAt: prossimaMezzanotteUtc(startedAt) }, input.ora, async () => {
3914
+ const now = input.ora(), day2 = giornoUtc(now);
3915
+ return { day: day2, seed: await calcolaSeed(input.hostname, day2, input.subtle), expiresAt: prossimaMezzanotteUtc(now) };
3916
+ }),
3813
3917
  time: { now: input.ora },
3814
3918
  save: creaSave(input.archivio, input.ora),
3815
3919
  board: {
@@ -3921,7 +4025,14 @@ async function connetti(input) {
3921
4025
  const base = {
3922
4026
  connected: true,
3923
4027
  player: me.player,
3924
- daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed), rng: () => creaMulberry32(me.seed) },
4028
+ daily: creaDaily(
4029
+ { day: me.day, seed: me.seed, expiresAt: me.expiresAt ?? prossimaMezzanotteUtc(me.serverTime) },
4030
+ () => input.ora() + scartoOrario,
4031
+ async () => {
4032
+ const next = await api.me();
4033
+ return { day: next.day, seed: next.seed, expiresAt: next.expiresAt ?? prossimaMezzanotteUtc(next.serverTime) };
4034
+ }
4035
+ ),
3925
4036
  time: { now: () => input.ora() + scartoOrario },
3926
4037
  save: {
3927
4038
  set: (key, value) => api.saveSet(key, value),
package/dist/node.js CHANGED
@@ -94,6 +94,9 @@ var LimiteMessaggiStanza = class {
94
94
  };
95
95
 
96
96
  // src/daily.ts
97
+ function prossimaMezzanotteUtc(ora) {
98
+ return (Math.floor(ora / 864e5) + 1) * 864e5;
99
+ }
97
100
  function giornoUtc(ora) {
98
101
  return new Date(ora).toISOString().slice(0, 10);
99
102
  }
@@ -341,6 +344,7 @@ var GRAZIA_MS = 6e4;
341
344
  var STANZA_VUOTA_MS = 5 * 6e4;
342
345
  var ATTESA_RIVINCITA_MS = 2 * 6e4;
343
346
  var COUNTDOWN_MS = 3e3;
347
+ var GRAZIA_GIORNALIERA_MS = 10 * 6e4;
344
348
  var RIPOSO_TICK_MS = 3e4;
345
349
  var INATTIVITA_MS = 10 * 6e4;
346
350
  var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
@@ -403,10 +407,13 @@ var NucleoStanza = class _NucleoStanza {
403
407
  const nucleo = this;
404
408
  const daily = {
405
409
  get day() {
406
- return nucleo.giornata();
410
+ return nucleo.richiediDati().daily.day;
407
411
  },
408
412
  get seed() {
409
- return seedGiornata(nucleo.manifest.id, nucleo.giornata());
413
+ return nucleo.richiediDati().daily.seed;
414
+ },
415
+ get expiresAt() {
416
+ return nucleo.richiediDati().daily.expiresAt;
410
417
  }
411
418
  };
412
419
  this.room = {
@@ -461,7 +468,7 @@ var NucleoStanza = class _NucleoStanza {
461
468
  nucleo.impostaSquadraDalServer(idGiocatore(player), team);
462
469
  },
463
470
  end(result, options) {
464
- nucleo.richiediFine(result, options?.rematch === true);
471
+ nucleo.richiediFine(result, options?.rematch ?? false);
465
472
  },
466
473
  save(key, value) {
467
474
  return nucleo.salva(key, value);
@@ -491,7 +498,11 @@ var NucleoStanza = class _NucleoStanza {
491
498
  },
492
499
  board: {
493
500
  submit(player, board, score, options = {}) {
494
- nucleo.accodaPunteggio(idGiocatore(player), board, score, options.daily === true);
501
+ if (typeof board === "number") {
502
+ const active = nucleo.richiediDati().giocatori.filter((p) => p.role !== "spectator");
503
+ if (nucleo.configurazione.players.max !== 1 || active.length !== 1) throw erroreConCodice("board_player_required", "Specify the player when submitting a multiplayer score.");
504
+ nucleo.accodaPunteggio(active[0].id, player, board, typeof score === "object" ? score : {});
505
+ } else nucleo.accodaPunteggio(idGiocatore(player), board, score, options);
495
506
  }
496
507
  },
497
508
  daily,
@@ -522,7 +533,8 @@ var NucleoStanza = class _NucleoStanza {
522
533
  if (salvato !== void 0) {
523
534
  nucleo.dati = salvato;
524
535
  nucleo.tickRateSincronizzato = salvato.tickRate;
525
- const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
536
+ const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0;
537
+ salvato.daily ??= nucleo.contestoGiornaliero();
526
538
  salvato.ultimoInputAt ??= adattatore.ora();
527
539
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
528
540
  nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
@@ -554,6 +566,7 @@ var NucleoStanza = class _NucleoStanza {
554
566
  const ora = this.adattatore.ora();
555
567
  this.dati = {
556
568
  versione: 1,
569
+ daily: this.contestoGiornaliero(ora),
557
570
  id,
558
571
  mode,
559
572
  status: "lobby",
@@ -596,7 +609,8 @@ var NucleoStanza = class _NucleoStanza {
596
609
  return true;
597
610
  }
598
611
  get configurazione() {
599
- return risolviModalita(this.manifest, this.dati?.mode ?? null);
612
+ const mode = risolviModalita(this.manifest, this.dati?.mode ?? null);
613
+ return mode.players.max === 1 ? { ...mode, lobby: false } : mode;
600
614
  }
601
615
  info(playerId) {
602
616
  if (this.dati === null) return null;
@@ -919,7 +933,7 @@ var NucleoStanza = class _NucleoStanza {
919
933
  else await this.rimuoviGiocatore(player, "timeout");
920
934
  }
921
935
  if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
922
- const errore = this.erroreMinimi();
936
+ const errore = this.erroreMinimi(this.dati.countdownRivincita);
923
937
  if (errore !== null) {
924
938
  this.dati.status = "lobby";
925
939
  this.dati.countdownAt = null;
@@ -1087,13 +1101,13 @@ var NucleoStanza = class _NucleoStanza {
1087
1101
  if (player === void 0) throw erroreConCodice("player_not_found", "Player not found.");
1088
1102
  return player;
1089
1103
  }
1090
- erroreMinimi() {
1104
+ erroreMinimi(saltaPronti = false) {
1091
1105
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
1092
1106
  const attivi = connessi.filter((player) => player.role !== "spectator");
1093
1107
  if (attivi.length < this.configurazione.players.min) {
1094
1108
  return { code: "not_enough_players", message: "The room does not have enough players." };
1095
1109
  }
1096
- if (connessi.some((player) => !player.ready)) {
1110
+ if (!saltaPronti && connessi.some((player) => !player.ready)) {
1097
1111
  return { code: "players_not_ready", message: "Every connected player must be ready." };
1098
1112
  }
1099
1113
  for (const role of this.manifest.roles) {
@@ -1115,31 +1129,48 @@ var NucleoStanza = class _NucleoStanza {
1115
1129
  this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1116
1130
  return;
1117
1131
  }
1132
+ if (this.configurazione.players.max === 1) {
1133
+ await this.avviaRivincita();
1134
+ return;
1135
+ }
1118
1136
  if (player.role !== "spectator" && !player.ready) {
1119
1137
  player.ready = true;
1120
1138
  this.inviaGiocatori();
1121
- await this.persistiEProgramma();
1139
+ if (dati.rivincita?.autoStart && this.prontiRivincita()) await this.avviaRivincita();
1140
+ else await this.persistiEProgramma();
1122
1141
  return;
1123
1142
  }
1124
1143
  if (dati.hostId !== player.id) return;
1125
- const attivi = dati.giocatori.filter((item) => item.connected && item.role !== "spectator");
1126
- if (attivi.length < this.configurazione.players.min || attivi.some((item) => !item.ready)) {
1144
+ if (!this.prontiRivincita(dati.rivincita?.autoStart === true)) {
1127
1145
  this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1128
1146
  return;
1129
1147
  }
1130
- dati.status = this.configurazione.lobby ? "lobby" : "playing";
1148
+ await this.avviaRivincita();
1149
+ }
1150
+ prontiRivincita(anticipata = false) {
1151
+ const attivi = this.richiediDati().giocatori.filter((item) => item.connected && item.role !== "spectator");
1152
+ return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && (anticipata || attivi.every((item) => item.ready));
1153
+ }
1154
+ async avviaRivincita() {
1155
+ const dati = this.richiediDati(), solo = this.configurazione.players.max === 1;
1156
+ const keepSetup = dati.rivincita?.keepSetup === true && !solo;
1157
+ dati.status = solo ? "playing" : keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
1158
+ dati.countdownRivincita = keepSetup;
1159
+ dati.countdownAt = keepSetup ? this.adattatore.ora() + COUNTDOWN_MS : null;
1131
1160
  dati.rivincitaFinoA = null;
1161
+ dati.rivincita = null;
1132
1162
  dati.result = null;
1133
1163
  dati.resultAt = null;
1134
1164
  dati.ultimoInputAt = this.adattatore.ora();
1135
- for (const item of dati.giocatori) item.ready = false;
1165
+ for (const item of dati.giocatori) item.ready = keepSetup && (dati.prontiPrecedenti?.includes(item.id) ?? false);
1166
+ dati.prontiPrecedenti = [];
1136
1167
  await this.chiama(this.definizione.onRestart, this.room);
1137
1168
  await this.applicaAzioni();
1138
1169
  if (dati.status === "playing") {
1139
1170
  await this.chiama(this.definizione.onStart, this.room);
1140
1171
  }
1141
1172
  await this.concludiEvento();
1142
- if (dati.status === "lobby" || dati.status === "playing") {
1173
+ if (dati.status === "lobby" || dati.status === "playing" || dati.status === "countdown") {
1143
1174
  this.inviaSnapshotTutti();
1144
1175
  this.inviaGiocatori();
1145
1176
  this.inviaStatus(this.adattatore.ora());
@@ -1158,13 +1189,14 @@ var NucleoStanza = class _NucleoStanza {
1158
1189
  return;
1159
1190
  }
1160
1191
  dati.status = "countdown";
1192
+ dati.countdownRivincita = false;
1161
1193
  dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
1162
1194
  this.inviaStatus(dati.countdownAt);
1163
1195
  await this.persistiEProgramma();
1164
1196
  }
1165
1197
  verificaCountdown() {
1166
1198
  const dati = this.richiediDati();
1167
- if (dati.status !== "countdown" || this.erroreMinimi() === null) return;
1199
+ if (dati.status !== "countdown" || this.erroreMinimi(dati.countdownRivincita) === null) return;
1168
1200
  dati.status = "lobby";
1169
1201
  dati.countdownAt = null;
1170
1202
  this.inviaStatus(this.adattatore.ora());
@@ -1233,7 +1265,11 @@ var NucleoStanza = class _NucleoStanza {
1233
1265
  giornata(ora = this.adattatore.ora()) {
1234
1266
  return this.adattatore.giorno?.(ora) ?? giornoUtc2(ora);
1235
1267
  }
1236
- accodaPunteggio(playerId, board, score, daily) {
1268
+ contestoGiornaliero(ora = this.adattatore.ora()) {
1269
+ const day = this.giornata(ora);
1270
+ return { day, seed: seedGiornata(this.manifest.id, day), expiresAt: prossimaMezzanotteUtc(ora) };
1271
+ }
1272
+ accodaPunteggio(playerId, board, score, options) {
1237
1273
  if (!this.richiediDati().giocatori.some((player2) => player2.id === playerId)) {
1238
1274
  throw new Error("Player not found.");
1239
1275
  }
@@ -1244,7 +1280,19 @@ var NucleoStanza = class _NucleoStanza {
1244
1280
  throw new TypeError("Score must be a non-negative safe integer.");
1245
1281
  }
1246
1282
  const submittedAt = this.adattatore.ora();
1247
- const day = daily ? this.giornata(submittedAt) : null;
1283
+ const daily = options.daily === true || options.day !== void 0;
1284
+ let day = daily ? this.giornata(submittedAt) : null;
1285
+ const start = this.manifest.boards?.[board]?.day === "start";
1286
+ if (options.day !== void 0 && (!start || options.daily === false)) {
1287
+ throw erroreConCodice("board_day_policy", "An explicit day requires a start-day board and a daily score.");
1288
+ }
1289
+ if (daily && start) {
1290
+ const run = this.richiediDati().daily;
1291
+ if (options.day === void 0) throw erroreConCodice("board_day_required", "Submit the daily score with room.daily.day.");
1292
+ if (options.day !== run.day) throw erroreConCodice("board_day_mismatch", "The score day must match room.daily.day.");
1293
+ if (submittedAt > run.expiresAt + GRAZIA_GIORNALIERA_MS) throw erroreConCodice("board_day_expired", "The starting day grace period has expired.");
1294
+ day = run.day;
1295
+ }
1248
1296
  this.richiediDati().punteggi.push({
1249
1297
  playerId,
1250
1298
  board,
@@ -1432,6 +1480,7 @@ var NucleoStanza = class _NucleoStanza {
1432
1480
  seed: seedStanza(dati.id),
1433
1481
  status: dati.status,
1434
1482
  result: dati.result,
1483
+ rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1435
1484
  mode: dati.mode,
1436
1485
  tick: dati.tick,
1437
1486
  tickRate: dati.tickRate,
@@ -1453,6 +1502,7 @@ var NucleoStanza = class _NucleoStanza {
1453
1502
  const dati = this.richiediDati();
1454
1503
  this.broadcast({
1455
1504
  t: "status",
1505
+ rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1456
1506
  status: dati.status,
1457
1507
  host: dati.hostId,
1458
1508
  countdownAt: dati.countdownAt,
@@ -1525,6 +1575,10 @@ var NucleoStanza = class _NucleoStanza {
1525
1575
  async concludiEvento() {
1526
1576
  await this.applicaAzioni();
1527
1577
  if (this.dati === null || this.dati.status === "ended") return;
1578
+ if (this.dati.status === "finished" && this.dati.rivincita?.autoStart && this.prontiRivincita()) {
1579
+ await this.avviaRivincita();
1580
+ return;
1581
+ }
1528
1582
  this.inviaGuadagniCambiati();
1529
1583
  const stato = await this.verificaStato();
1530
1584
  if (stato === null || this.stanzaTerminata()) return;
@@ -1620,6 +1674,11 @@ var NucleoStanza = class _NucleoStanza {
1620
1674
  if (dati.status === "ended") return;
1621
1675
  const giaFinita = dati.status === "finished";
1622
1676
  dati.status = rematch ? "finished" : "ended";
1677
+ dati.rivincita = rematch ? {
1678
+ keepSetup: typeof rematch === "object" && rematch.keepSetup === true,
1679
+ autoStart: typeof rematch === "object" && rematch.autoStart === true
1680
+ } : null;
1681
+ dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
1623
1682
  dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1624
1683
  dati.timer = [];
1625
1684
  if (rematch) for (const player of dati.giocatori) player.ready = false;