@caisual/kit 0.8.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/node.js CHANGED
@@ -1,9 +1,3 @@
1
- // src/node/index.ts
2
- import { randomUUID } from "node:crypto";
3
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
- import { dirname } from "node:path";
5
- import { performance } from "node:perf_hooks";
6
-
7
1
  // ../contracts/src/slug.ts
8
2
  var NOMI_RISERVATI = [
9
3
  "www",
@@ -51,6 +45,68 @@ function modalitaLocale(manifest, mode) {
51
45
  var MASSIMO_SPETTATORI = 100;
52
46
  var RITARDO_SPETTATORI_MS = 3e3;
53
47
 
48
+ // ../contracts/src/overlay.ts
49
+ function validBoardDay(value) {
50
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
51
+ const at = Date.parse(`${value}T00:00:00Z`);
52
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
53
+ }
54
+
55
+ // ../contracts/src/room-limits.ts
56
+ var MESSAGGI_GIOCO_AL_SECONDO = 20;
57
+ var MESSAGGI_SERVIZIO_AL_SECONDO = 20;
58
+ var LimiteMessaggiStanza = class {
59
+ connessioni = /* @__PURE__ */ new Map();
60
+ delete(connessione) {
61
+ this.connessioni.delete(connessione);
62
+ }
63
+ clear() {
64
+ this.connessioni.clear();
65
+ }
66
+ controlla(connessione, gioco, ora) {
67
+ let stato = this.connessioni.get(connessione);
68
+ if (stato === void 0) {
69
+ const budget2 = () => ({ accettati: [], finestra: ora, tentativi: 0, finestreAbusive: 0 });
70
+ stato = { gioco: budget2(), servizio: budget2(), ultimoErrore: -Infinity };
71
+ this.connessioni.set(connessione, stato);
72
+ }
73
+ const budget = gioco ? stato.gioco : stato.servizio;
74
+ const limite = gioco ? MESSAGGI_GIOCO_AL_SECONDO : MESSAGGI_SERVIZIO_AL_SECONDO;
75
+ if (ora - budget.finestra >= 1e3) {
76
+ budget.finestreAbusive = ora - budget.finestra < 2e3 && budget.tentativi > limite * 5 ? budget.finestreAbusive + 1 : 0;
77
+ budget.finestra += Math.floor((ora - budget.finestra) / 1e3) * 1e3;
78
+ budget.tentativi = 0;
79
+ }
80
+ budget.tentativi = Math.min(budget.tentativi + 1, limite * 5 + 1);
81
+ budget.accettati = budget.accettati.filter((at) => ora - at < 1e3);
82
+ if (budget.accettati.length < limite) {
83
+ budget.accettati.push(ora);
84
+ return { accetta: true, avvisa: false, chiudi: false };
85
+ }
86
+ const avvisa = ora - stato.ultimoErrore >= 1e3;
87
+ if (avvisa) stato.ultimoErrore = ora;
88
+ return {
89
+ accetta: false,
90
+ avvisa,
91
+ chiudi: budget.finestreAbusive >= 2 && budget.tentativi > limite * 5
92
+ };
93
+ }
94
+ };
95
+
96
+ // src/daily.ts
97
+ function prossimaMezzanotteUtc(ora) {
98
+ return (Math.floor(ora / 864e5) + 1) * 864e5;
99
+ }
100
+ function giornoUtc(ora) {
101
+ return new Date(ora).toISOString().slice(0, 10);
102
+ }
103
+
104
+ // src/node/index.ts
105
+ import { randomUUID } from "node:crypto";
106
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
107
+ import { dirname } from "node:path";
108
+ import { performance } from "node:perf_hooks";
109
+
54
110
  // src/stanza/json.ts
55
111
  function isPlainObject(value) {
56
112
  const prototype = Object.getPrototypeOf(value);
@@ -133,7 +189,7 @@ function creaDiff(prima, dopo) {
133
189
  visitaDiff(prima, dopo, [], patch);
134
190
  return patch;
135
191
  }
136
- function giornoUtc(ora) {
192
+ function giornoUtc2(ora) {
137
193
  return new Date(ora).toISOString().slice(0, 10);
138
194
  }
139
195
  var COSTANTI_SHA256 = [
@@ -286,7 +342,9 @@ var LIMITE_DEPOSITO = 64 * 1024;
286
342
  var LIMITE_OPERAZIONI_DEPOSITO = 120;
287
343
  var GRAZIA_MS = 6e4;
288
344
  var STANZA_VUOTA_MS = 5 * 6e4;
345
+ var ATTESA_RIVINCITA_MS = 2 * 6e4;
289
346
  var COUNTDOWN_MS = 3e3;
347
+ var GRAZIA_GIORNALIERA_MS = 10 * 6e4;
290
348
  var RIPOSO_TICK_MS = 3e4;
291
349
  var INATTIVITA_MS = 10 * 6e4;
292
350
  var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
@@ -337,21 +395,25 @@ var NucleoStanza = class _NucleoStanza {
337
395
  this.manifest = manifest;
338
396
  this.adattatore = adattatore;
339
397
  this.dati = null;
340
- this.frequenza = /* @__PURE__ */ new Map();
398
+ this.frequenza = new LimiteMessaggiStanza();
341
399
  this.frequenzaDeposito = [];
342
400
  this.kickRichiesti = /* @__PURE__ */ new Set();
343
401
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
344
402
  this.fineRichiesta = null;
345
403
  this.applicandoAzioni = false;
346
404
  this.ultimoStatoOsservato = "";
405
+ this.tickRateSincronizzato = null;
347
406
  this.voceDaPersistire = false;
348
407
  const nucleo = this;
349
408
  const daily = {
350
409
  get day() {
351
- return giornoUtc(nucleo.adattatore.ora());
410
+ return nucleo.richiediDati().daily.day;
352
411
  },
353
412
  get seed() {
354
- return seedGiornata(nucleo.manifest.id, giornoUtc(nucleo.adattatore.ora()));
413
+ return nucleo.richiediDati().daily.seed;
414
+ },
415
+ get expiresAt() {
416
+ return nucleo.richiediDati().daily.expiresAt;
355
417
  }
356
418
  };
357
419
  this.room = {
@@ -405,8 +467,8 @@ var NucleoStanza = class _NucleoStanza {
405
467
  setTeam(player, team) {
406
468
  nucleo.impostaSquadraDalServer(idGiocatore(player), team);
407
469
  },
408
- end(result) {
409
- nucleo.richiediFine(result);
470
+ end(result, options) {
471
+ nucleo.richiediFine(result, options?.rematch ?? false);
410
472
  },
411
473
  save(key, value) {
412
474
  return nucleo.salva(key, value);
@@ -436,7 +498,11 @@ var NucleoStanza = class _NucleoStanza {
436
498
  },
437
499
  board: {
438
500
  submit(player, board, score, options = {}) {
439
- 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);
440
506
  }
441
507
  },
442
508
  daily,
@@ -466,7 +532,9 @@ var NucleoStanza = class _NucleoStanza {
466
532
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
467
533
  if (salvato !== void 0) {
468
534
  nucleo.dati = salvato;
469
- const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
535
+ nucleo.tickRateSincronizzato = salvato.tickRate;
536
+ const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0;
537
+ salvato.daily ??= nucleo.contestoGiornaliero();
470
538
  salvato.ultimoInputAt ??= adattatore.ora();
471
539
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
472
540
  nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
@@ -498,6 +566,7 @@ var NucleoStanza = class _NucleoStanza {
498
566
  const ora = this.adattatore.ora();
499
567
  this.dati = {
500
568
  versione: 1,
569
+ daily: this.contestoGiornaliero(ora),
501
570
  id,
502
571
  mode,
503
572
  status: "lobby",
@@ -540,7 +609,8 @@ var NucleoStanza = class _NucleoStanza {
540
609
  return true;
541
610
  }
542
611
  get configurazione() {
543
- 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;
544
614
  }
545
615
  info(playerId) {
546
616
  if (this.dati === null) return null;
@@ -593,7 +663,7 @@ var NucleoStanza = class _NucleoStanza {
593
663
  if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
594
664
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
595
665
  if (esistente !== void 0) return { ok: true };
596
- if (this.configurazione.lobby && this.dati.status !== "lobby") {
666
+ if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
597
667
  return { ok: false, code: "room_playing" };
598
668
  }
599
669
  if (this.dati.giocatori.length >= this.configurazione.players.max) {
@@ -612,6 +682,7 @@ var NucleoStanza = class _NucleoStanza {
612
682
  const ora = this.adattatore.ora();
613
683
  let player = dati.giocatori.find((item) => item.id === identity.id);
614
684
  const nuovo = player === void 0;
685
+ const riconnesso = player !== void 0 && !player.connected;
615
686
  if (player === void 0) {
616
687
  player = {
617
688
  ...identity,
@@ -627,6 +698,7 @@ var NucleoStanza = class _NucleoStanza {
627
698
  dati.giocatori.push(player);
628
699
  } else {
629
700
  if (player.connected && player.connessione !== null && player.connessione !== connessione) {
701
+ this.frequenza.delete(player.connessione);
630
702
  this.adattatore.chiudi(player.connessione, 4006, "replaced");
631
703
  }
632
704
  player.name = identity.name;
@@ -648,6 +720,9 @@ var NucleoStanza = class _NucleoStanza {
648
720
  copiaGiocatore(player)
649
721
  );
650
722
  }
723
+ if (riconnesso) {
724
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), true);
725
+ }
651
726
  if (primaConnessione) {
652
727
  await this.chiama(this.definizione.onStart, this.room);
653
728
  this.inviaStatus(ora);
@@ -670,14 +745,16 @@ var NucleoStanza = class _NucleoStanza {
670
745
  player.connected = false;
671
746
  player.connessione = null;
672
747
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
673
- if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
748
+ if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
674
749
  this.frequenza.delete(connessione);
675
750
  if (this.dati.hostId === player.id) this.assegnaHost();
676
751
  this.verificaCountdown();
752
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
753
+ await this.concludiEvento();
677
754
  this.inviaGiocatori();
678
755
  await this.persistiEProgramma();
679
756
  }
680
- async ricevi(connessione, frame) {
757
+ async ricevi(connessione, frame, limiteVerificato = false) {
681
758
  if (this.dati === null || this.dati.status === "ended") return;
682
759
  if (await this.terminaSeInattiva()) return;
683
760
  const player = this.dati.giocatori.find(
@@ -685,17 +762,10 @@ var NucleoStanza = class _NucleoStanza {
685
762
  );
686
763
  if (player === void 0) return;
687
764
  if (new TextEncoder().encode(frame).byteLength > LIMITE_FRAME) {
688
- await this.chiudiConnessione(player, 4009, "bad_message");
765
+ await this.chiudiConnessione(player, 4009, "message_too_large");
689
766
  return;
690
767
  }
691
768
  const ora = this.adattatore.ora();
692
- const recenti = (this.frequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
693
- if (recenti.length >= 20) {
694
- await this.chiudiConnessione(player, 4008, "rate_limited");
695
- return;
696
- }
697
- recenti.push(ora);
698
- this.frequenza.set(connessione, recenti);
699
769
  let message = null;
700
770
  try {
701
771
  message = record(JSON.parse(frame));
@@ -705,6 +775,14 @@ var NucleoStanza = class _NucleoStanza {
705
775
  await this.chiudiConnessione(player, 4009, "bad_message");
706
776
  return;
707
777
  }
778
+ if (!limiteVerificato) {
779
+ const limite = this.frequenza.controlla(connessione, message.t === "msg", ora);
780
+ if (!limite.accetta) {
781
+ if (limite.avvisa) this.inviaErrore(player, "rate_limited", "Too many room messages. Excess messages are dropped.");
782
+ if (limite.chiudi) await this.chiudiConnessione(player, 4008, "rate_limited");
783
+ return;
784
+ }
785
+ }
708
786
  if (message.t === "ping") {
709
787
  if (typeof message.c !== "number" || !Number.isFinite(message.c)) {
710
788
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -727,6 +805,10 @@ var NucleoStanza = class _NucleoStanza {
727
805
  await this.persistiEProgramma();
728
806
  return;
729
807
  }
808
+ if (message.t === "restart") {
809
+ await this.rivincita(player);
810
+ return;
811
+ }
730
812
  if (message.t === "ready") {
731
813
  if (typeof message.ready !== "boolean") return this.messaggioErrato(player);
732
814
  if (!this.inLobby(player)) return;
@@ -798,6 +880,7 @@ var NucleoStanza = class _NucleoStanza {
798
880
  await this.persistiEProgramma();
799
881
  return;
800
882
  }
883
+ if (this.dati.status === "finished") return;
801
884
  this.dati.ultimoInputAt = ora;
802
885
  await this.chiama(
803
886
  this.definizione.onMessage,
@@ -850,7 +933,7 @@ var NucleoStanza = class _NucleoStanza {
850
933
  else await this.rimuoviGiocatore(player, "timeout");
851
934
  }
852
935
  if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
853
- const errore = this.erroreMinimi();
936
+ const errore = this.erroreMinimi(this.dati.countdownRivincita);
854
937
  if (errore !== null) {
855
938
  this.dati.status = "lobby";
856
939
  this.dati.countdownAt = null;
@@ -868,7 +951,11 @@ var NucleoStanza = class _NucleoStanza {
868
951
  if (dovuti.length > 0) {
869
952
  const ids = new Set(dovuti.map((timer) => timer.id));
870
953
  this.dati.timer = this.dati.timer.filter((timer) => !ids.has(timer.id));
871
- for (const timer of dovuti) await this.eseguiTimer(timer);
954
+ for (const timer of dovuti) {
955
+ await this.eseguiTimer(timer);
956
+ await this.applicaAzioni();
957
+ if (this.dati.status === "finished" || this.stanzaTerminata()) break;
958
+ }
872
959
  }
873
960
  await this.concludiEvento();
874
961
  if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
@@ -899,22 +986,30 @@ var NucleoStanza = class _NucleoStanza {
899
986
  return esito;
900
987
  }
901
988
  async riconciliaConnessioni() {
989
+ if (this.dati === null || this.dati.status === "ended") return;
902
990
  const dati = this.richiediDati();
903
991
  const attive = new Set(this.adattatore.connessioniAttive());
904
992
  const ora = this.adattatore.ora();
905
- let cambiato = false;
993
+ const disconnessi = [];
906
994
  for (const player of dati.giocatori) {
907
995
  if (player.connected && (player.connessione === null || !attive.has(player.connessione))) {
908
996
  player.connected = false;
997
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
909
998
  player.connessione = null;
910
999
  player.graziaFinoA = ora + GRAZIA_MS;
911
- if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
912
- cambiato = true;
1000
+ if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
1001
+ disconnessi.push(player);
913
1002
  }
914
1003
  }
915
- if (cambiato) {
1004
+ if (disconnessi.length > 0) {
916
1005
  this.assegnaHost();
917
- await this.persisti();
1006
+ this.verificaCountdown();
1007
+ for (const player of disconnessi) {
1008
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
1009
+ }
1010
+ await this.concludiEvento();
1011
+ this.inviaGiocatori();
1012
+ await this.persistiEProgramma();
918
1013
  }
919
1014
  }
920
1015
  ruoloAutomatico() {
@@ -1006,13 +1101,13 @@ var NucleoStanza = class _NucleoStanza {
1006
1101
  if (player === void 0) throw erroreConCodice("player_not_found", "Player not found.");
1007
1102
  return player;
1008
1103
  }
1009
- erroreMinimi() {
1104
+ erroreMinimi(saltaPronti = false) {
1010
1105
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
1011
1106
  const attivi = connessi.filter((player) => player.role !== "spectator");
1012
1107
  if (attivi.length < this.configurazione.players.min) {
1013
1108
  return { code: "not_enough_players", message: "The room does not have enough players." };
1014
1109
  }
1015
- if (connessi.some((player) => !player.ready)) {
1110
+ if (!saltaPronti && connessi.some((player) => !player.ready)) {
1016
1111
  return { code: "players_not_ready", message: "Every connected player must be ready." };
1017
1112
  }
1018
1113
  for (const role of this.manifest.roles) {
@@ -1028,6 +1123,60 @@ var NucleoStanza = class _NucleoStanza {
1028
1123
  }
1029
1124
  return null;
1030
1125
  }
1126
+ async rivincita(player) {
1127
+ const dati = this.richiediDati();
1128
+ if (dati.status !== "finished") {
1129
+ this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1130
+ return;
1131
+ }
1132
+ if (this.configurazione.players.max === 1) {
1133
+ await this.avviaRivincita();
1134
+ return;
1135
+ }
1136
+ if (player.role !== "spectator" && !player.ready) {
1137
+ player.ready = true;
1138
+ this.inviaGiocatori();
1139
+ if (dati.rivincita?.autoStart && this.prontiRivincita()) await this.avviaRivincita();
1140
+ else await this.persistiEProgramma();
1141
+ return;
1142
+ }
1143
+ if (dati.hostId !== player.id) return;
1144
+ if (!this.prontiRivincita(dati.rivincita?.autoStart === true)) {
1145
+ this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1146
+ return;
1147
+ }
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;
1160
+ dati.rivincitaFinoA = null;
1161
+ dati.rivincita = null;
1162
+ dati.result = null;
1163
+ dati.resultAt = null;
1164
+ dati.ultimoInputAt = this.adattatore.ora();
1165
+ for (const item of dati.giocatori) item.ready = keepSetup && (dati.prontiPrecedenti?.includes(item.id) ?? false);
1166
+ dati.prontiPrecedenti = [];
1167
+ await this.chiama(this.definizione.onRestart, this.room);
1168
+ await this.applicaAzioni();
1169
+ if (dati.status === "playing") {
1170
+ await this.chiama(this.definizione.onStart, this.room);
1171
+ }
1172
+ await this.concludiEvento();
1173
+ if (dati.status === "lobby" || dati.status === "playing" || dati.status === "countdown") {
1174
+ this.inviaSnapshotTutti();
1175
+ this.inviaGiocatori();
1176
+ this.inviaStatus(this.adattatore.ora());
1177
+ }
1178
+ await this.persistiEProgramma();
1179
+ }
1031
1180
  async avviaCountdown(player) {
1032
1181
  const dati = this.richiediDati();
1033
1182
  if (dati.hostId !== player.id) {
@@ -1040,13 +1189,14 @@ var NucleoStanza = class _NucleoStanza {
1040
1189
  return;
1041
1190
  }
1042
1191
  dati.status = "countdown";
1192
+ dati.countdownRivincita = false;
1043
1193
  dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
1044
1194
  this.inviaStatus(dati.countdownAt);
1045
1195
  await this.persistiEProgramma();
1046
1196
  }
1047
1197
  verificaCountdown() {
1048
1198
  const dati = this.richiediDati();
1049
- if (dati.status !== "countdown" || this.erroreMinimi() === null) return;
1199
+ if (dati.status !== "countdown" || this.erroreMinimi(dati.countdownRivincita) === null) return;
1050
1200
  dati.status = "lobby";
1051
1201
  dati.countdownAt = null;
1052
1202
  this.inviaStatus(this.adattatore.ora());
@@ -1064,6 +1214,7 @@ var NucleoStanza = class _NucleoStanza {
1064
1214
  const indice = dati.giocatori.findIndex((item) => item.id === player.id);
1065
1215
  if (indice < 0) return;
1066
1216
  dati.giocatori.splice(indice, 1);
1217
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
1067
1218
  this.rivediVoce();
1068
1219
  this.pulisciGuadagni(player.id);
1069
1220
  if (dati.hostId === player.id) this.assegnaHost();
@@ -1103,6 +1254,7 @@ var NucleoStanza = class _NucleoStanza {
1103
1254
  const json = analizzaJson(payload);
1104
1255
  if (!json.ok) throw new TypeError("Schedule payload must be valid JSON.");
1105
1256
  const dati = this.richiediDati();
1257
+ if (dati.status === "finished" || dati.status === "ended") return;
1106
1258
  dati.timer.push({
1107
1259
  id: dati.prossimoTimerId++,
1108
1260
  at: this.adattatore.ora() + milliseconds,
@@ -1110,7 +1262,14 @@ var NucleoStanza = class _NucleoStanza {
1110
1262
  payload: json.valore
1111
1263
  });
1112
1264
  }
1113
- accodaPunteggio(playerId, board, score, daily) {
1265
+ giornata(ora = this.adattatore.ora()) {
1266
+ return this.adattatore.giorno?.(ora) ?? giornoUtc2(ora);
1267
+ }
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) {
1114
1273
  if (!this.richiediDati().giocatori.some((player2) => player2.id === playerId)) {
1115
1274
  throw new Error("Player not found.");
1116
1275
  }
@@ -1121,25 +1280,39 @@ var NucleoStanza = class _NucleoStanza {
1121
1280
  throw new TypeError("Score must be a non-negative safe integer.");
1122
1281
  }
1123
1282
  const submittedAt = this.adattatore.ora();
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
+ }
1124
1296
  this.richiediDati().punteggi.push({
1125
1297
  playerId,
1126
1298
  board,
1127
1299
  score,
1128
1300
  daily,
1129
1301
  submittedAt,
1130
- day: daily ? giornoUtc(submittedAt) : null
1302
+ day
1131
1303
  });
1132
1304
  const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
1133
1305
  if (player.connected && player.connessione !== null) this.adattatore.invia(player.connessione, {
1134
1306
  t: "score-queued",
1135
- score: { player: playerId, board, score, day: daily ? giornoUtc(submittedAt) : null, submittedAt }
1307
+ score: { player: playerId, board, score, day, submittedAt }
1136
1308
  });
1137
1309
  this.broadcast({ t: "flush" });
1138
1310
  }
1139
- richiediFine(result) {
1311
+ richiediFine(result, rematch = false) {
1140
1312
  const json = analizzaJson(result);
1141
1313
  if (!json.ok) throw new TypeError("Game result must be valid JSON.");
1142
- this.fineRichiesta = json.valore;
1314
+ if (this.dati?.status === "ended" || this.dati?.status === "finished" && rematch) return;
1315
+ this.fineRichiesta = { result: json.valore, rematch };
1143
1316
  }
1144
1317
  async salva(key, value) {
1145
1318
  if (!CHIAVE.test(key)) {
@@ -1306,6 +1479,8 @@ var NucleoStanza = class _NucleoStanza {
1306
1479
  id: dati.id,
1307
1480
  seed: seedStanza(dati.id),
1308
1481
  status: dati.status,
1482
+ result: dati.result,
1483
+ rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1309
1484
  mode: dati.mode,
1310
1485
  tick: dati.tick,
1311
1486
  tickRate: dati.tickRate,
@@ -1327,20 +1502,23 @@ var NucleoStanza = class _NucleoStanza {
1327
1502
  const dati = this.richiediDati();
1328
1503
  this.broadcast({
1329
1504
  t: "status",
1505
+ rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1330
1506
  status: dati.status,
1331
1507
  host: dati.hostId,
1332
1508
  countdownAt: dati.countdownAt,
1333
1509
  at,
1334
- result: dati.status === "ended" ? dati.result : null
1510
+ result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
1335
1511
  });
1336
1512
  }
1337
1513
  inviaDiff() {
1338
1514
  const dati = this.richiediDati();
1339
1515
  const patch = creaDiff(dati.statoSincronizzato, dati.state);
1340
- if (patch.length === 0) return;
1516
+ if (patch.length === 0 && this.tickRateSincronizzato === dati.tickRate) return;
1517
+ this.tickRateSincronizzato = dati.tickRate;
1341
1518
  this.broadcast({
1342
1519
  t: "state",
1343
1520
  tick: dati.tick,
1521
+ tickRate: dati.tickRate,
1344
1522
  base: dati.tickSincronizzato,
1345
1523
  serverTime: this.adattatore.ora(),
1346
1524
  patch
@@ -1355,8 +1533,10 @@ var NucleoStanza = class _NucleoStanza {
1355
1533
  dati.state = stato.valore;
1356
1534
  dati.statoSincronizzato = copiaJson(stato.valore);
1357
1535
  dati.tickSincronizzato = dati.tick;
1536
+ this.tickRateSincronizzato = dati.tickRate;
1358
1537
  this.broadcast({
1359
1538
  t: "snapshot",
1539
+ tickRate: dati.tickRate,
1360
1540
  tick: dati.tick,
1361
1541
  serverTime: this.adattatore.ora(),
1362
1542
  state: stato.valore
@@ -1367,7 +1547,7 @@ var NucleoStanza = class _NucleoStanza {
1367
1547
  try {
1368
1548
  await callback(...args);
1369
1549
  } catch {
1370
- this.fineRichiesta = { error: "callback_error" };
1550
+ this.fineRichiesta = { result: { error: "callback_error" }, rematch: false };
1371
1551
  }
1372
1552
  }
1373
1553
  async applicaAzioni() {
@@ -1386,7 +1566,7 @@ var NucleoStanza = class _NucleoStanza {
1386
1566
  if (this.fineRichiesta !== null && this.dati.status !== "ended") {
1387
1567
  const result = this.fineRichiesta;
1388
1568
  this.fineRichiesta = null;
1389
- await this.terminaInterna(result);
1569
+ await this.terminaInterna(result.result, result.rematch);
1390
1570
  }
1391
1571
  } finally {
1392
1572
  this.applicandoAzioni = false;
@@ -1395,6 +1575,10 @@ var NucleoStanza = class _NucleoStanza {
1395
1575
  async concludiEvento() {
1396
1576
  await this.applicaAzioni();
1397
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
+ }
1398
1582
  this.inviaGuadagniCambiati();
1399
1583
  const stato = await this.verificaStato();
1400
1584
  if (stato === null || this.stanzaTerminata()) return;
@@ -1485,33 +1669,47 @@ var NucleoStanza = class _NucleoStanza {
1485
1669
  dati.state = dati.statoSincronizzato;
1486
1670
  await this.terminaInterna({ error: code });
1487
1671
  }
1488
- async terminaInterna(result) {
1672
+ async terminaInterna(result, rematch = false) {
1489
1673
  const dati = this.richiediDati();
1490
1674
  if (dati.status === "ended") return;
1491
- dati.status = "ended";
1675
+ const giaFinita = dati.status === "finished";
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) : [];
1682
+ dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1683
+ dati.timer = [];
1684
+ if (rematch) for (const player of dati.giocatori) player.ready = false;
1492
1685
  dati.countdownAt = null;
1493
1686
  dati.result = result;
1494
1687
  dati.resultAt = this.adattatore.ora();
1495
1688
  try {
1496
- await this.definizione.onEnd?.(this.room);
1689
+ if (!giaFinita) await this.definizione.onEnd?.(this.room);
1497
1690
  } catch {
1498
1691
  if (record(result)?.error === void 0) dati.result = { error: "callback_error" };
1692
+ dati.status = "ended";
1693
+ dati.rivincitaFinoA = null;
1499
1694
  }
1500
1695
  const stato = analizzaJson(dati.state);
1501
1696
  if (!stato.ok || stato.bytes > LIMITE_STATO) {
1502
1697
  dati.state = dati.statoSincronizzato;
1503
1698
  dati.result = { error: stato.ok ? "state_too_large" : "state_invalid" };
1699
+ dati.status = "ended";
1700
+ dati.rivincitaFinoA = null;
1504
1701
  } else if (stato.testo !== JSON.stringify(dati.statoSincronizzato)) {
1505
1702
  dati.tick++;
1506
1703
  dati.state = stato.valore;
1507
1704
  this.inviaDiff();
1508
1705
  }
1509
1706
  const fine = { result: dati.result, at: dati.resultAt };
1510
- dati.fineInCoda = fine;
1707
+ if (dati.status === "ended") dati.fineInCoda = fine;
1708
+ if (dati.status === "finished") this.inviaGiocatori();
1511
1709
  this.inviaStatus(dati.resultAt);
1512
1710
  this.broadcast({ t: "flush" });
1513
1711
  for (const player of dati.giocatori) {
1514
- if (player.connected && player.connessione !== null) {
1712
+ if (dati.status === "ended" && player.connected && player.connessione !== null) {
1515
1713
  this.adattatore.chiudi(player.connessione, 4004, "room_ended");
1516
1714
  player.connected = false;
1517
1715
  player.connessione = null;
@@ -1526,7 +1724,7 @@ var NucleoStanza = class _NucleoStanza {
1526
1724
  if (dati.durateCpu.length > 50) dati.durateCpu.shift();
1527
1725
  dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
1528
1726
  if (dati.cpuOltreCento >= 20) {
1529
- this.fineRichiesta = { error: "cpu_budget" };
1727
+ this.fineRichiesta = { result: { error: "cpu_budget" }, rematch: false };
1530
1728
  return;
1531
1729
  }
1532
1730
  if (dati.durateCpu.length === 50) {
@@ -1557,6 +1755,11 @@ var NucleoStanza = class _NucleoStanza {
1557
1755
  return dati !== null && dati.status === "playing" && dati.tickRate > 0 && dati.giocatori.some((player) => player.connected) && this.adattatore.ora() - Math.max(dati.ultimoInputAt, dati.ultimoCambioStatoAt) < RIPOSO_TICK_MS;
1558
1756
  }
1559
1757
  async terminaSeInattiva() {
1758
+ if (this.dati?.status === "finished") {
1759
+ if (this.adattatore.ora() < (this.dati.rivincitaFinoA ?? 0)) return false;
1760
+ await this.terminaInterna(this.dati.result);
1761
+ return true;
1762
+ }
1560
1763
  if (this.manifest.persistent === true) {
1561
1764
  if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
1562
1765
  await this.terminaInterna({ error: "expired" });
@@ -1576,6 +1779,7 @@ var NucleoStanza = class _NucleoStanza {
1576
1779
  this.serveTick() ? 1e3 / this.dati.tickRate : null
1577
1780
  );
1578
1781
  const prossime = [];
1782
+ if (this.dati.status === "finished") prossime.push(this.dati.rivincitaFinoA ?? this.adattatore.ora());
1579
1783
  if (this.manifest.persistent === true) {
1580
1784
  prossime.push(
1581
1785
  Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
@@ -1863,10 +2067,11 @@ var ArchivioNode = class _ArchivioNode {
1863
2067
  }
1864
2068
  };
1865
2069
  var AdattatoreNode = class {
1866
- constructor(storage, deposito, ritardoSpettatori) {
2070
+ constructor(storage, deposito, ritardoSpettatori, dailyDay) {
1867
2071
  this.storage = storage;
1868
2072
  this.deposito = deposito;
1869
2073
  this.ritardoSpettatori = ritardoSpettatori;
2074
+ this.dailyDay = dailyDay;
1870
2075
  this.connessioni = /* @__PURE__ */ new Map();
1871
2076
  this.spettatori = /* @__PURE__ */ new Map();
1872
2077
  this.timerSpettatori = /* @__PURE__ */ new Set();
@@ -1957,6 +2162,10 @@ var AdattatoreNode = class {
1957
2162
  ora() {
1958
2163
  return Date.now();
1959
2164
  }
2165
+ // La giornata di prova non deve spostare scadenze, timer o misure della connessione.
2166
+ giorno(ora) {
2167
+ return this.dailyDay ?? giornoUtc(ora);
2168
+ }
1960
2169
  misuraCpu() {
1961
2170
  return performance.now();
1962
2171
  }
@@ -2025,7 +2234,7 @@ var StanzaNode = class {
2025
2234
  this.voceListeners = /* @__PURE__ */ new Map();
2026
2235
  this.voceFrequenza = /* @__PURE__ */ new Map();
2027
2236
  this.voceUltimaRichiesta = /* @__PURE__ */ new Map();
2028
- this.frameFrequenza = /* @__PURE__ */ new Map();
2237
+ this.frameFrequenza = new LimiteMessaggiStanza();
2029
2238
  this.connessioniGiocatori = /* @__PURE__ */ new Map();
2030
2239
  this.giocatoriConnessioni = /* @__PURE__ */ new Map();
2031
2240
  adattatore.collega({
@@ -2126,15 +2335,6 @@ var StanzaNode = class {
2126
2335
  const player = this.nucleo.giocatoreConnesso(connessione);
2127
2336
  if (player === null) return;
2128
2337
  const ora = Date.now();
2129
- const frames = (this.frameFrequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
2130
- if (frames.length >= 20) {
2131
- this.adattatore.chiudi(connessione, 4008, "rate_limited");
2132
- this.rimuoviConnessione(connessione);
2133
- await this.nucleo.disconnetti(connessione);
2134
- return;
2135
- }
2136
- frames.push(ora);
2137
- this.frameFrequenza.set(connessione, frames);
2138
2338
  let value;
2139
2339
  try {
2140
2340
  value = JSON.parse(frame);
@@ -2143,17 +2343,31 @@ var StanzaNode = class {
2143
2343
  return;
2144
2344
  }
2145
2345
  const message = typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2146
- if (message?.t !== "voice") {
2147
- await this.nucleo.ricevi(connessione, frame);
2148
- this.riconciliaRoster();
2149
- return;
2150
- }
2151
- if (Buffer.byteLength(frame, "utf8") > 64 * 1024) {
2152
- this.adattatore.chiudi(connessione, 4009, "bad_message");
2346
+ if (Buffer.byteLength(frame, "utf8") > (message?.t === "voice" ? 64 : 16) * 1024) {
2347
+ this.adattatore.chiudi(connessione, 4009, "message_too_large");
2153
2348
  this.rimuoviConnessione(connessione);
2154
2349
  await this.nucleo.disconnetti(connessione);
2155
2350
  return;
2156
2351
  }
2352
+ const limite = this.frameFrequenza.controlla(connessione, message?.t === "msg", ora);
2353
+ if (!limite.accetta) {
2354
+ if (limite.avvisa) this.adattatore.invia(connessione, {
2355
+ t: "error",
2356
+ code: "rate_limited",
2357
+ message: "Too many room messages. Excess messages are dropped."
2358
+ });
2359
+ if (limite.chiudi) {
2360
+ this.adattatore.chiudi(connessione, 4008, "rate_limited");
2361
+ this.rimuoviConnessione(connessione);
2362
+ await this.nucleo.disconnetti(connessione);
2363
+ }
2364
+ return;
2365
+ }
2366
+ if (message?.t !== "voice") {
2367
+ await this.nucleo.ricevi(connessione, frame, true);
2368
+ this.riconciliaRoster();
2369
+ return;
2370
+ }
2157
2371
  await this.riceviVoce(connessione, player.id, player.role, message);
2158
2372
  }
2159
2373
  permessoSpettatore() {
@@ -2177,19 +2391,24 @@ var StanzaNode = class {
2177
2391
  }
2178
2392
  async riceviSpettatore(connessione, frame) {
2179
2393
  if (Buffer.byteLength(frame, "utf8") > 16 * 1024) {
2180
- this.adattatore.chiudiSpettatore(connessione, 4008, "rate_limited");
2394
+ this.adattatore.chiudiSpettatore(connessione, 4009, "message_too_large");
2181
2395
  this.frameFrequenza.delete(connessione);
2182
2396
  return;
2183
2397
  }
2184
2398
  const ora = Date.now();
2185
- const frames = (this.frameFrequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
2186
- if (frames.length >= 20) {
2187
- this.adattatore.chiudiSpettatore(connessione, 4008, "rate_limited");
2188
- this.frameFrequenza.delete(connessione);
2399
+ const limite = this.frameFrequenza.controlla(connessione, false, ora);
2400
+ if (!limite.accetta) {
2401
+ if (limite.avvisa) this.adattatore.inviaSpettatoreSubito(connessione, JSON.stringify({
2402
+ t: "error",
2403
+ code: "rate_limited",
2404
+ message: "Too many room messages. Excess messages are dropped."
2405
+ }));
2406
+ if (limite.chiudi) {
2407
+ this.adattatore.chiudiSpettatore(connessione, 4008, "rate_limited");
2408
+ this.frameFrequenza.delete(connessione);
2409
+ }
2189
2410
  return;
2190
2411
  }
2191
- frames.push(ora);
2192
- this.frameFrequenza.set(connessione, frames);
2193
2412
  let message = null;
2194
2413
  try {
2195
2414
  const value = JSON.parse(frame);
@@ -2418,9 +2637,10 @@ var StanzaNode = class {
2418
2637
  }
2419
2638
  };
2420
2639
  async function createNodeRoom(definition, manifest, options = {}) {
2640
+ if (options.dailyDay !== void 0 && !validBoardDay(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
2421
2641
  const storage = await ArchivioNode.apri(options.storageFile ?? null);
2422
2642
  const ritardoSpettatori = manifest.spectators === null ? null : manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS;
2423
- const adattatore = new AdattatoreNode(storage, options.deposito ?? null, ritardoSpettatori);
2643
+ const adattatore = new AdattatoreNode(storage, options.deposito ?? null, ritardoSpettatori, options.dailyDay);
2424
2644
  const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
2425
2645
  return new StanzaNode(nucleo, adattatore, manifest);
2426
2646
  }