@caisual/kit 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.js CHANGED
@@ -43,6 +43,47 @@ function modalitaLocale(manifest, mode) {
43
43
  return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
44
44
  }
45
45
 
46
+ // ../contracts/src/room-limits.ts
47
+ var MESSAGGI_GIOCO_AL_SECONDO = 20;
48
+ var MESSAGGI_SERVIZIO_AL_SECONDO = 20;
49
+ var LimiteMessaggiStanza = class {
50
+ connessioni = /* @__PURE__ */ new Map();
51
+ delete(connessione) {
52
+ this.connessioni.delete(connessione);
53
+ }
54
+ clear() {
55
+ this.connessioni.clear();
56
+ }
57
+ controlla(connessione, gioco, ora) {
58
+ let stato = this.connessioni.get(connessione);
59
+ if (stato === void 0) {
60
+ const budget2 = () => ({ accettati: [], finestra: ora, tentativi: 0, finestreAbusive: 0 });
61
+ stato = { gioco: budget2(), servizio: budget2(), ultimoErrore: -Infinity };
62
+ this.connessioni.set(connessione, stato);
63
+ }
64
+ const budget = gioco ? stato.gioco : stato.servizio;
65
+ const limite = gioco ? MESSAGGI_GIOCO_AL_SECONDO : MESSAGGI_SERVIZIO_AL_SECONDO;
66
+ if (ora - budget.finestra >= 1e3) {
67
+ budget.finestreAbusive = ora - budget.finestra < 2e3 && budget.tentativi > limite * 5 ? budget.finestreAbusive + 1 : 0;
68
+ budget.finestra += Math.floor((ora - budget.finestra) / 1e3) * 1e3;
69
+ budget.tentativi = 0;
70
+ }
71
+ budget.tentativi = Math.min(budget.tentativi + 1, limite * 5 + 1);
72
+ budget.accettati = budget.accettati.filter((at) => ora - at < 1e3);
73
+ if (budget.accettati.length < limite) {
74
+ budget.accettati.push(ora);
75
+ return { accetta: true, avvisa: false, chiudi: false };
76
+ }
77
+ const avvisa = ora - stato.ultimoErrore >= 1e3;
78
+ if (avvisa) stato.ultimoErrore = ora;
79
+ return {
80
+ accetta: false,
81
+ avvisa,
82
+ chiudi: budget.finestreAbusive >= 2 && budget.tentativi > limite * 5
83
+ };
84
+ }
85
+ };
86
+
46
87
  // src/stanza/json.ts
47
88
  function isPlainObject(value) {
48
89
  const prototype = Object.getPrototypeOf(value);
@@ -278,6 +319,7 @@ var LIMITE_DEPOSITO = 64 * 1024;
278
319
  var LIMITE_OPERAZIONI_DEPOSITO = 120;
279
320
  var GRAZIA_MS = 6e4;
280
321
  var STANZA_VUOTA_MS = 5 * 6e4;
322
+ var ATTESA_RIVINCITA_MS = 2 * 6e4;
281
323
  var COUNTDOWN_MS = 3e3;
282
324
  var RIPOSO_TICK_MS = 3e4;
283
325
  var INATTIVITA_MS = 10 * 6e4;
@@ -329,21 +371,22 @@ var NucleoStanza = class _NucleoStanza {
329
371
  this.manifest = manifest;
330
372
  this.adattatore = adattatore;
331
373
  this.dati = null;
332
- this.frequenza = /* @__PURE__ */ new Map();
374
+ this.frequenza = new LimiteMessaggiStanza();
333
375
  this.frequenzaDeposito = [];
334
376
  this.kickRichiesti = /* @__PURE__ */ new Set();
335
377
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
336
378
  this.fineRichiesta = null;
337
379
  this.applicandoAzioni = false;
338
380
  this.ultimoStatoOsservato = "";
381
+ this.tickRateSincronizzato = null;
339
382
  this.voceDaPersistire = false;
340
383
  const nucleo = this;
341
384
  const daily = {
342
385
  get day() {
343
- return giornoUtc(nucleo.adattatore.ora());
386
+ return nucleo.giornata();
344
387
  },
345
388
  get seed() {
346
- return seedGiornata(nucleo.manifest.id, giornoUtc(nucleo.adattatore.ora()));
389
+ return seedGiornata(nucleo.manifest.id, nucleo.giornata());
347
390
  }
348
391
  };
349
392
  this.room = {
@@ -397,8 +440,8 @@ var NucleoStanza = class _NucleoStanza {
397
440
  setTeam(player, team) {
398
441
  nucleo.impostaSquadraDalServer(idGiocatore(player), team);
399
442
  },
400
- end(result) {
401
- nucleo.richiediFine(result);
443
+ end(result, options) {
444
+ nucleo.richiediFine(result, options?.rematch === true);
402
445
  },
403
446
  save(key, value) {
404
447
  return nucleo.salva(key, value);
@@ -458,6 +501,7 @@ var NucleoStanza = class _NucleoStanza {
458
501
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
459
502
  if (salvato !== void 0) {
460
503
  nucleo.dati = salvato;
504
+ nucleo.tickRateSincronizzato = salvato.tickRate;
461
505
  const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
462
506
  salvato.ultimoInputAt ??= adattatore.ora();
463
507
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
@@ -585,7 +629,7 @@ var NucleoStanza = class _NucleoStanza {
585
629
  if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
586
630
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
587
631
  if (esistente !== void 0) return { ok: true };
588
- if (this.configurazione.lobby && this.dati.status !== "lobby") {
632
+ if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
589
633
  return { ok: false, code: "room_playing" };
590
634
  }
591
635
  if (this.dati.giocatori.length >= this.configurazione.players.max) {
@@ -604,6 +648,7 @@ var NucleoStanza = class _NucleoStanza {
604
648
  const ora = this.adattatore.ora();
605
649
  let player = dati.giocatori.find((item) => item.id === identity.id);
606
650
  const nuovo = player === void 0;
651
+ const riconnesso = player !== void 0 && !player.connected;
607
652
  if (player === void 0) {
608
653
  player = {
609
654
  ...identity,
@@ -619,6 +664,7 @@ var NucleoStanza = class _NucleoStanza {
619
664
  dati.giocatori.push(player);
620
665
  } else {
621
666
  if (player.connected && player.connessione !== null && player.connessione !== connessione) {
667
+ this.frequenza.delete(player.connessione);
622
668
  this.adattatore.chiudi(player.connessione, 4006, "replaced");
623
669
  }
624
670
  player.name = identity.name;
@@ -640,6 +686,9 @@ var NucleoStanza = class _NucleoStanza {
640
686
  copiaGiocatore(player)
641
687
  );
642
688
  }
689
+ if (riconnesso) {
690
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), true);
691
+ }
643
692
  if (primaConnessione) {
644
693
  await this.chiama(this.definizione.onStart, this.room);
645
694
  this.inviaStatus(ora);
@@ -662,14 +711,16 @@ var NucleoStanza = class _NucleoStanza {
662
711
  player.connected = false;
663
712
  player.connessione = null;
664
713
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
665
- if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
714
+ if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
666
715
  this.frequenza.delete(connessione);
667
716
  if (this.dati.hostId === player.id) this.assegnaHost();
668
717
  this.verificaCountdown();
718
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
719
+ await this.concludiEvento();
669
720
  this.inviaGiocatori();
670
721
  await this.persistiEProgramma();
671
722
  }
672
- async ricevi(connessione, frame) {
723
+ async ricevi(connessione, frame, limiteVerificato = false) {
673
724
  if (this.dati === null || this.dati.status === "ended") return;
674
725
  if (await this.terminaSeInattiva()) return;
675
726
  const player = this.dati.giocatori.find(
@@ -677,17 +728,10 @@ var NucleoStanza = class _NucleoStanza {
677
728
  );
678
729
  if (player === void 0) return;
679
730
  if (new TextEncoder().encode(frame).byteLength > LIMITE_FRAME) {
680
- await this.chiudiConnessione(player, 4009, "bad_message");
731
+ await this.chiudiConnessione(player, 4009, "message_too_large");
681
732
  return;
682
733
  }
683
734
  const ora = this.adattatore.ora();
684
- const recenti = (this.frequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
685
- if (recenti.length >= 20) {
686
- await this.chiudiConnessione(player, 4008, "rate_limited");
687
- return;
688
- }
689
- recenti.push(ora);
690
- this.frequenza.set(connessione, recenti);
691
735
  let message = null;
692
736
  try {
693
737
  message = record(JSON.parse(frame));
@@ -697,6 +741,14 @@ var NucleoStanza = class _NucleoStanza {
697
741
  await this.chiudiConnessione(player, 4009, "bad_message");
698
742
  return;
699
743
  }
744
+ if (!limiteVerificato) {
745
+ const limite = this.frequenza.controlla(connessione, message.t === "msg", ora);
746
+ if (!limite.accetta) {
747
+ if (limite.avvisa) this.inviaErrore(player, "rate_limited", "Too many room messages. Excess messages are dropped.");
748
+ if (limite.chiudi) await this.chiudiConnessione(player, 4008, "rate_limited");
749
+ return;
750
+ }
751
+ }
700
752
  if (message.t === "ping") {
701
753
  if (typeof message.c !== "number" || !Number.isFinite(message.c)) {
702
754
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -719,6 +771,10 @@ var NucleoStanza = class _NucleoStanza {
719
771
  await this.persistiEProgramma();
720
772
  return;
721
773
  }
774
+ if (message.t === "restart") {
775
+ await this.rivincita(player);
776
+ return;
777
+ }
722
778
  if (message.t === "ready") {
723
779
  if (typeof message.ready !== "boolean") return this.messaggioErrato(player);
724
780
  if (!this.inLobby(player)) return;
@@ -790,6 +846,7 @@ var NucleoStanza = class _NucleoStanza {
790
846
  await this.persistiEProgramma();
791
847
  return;
792
848
  }
849
+ if (this.dati.status === "finished") return;
793
850
  this.dati.ultimoInputAt = ora;
794
851
  await this.chiama(
795
852
  this.definizione.onMessage,
@@ -860,7 +917,11 @@ var NucleoStanza = class _NucleoStanza {
860
917
  if (dovuti.length > 0) {
861
918
  const ids = new Set(dovuti.map((timer) => timer.id));
862
919
  this.dati.timer = this.dati.timer.filter((timer) => !ids.has(timer.id));
863
- for (const timer of dovuti) await this.eseguiTimer(timer);
920
+ for (const timer of dovuti) {
921
+ await this.eseguiTimer(timer);
922
+ await this.applicaAzioni();
923
+ if (this.dati.status === "finished" || this.stanzaTerminata()) break;
924
+ }
864
925
  }
865
926
  await this.concludiEvento();
866
927
  if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
@@ -891,22 +952,30 @@ var NucleoStanza = class _NucleoStanza {
891
952
  return esito;
892
953
  }
893
954
  async riconciliaConnessioni() {
955
+ if (this.dati === null || this.dati.status === "ended") return;
894
956
  const dati = this.richiediDati();
895
957
  const attive = new Set(this.adattatore.connessioniAttive());
896
958
  const ora = this.adattatore.ora();
897
- let cambiato = false;
959
+ const disconnessi = [];
898
960
  for (const player of dati.giocatori) {
899
961
  if (player.connected && (player.connessione === null || !attive.has(player.connessione))) {
900
962
  player.connected = false;
963
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
901
964
  player.connessione = null;
902
965
  player.graziaFinoA = ora + GRAZIA_MS;
903
- if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
904
- cambiato = true;
966
+ if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
967
+ disconnessi.push(player);
905
968
  }
906
969
  }
907
- if (cambiato) {
970
+ if (disconnessi.length > 0) {
908
971
  this.assegnaHost();
909
- await this.persisti();
972
+ this.verificaCountdown();
973
+ for (const player of disconnessi) {
974
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
975
+ }
976
+ await this.concludiEvento();
977
+ this.inviaGiocatori();
978
+ await this.persistiEProgramma();
910
979
  }
911
980
  }
912
981
  ruoloAutomatico() {
@@ -1020,6 +1089,43 @@ var NucleoStanza = class _NucleoStanza {
1020
1089
  }
1021
1090
  return null;
1022
1091
  }
1092
+ async rivincita(player) {
1093
+ const dati = this.richiediDati();
1094
+ if (dati.status !== "finished") {
1095
+ this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1096
+ return;
1097
+ }
1098
+ if (player.role !== "spectator" && !player.ready) {
1099
+ player.ready = true;
1100
+ this.inviaGiocatori();
1101
+ await this.persistiEProgramma();
1102
+ return;
1103
+ }
1104
+ if (dati.hostId !== player.id) return;
1105
+ const attivi = dati.giocatori.filter((item) => item.connected && item.role !== "spectator");
1106
+ if (attivi.length < this.configurazione.players.min || attivi.some((item) => !item.ready)) {
1107
+ this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1108
+ return;
1109
+ }
1110
+ dati.status = this.configurazione.lobby ? "lobby" : "playing";
1111
+ dati.rivincitaFinoA = null;
1112
+ dati.result = null;
1113
+ dati.resultAt = null;
1114
+ dati.ultimoInputAt = this.adattatore.ora();
1115
+ for (const item of dati.giocatori) item.ready = false;
1116
+ await this.chiama(this.definizione.onRestart, this.room);
1117
+ await this.applicaAzioni();
1118
+ if (dati.status === "playing") {
1119
+ await this.chiama(this.definizione.onStart, this.room);
1120
+ }
1121
+ await this.concludiEvento();
1122
+ if (dati.status === "lobby" || dati.status === "playing") {
1123
+ this.inviaSnapshotTutti();
1124
+ this.inviaGiocatori();
1125
+ this.inviaStatus(this.adattatore.ora());
1126
+ }
1127
+ await this.persistiEProgramma();
1128
+ }
1023
1129
  async avviaCountdown(player) {
1024
1130
  const dati = this.richiediDati();
1025
1131
  if (dati.hostId !== player.id) {
@@ -1056,6 +1162,7 @@ var NucleoStanza = class _NucleoStanza {
1056
1162
  const indice = dati.giocatori.findIndex((item) => item.id === player.id);
1057
1163
  if (indice < 0) return;
1058
1164
  dati.giocatori.splice(indice, 1);
1165
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
1059
1166
  this.rivediVoce();
1060
1167
  this.pulisciGuadagni(player.id);
1061
1168
  if (dati.hostId === player.id) this.assegnaHost();
@@ -1095,6 +1202,7 @@ var NucleoStanza = class _NucleoStanza {
1095
1202
  const json = analizzaJson(payload);
1096
1203
  if (!json.ok) throw new TypeError("Schedule payload must be valid JSON.");
1097
1204
  const dati = this.richiediDati();
1205
+ if (dati.status === "finished" || dati.status === "ended") return;
1098
1206
  dati.timer.push({
1099
1207
  id: dati.prossimoTimerId++,
1100
1208
  at: this.adattatore.ora() + milliseconds,
@@ -1102,6 +1210,9 @@ var NucleoStanza = class _NucleoStanza {
1102
1210
  payload: json.valore
1103
1211
  });
1104
1212
  }
1213
+ giornata(ora = this.adattatore.ora()) {
1214
+ return this.adattatore.giorno?.(ora) ?? giornoUtc(ora);
1215
+ }
1105
1216
  accodaPunteggio(playerId, board, score, daily) {
1106
1217
  if (!this.richiediDati().giocatori.some((player2) => player2.id === playerId)) {
1107
1218
  throw new Error("Player not found.");
@@ -1113,25 +1224,27 @@ var NucleoStanza = class _NucleoStanza {
1113
1224
  throw new TypeError("Score must be a non-negative safe integer.");
1114
1225
  }
1115
1226
  const submittedAt = this.adattatore.ora();
1227
+ const day = daily ? this.giornata(submittedAt) : null;
1116
1228
  this.richiediDati().punteggi.push({
1117
1229
  playerId,
1118
1230
  board,
1119
1231
  score,
1120
1232
  daily,
1121
1233
  submittedAt,
1122
- day: daily ? giornoUtc(submittedAt) : null
1234
+ day
1123
1235
  });
1124
1236
  const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
1125
1237
  if (player.connected && player.connessione !== null) this.adattatore.invia(player.connessione, {
1126
1238
  t: "score-queued",
1127
- score: { player: playerId, board, score, day: daily ? giornoUtc(submittedAt) : null, submittedAt }
1239
+ score: { player: playerId, board, score, day, submittedAt }
1128
1240
  });
1129
1241
  this.broadcast({ t: "flush" });
1130
1242
  }
1131
- richiediFine(result) {
1243
+ richiediFine(result, rematch = false) {
1132
1244
  const json = analizzaJson(result);
1133
1245
  if (!json.ok) throw new TypeError("Game result must be valid JSON.");
1134
- this.fineRichiesta = json.valore;
1246
+ if (this.dati?.status === "ended" || this.dati?.status === "finished" && rematch) return;
1247
+ this.fineRichiesta = { result: json.valore, rematch };
1135
1248
  }
1136
1249
  async salva(key, value) {
1137
1250
  if (!CHIAVE.test(key)) {
@@ -1298,6 +1411,7 @@ var NucleoStanza = class _NucleoStanza {
1298
1411
  id: dati.id,
1299
1412
  seed: seedStanza(dati.id),
1300
1413
  status: dati.status,
1414
+ result: dati.result,
1301
1415
  mode: dati.mode,
1302
1416
  tick: dati.tick,
1303
1417
  tickRate: dati.tickRate,
@@ -1323,16 +1437,18 @@ var NucleoStanza = class _NucleoStanza {
1323
1437
  host: dati.hostId,
1324
1438
  countdownAt: dati.countdownAt,
1325
1439
  at,
1326
- result: dati.status === "ended" ? dati.result : null
1440
+ result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
1327
1441
  });
1328
1442
  }
1329
1443
  inviaDiff() {
1330
1444
  const dati = this.richiediDati();
1331
1445
  const patch = creaDiff(dati.statoSincronizzato, dati.state);
1332
- if (patch.length === 0) return;
1446
+ if (patch.length === 0 && this.tickRateSincronizzato === dati.tickRate) return;
1447
+ this.tickRateSincronizzato = dati.tickRate;
1333
1448
  this.broadcast({
1334
1449
  t: "state",
1335
1450
  tick: dati.tick,
1451
+ tickRate: dati.tickRate,
1336
1452
  base: dati.tickSincronizzato,
1337
1453
  serverTime: this.adattatore.ora(),
1338
1454
  patch
@@ -1347,8 +1463,10 @@ var NucleoStanza = class _NucleoStanza {
1347
1463
  dati.state = stato.valore;
1348
1464
  dati.statoSincronizzato = copiaJson(stato.valore);
1349
1465
  dati.tickSincronizzato = dati.tick;
1466
+ this.tickRateSincronizzato = dati.tickRate;
1350
1467
  this.broadcast({
1351
1468
  t: "snapshot",
1469
+ tickRate: dati.tickRate,
1352
1470
  tick: dati.tick,
1353
1471
  serverTime: this.adattatore.ora(),
1354
1472
  state: stato.valore
@@ -1359,7 +1477,7 @@ var NucleoStanza = class _NucleoStanza {
1359
1477
  try {
1360
1478
  await callback(...args);
1361
1479
  } catch {
1362
- this.fineRichiesta = { error: "callback_error" };
1480
+ this.fineRichiesta = { result: { error: "callback_error" }, rematch: false };
1363
1481
  }
1364
1482
  }
1365
1483
  async applicaAzioni() {
@@ -1378,7 +1496,7 @@ var NucleoStanza = class _NucleoStanza {
1378
1496
  if (this.fineRichiesta !== null && this.dati.status !== "ended") {
1379
1497
  const result = this.fineRichiesta;
1380
1498
  this.fineRichiesta = null;
1381
- await this.terminaInterna(result);
1499
+ await this.terminaInterna(result.result, result.rematch);
1382
1500
  }
1383
1501
  } finally {
1384
1502
  this.applicandoAzioni = false;
@@ -1477,33 +1595,42 @@ var NucleoStanza = class _NucleoStanza {
1477
1595
  dati.state = dati.statoSincronizzato;
1478
1596
  await this.terminaInterna({ error: code });
1479
1597
  }
1480
- async terminaInterna(result) {
1598
+ async terminaInterna(result, rematch = false) {
1481
1599
  const dati = this.richiediDati();
1482
1600
  if (dati.status === "ended") return;
1483
- dati.status = "ended";
1601
+ const giaFinita = dati.status === "finished";
1602
+ dati.status = rematch ? "finished" : "ended";
1603
+ dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1604
+ dati.timer = [];
1605
+ if (rematch) for (const player of dati.giocatori) player.ready = false;
1484
1606
  dati.countdownAt = null;
1485
1607
  dati.result = result;
1486
1608
  dati.resultAt = this.adattatore.ora();
1487
1609
  try {
1488
- await this.definizione.onEnd?.(this.room);
1610
+ if (!giaFinita) await this.definizione.onEnd?.(this.room);
1489
1611
  } catch {
1490
1612
  if (record(result)?.error === void 0) dati.result = { error: "callback_error" };
1613
+ dati.status = "ended";
1614
+ dati.rivincitaFinoA = null;
1491
1615
  }
1492
1616
  const stato = analizzaJson(dati.state);
1493
1617
  if (!stato.ok || stato.bytes > LIMITE_STATO) {
1494
1618
  dati.state = dati.statoSincronizzato;
1495
1619
  dati.result = { error: stato.ok ? "state_too_large" : "state_invalid" };
1620
+ dati.status = "ended";
1621
+ dati.rivincitaFinoA = null;
1496
1622
  } else if (stato.testo !== JSON.stringify(dati.statoSincronizzato)) {
1497
1623
  dati.tick++;
1498
1624
  dati.state = stato.valore;
1499
1625
  this.inviaDiff();
1500
1626
  }
1501
1627
  const fine = { result: dati.result, at: dati.resultAt };
1502
- dati.fineInCoda = fine;
1628
+ if (dati.status === "ended") dati.fineInCoda = fine;
1629
+ if (dati.status === "finished") this.inviaGiocatori();
1503
1630
  this.inviaStatus(dati.resultAt);
1504
1631
  this.broadcast({ t: "flush" });
1505
1632
  for (const player of dati.giocatori) {
1506
- if (player.connected && player.connessione !== null) {
1633
+ if (dati.status === "ended" && player.connected && player.connessione !== null) {
1507
1634
  this.adattatore.chiudi(player.connessione, 4004, "room_ended");
1508
1635
  player.connected = false;
1509
1636
  player.connessione = null;
@@ -1518,7 +1645,7 @@ var NucleoStanza = class _NucleoStanza {
1518
1645
  if (dati.durateCpu.length > 50) dati.durateCpu.shift();
1519
1646
  dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
1520
1647
  if (dati.cpuOltreCento >= 20) {
1521
- this.fineRichiesta = { error: "cpu_budget" };
1648
+ this.fineRichiesta = { result: { error: "cpu_budget" }, rematch: false };
1522
1649
  return;
1523
1650
  }
1524
1651
  if (dati.durateCpu.length === 50) {
@@ -1549,6 +1676,11 @@ var NucleoStanza = class _NucleoStanza {
1549
1676
  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;
1550
1677
  }
1551
1678
  async terminaSeInattiva() {
1679
+ if (this.dati?.status === "finished") {
1680
+ if (this.adattatore.ora() < (this.dati.rivincitaFinoA ?? 0)) return false;
1681
+ await this.terminaInterna(this.dati.result);
1682
+ return true;
1683
+ }
1552
1684
  if (this.manifest.persistent === true) {
1553
1685
  if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
1554
1686
  await this.terminaInterna({ error: "expired" });
@@ -1568,6 +1700,7 @@ var NucleoStanza = class _NucleoStanza {
1568
1700
  this.serveTick() ? 1e3 / this.dati.tickRate : null
1569
1701
  );
1570
1702
  const prossime = [];
1703
+ if (this.dati.status === "finished") prossime.push(this.dati.rivincitaFinoA ?? this.adattatore.ora());
1571
1704
  if (this.manifest.persistent === true) {
1572
1705
  prossime.push(
1573
1706
  Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
@@ -1758,12 +1891,12 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1758
1891
  await nucleo.entra(identita, connessione);
1759
1892
  });
1760
1893
  }
1761
- ricevi(connessione, testo) {
1894
+ ricevi(connessione, testo, limiteVerificato = false) {
1762
1895
  return this.#esegui(async (nucleo) => {
1763
1896
  if (new TextEncoder().encode(testo).byteLength > 16 * 1024) {
1764
- this.#adattatore.chiudi(connessione, 4008, "rate_limited");
1897
+ this.#adattatore.chiudi(connessione, 4009, "message_too_large");
1765
1898
  await nucleo.disconnetti(connessione);
1766
- } else await nucleo.ricevi(connessione, testo);
1899
+ } else await nucleo.ricevi(connessione, testo, limiteVerificato);
1767
1900
  });
1768
1901
  }
1769
1902
  disconnetti(connessione) {
@@ -1772,6 +1905,13 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1772
1905
  await nucleo.disconnetti(connessione);
1773
1906
  });
1774
1907
  }
1908
+ riconciliaConnessioni(connessioni) {
1909
+ return this.#esegui(async (nucleo) => {
1910
+ this.#adattatore.connessioni.clear();
1911
+ for (const connessione of connessioni) this.#adattatore.connessioni.add(connessione);
1912
+ await nucleo.riconciliaConnessioni();
1913
+ });
1914
+ }
1775
1915
  tick() {
1776
1916
  return this.#esegui((nucleo) => nucleo.eseguiTick());
1777
1917
  }
package/dist/server.js CHANGED
@@ -3,7 +3,9 @@ var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition")
3
3
  var CALLBACKS = [
4
4
  "onCreate",
5
5
  "onStart",
6
+ "onRestart",
6
7
  "onJoin",
8
+ "onConnection",
7
9
  "onLeave",
8
10
  "onMessage",
9
11
  "onRoleRequest",
@@ -1,7 +1,7 @@
1
1
  import type { BoardResult, BoardTop, JsonValue, Player, SaveInfo } from './index.js';
2
2
  import type { GestoreBiglietto } from './handshake.js';
3
3
  export interface RispostaMe {
4
- player: Player;
4
+ player: Omit<Player, 'language' | 'uiLanguage'>;
5
5
  game: {
6
6
  slug: string;
7
7
  };
@@ -0,0 +1,12 @@
1
+ export type LocalizedText = string | Record<string, string>;
2
+ export type TextDictionary = Record<string, string>;
3
+ export declare function normalizeLanguage(value: unknown): string | null;
4
+ export declare function manifestLanguages(manifest: {
5
+ languages?: string[];
6
+ language?: string;
7
+ }): string[];
8
+ export declare function languageFallbacks(language: string, defaultLanguage?: string): string[];
9
+ export declare function resolveGameLanguage(preferences: readonly string[], languages?: readonly string[]): string;
10
+ export declare function resolveText(value: LocalizedText | undefined, language: string, defaultLanguage?: string, key?: string): string;
11
+ export declare function isTextDictionary(value: unknown): value is TextDictionary;
12
+ export declare function loadGameTexts(language: string, defaultLanguage: string, read: (language: string) => Promise<unknown>): Promise<TextDictionary>;
@@ -8,3 +8,6 @@ export * from './biglietto.js';
8
8
  export * from './token-crew.js';
9
9
  export * from './overlay.js';
10
10
  export * from './overlay-boards.js';
11
+ export * from './i18n.js';
12
+ export * from './room-limits.js';
13
+ export * from './player.js';
@@ -1,3 +1,4 @@
1
+ import { type LocalizedText } from './i18n.js';
1
2
  export type Platform = 'desktop' | 'mobile' | 'both';
2
3
  export type Orientation = 'landscape' | 'portrait';
3
4
  export type Input = 'keyboard' | 'mouse' | 'touch' | 'gamepad';
@@ -8,7 +9,7 @@ export interface ManifestPlayers {
8
9
  max: number;
9
10
  }
10
11
  export interface ManifestRole {
11
- label?: string;
12
+ label?: LocalizedText;
12
13
  id: string;
13
14
  min: number;
14
15
  max?: number;
@@ -40,14 +41,14 @@ export interface ManifestOverlay {
40
41
  accent?: string;
41
42
  }
42
43
  export interface ManifestBoard {
43
- label?: string;
44
+ label?: LocalizedText;
44
45
  periods?: BoardPeriod[];
45
46
  source: 'client' | 'server';
46
47
  }
47
48
  export interface ManifestMode {
48
49
  execution?: ModeExecution;
49
- label?: string;
50
- instructions?: string;
50
+ label?: LocalizedText;
51
+ instructions?: LocalizedText;
51
52
  id: string;
52
53
  players?: ManifestPlayers;
53
54
  lobby?: boolean;
@@ -63,7 +64,9 @@ export type ManifestModalita = ModalitaRisolta & {
63
64
  export declare function risolviModalita(manifest: ManifestModalita, mode: string | null): ModalitaRisolta;
64
65
  export declare function risolviPresentazione(manifest: ManifestModalita & {
65
66
  name?: string;
66
- }, mode: string | null): {
67
+ languages?: string[];
68
+ language?: string;
69
+ }, mode: string | null, language?: string): {
67
70
  execution: ModeExecution | null;
68
71
  label: string;
69
72
  instructions: string | null;
@@ -79,6 +82,8 @@ export interface Manifest {
79
82
  cover: string | null;
80
83
  screenshots: string[];
81
84
  tags: string[];
85
+ languages: string[];
86
+ /** @deprecated Usa languages; il primo elemento e' il default. */
82
87
  language: string;
83
88
  platform: Platform;
84
89
  orientation: Orientation;
@@ -9,9 +9,16 @@ export interface ReservedRect {
9
9
  width: number;
10
10
  height: number;
11
11
  }
12
+ export interface SafeArea {
13
+ top: number;
14
+ right: number;
15
+ bottom: number;
16
+ left: number;
17
+ }
12
18
  export interface OverlayView {
13
19
  inputBlocked: boolean;
14
20
  reservedRects: ReservedRect[];
21
+ safeArea?: SafeArea;
15
22
  shortcutEnabled?: boolean;
16
23
  }
17
24
  export interface OverlayConfiguration {
@@ -50,7 +57,7 @@ export interface SessionResume {
50
57
  export interface OverlayRoom {
51
58
  code: string;
52
59
  mode: string | null;
53
- status: 'lobby' | 'countdown' | 'playing' | 'ended';
60
+ status: 'lobby' | 'countdown' | 'playing' | 'finished' | 'ended';
54
61
  host: string | null;
55
62
  you: string | null;
56
63
  players: OverlayPlayer[];
@@ -128,6 +135,7 @@ export interface OverlayOperations {
128
135
  team: number;
129
136
  };
130
137
  'room.start': Record<string, never>;
138
+ 'room.restart': Record<string, never>;
131
139
  'session.cancel': Record<string, never>;
132
140
  'session.leave': Record<string, never>;
133
141
  'session.disconnect': Record<string, never>;
@@ -0,0 +1 @@
1
+ export declare function guestName(id: string): string;
@@ -0,0 +1,13 @@
1
+ export declare const MESSAGGI_GIOCO_AL_SECONDO = 20;
2
+ export declare const MESSAGGI_SERVIZIO_AL_SECONDO = 20;
3
+ export type EsitoLimiteMessaggi = {
4
+ accetta: boolean;
5
+ avvisa: boolean;
6
+ chiudi: boolean;
7
+ };
8
+ export declare class LimiteMessaggiStanza {
9
+ private readonly connessioni;
10
+ delete(connessione: string): void;
11
+ clear(): void;
12
+ controlla(connessione: string, gioco: boolean, ora: number): EsitoLimiteMessaggi;
13
+ }
@@ -10,6 +10,10 @@ export interface FinestraHandshakeKit extends GenitoreHandshake {
10
10
  clearTimeout(id: number): void;
11
11
  }
12
12
  export interface EsitoHandshake {
13
+ language?: string;
14
+ uiLanguage?: string;
15
+ languagePreferences?: string[];
16
+ gameLanguages?: string[];
13
17
  overlay?: OverlayHello;
14
18
  ticket: string;
15
19
  live: string | null;