@caisual/kit 0.25.0 → 0.25.1

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
@@ -420,6 +420,7 @@ var GRAZIA_MS = 6e4;
420
420
  var STANZA_VUOTA_MS = 5 * 6e4;
421
421
  var ATTESA_RIVINCITA_MS = 2 * 6e4;
422
422
  var COUNTDOWN_MS = 3e3;
423
+ var INTERVALLO_SALVATAGGIO_MS = 5e3;
423
424
  var RIPOSO_TICK_MS = 3e4;
424
425
  var INATTIVITA_MS = 10 * 6e4;
425
426
  var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
@@ -471,9 +472,9 @@ var NucleoStanza = class _NucleoStanza {
471
472
  this.fineRichiesta = null;
472
473
  this.applicandoAzioni = false;
473
474
  this.ultimoStatoOsservato = "";
474
- this.tickRateSincronizzato = null;
475
- this.voceDaPersistire = false;
475
+ this.salvataggioImmediato = false;
476
476
  const nucleo = this;
477
+ this.tickRate = definizione.tickRate;
477
478
  const daily = {
478
479
  get day() {
479
480
  return nucleo.richiediDati().daily.day;
@@ -502,7 +503,7 @@ var NucleoStanza = class _NucleoStanza {
502
503
  return nucleo.richiediDati().tick;
503
504
  },
504
505
  get tickRate() {
505
- return nucleo.richiediDati().tickRate;
506
+ return nucleo.tickRate;
506
507
  },
507
508
  get result() {
508
509
  return nucleo.richiediDati().result;
@@ -572,10 +573,10 @@ var NucleoStanza = class _NucleoStanza {
572
573
  if (salvato.versione !== VERSIONE_STATO) throw new Error("The saved room format is unsupported. Create a new room.");
573
574
  if (modalitaLocale(manifest, salvato.mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE), { code: "mode_local" });
574
575
  nucleo.dati = salvato;
575
- nucleo.tickRateSincronizzato = salvato.tickRate;
576
576
  nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
577
577
  await nucleo.riconciliaConnessioni();
578
578
  if (salvato.origin === "matchmaking") nucleo.rivalutaAvvio();
579
+ if (salvato.status === "playing" && nucleo.tickRate > 0) nucleo.inviaSnapshotTutti();
579
580
  }
580
581
  await nucleo.aggiornaProgrammazione();
581
582
  return nucleo;
@@ -607,7 +608,6 @@ var NucleoStanza = class _NucleoStanza {
607
608
  mode,
608
609
  status: origin === "matchmaking" ? "waiting" : "lobby",
609
610
  tick: 0,
610
- tickRate: this.definizione.tickRate,
611
611
  ultimoInputAt: ora,
612
612
  ultimoCambioStatoAt: ora,
613
613
  state: {},
@@ -622,8 +622,6 @@ var NucleoStanza = class _NucleoStanza {
622
622
  cancellaDopoFlush: false,
623
623
  tickSincronizzato: 0,
624
624
  statoSincronizzato: {},
625
- durateCpu: [],
626
- cpuOltreCento: 0,
627
625
  voceGuadagni: {}
628
626
  };
629
627
  await this.chiama(this.definizione.onCreate, this.room);
@@ -764,7 +762,7 @@ var NucleoStanza = class _NucleoStanza {
764
762
  this.inviaGiocatori();
765
763
  this.rivalutaAvvio();
766
764
  }
767
- await this.persistiEProgramma();
765
+ await this.persistiEProgramma(true);
768
766
  return { ok: true };
769
767
  }
770
768
  async disconnetti(connessione) {
@@ -782,7 +780,7 @@ var NucleoStanza = class _NucleoStanza {
782
780
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
783
781
  await this.concludiEvento();
784
782
  this.inviaGiocatori();
785
- await this.persistiEProgramma();
783
+ await this.persistiEProgramma(true);
786
784
  }
787
785
  async ricevi(connessione, frame, limiteVerificato = false) {
788
786
  if (this.dati === null || this.dati.status === "ended") return;
@@ -920,7 +918,7 @@ var NucleoStanza = class _NucleoStanza {
920
918
  await this.messaggioErrato(player);
921
919
  }
922
920
  async eseguiTick() {
923
- if (this.dati === null || this.dati.status !== "playing" || this.dati.tickRate === 0) return;
921
+ if (this.dati === null || this.dati.status !== "playing" || this.tickRate === 0) return;
924
922
  if (await this.terminaSeInattiva()) return;
925
923
  if (!this.serveTick()) {
926
924
  await this.persistiEProgramma();
@@ -928,14 +926,11 @@ var NucleoStanza = class _NucleoStanza {
928
926
  }
929
927
  const dati = this.dati;
930
928
  dati.tick++;
931
- const inizio = this.adattatore.misuraCpu();
932
929
  await this.chiama(
933
930
  this.definizione.onTick,
934
931
  this.room,
935
- 1 / dati.tickRate
932
+ 1 / this.tickRate
936
933
  );
937
- const durata = Math.max(0, this.adattatore.misuraCpu() - inizio);
938
- this.registraCpu(durata);
939
934
  await this.applicaAzioni();
940
935
  if (dati.status === "ended") return;
941
936
  this.inviaGuadagniCambiati();
@@ -943,13 +938,14 @@ var NucleoStanza = class _NucleoStanza {
943
938
  if (stato === null || this.stanzaTerminata()) return;
944
939
  dati.state = stato.valore;
945
940
  this.inviaDiff();
946
- if (dati.tick % 100 === 0 || this.voceDaPersistire) await this.persisti();
947
- await this.aggiornaProgrammazione();
941
+ await this.persistiEProgramma();
948
942
  }
949
943
  async sveglia() {
950
944
  if (this.dati === null || this.dati.status === "ended") return;
945
+ if (await this.terminaSeVuota()) return;
951
946
  if (await this.terminaSeInattiva()) return;
952
947
  const ora = this.adattatore.ora();
948
+ const statoPrima = this.dati.status;
953
949
  const scaduti = this.dati.giocatori.filter(
954
950
  (player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
955
951
  );
@@ -983,13 +979,10 @@ var NucleoStanza = class _NucleoStanza {
983
979
  }
984
980
  }
985
981
  await this.concludiEvento();
986
- if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
987
- this.dati.cancellaDopoFlush = true;
988
- await this.terminaInterna(null);
989
- }
982
+ await this.terminaSeVuota();
990
983
  if (scaduti.length > 0) this.inviaGiocatori();
991
984
  await this.concludiEvento();
992
- await this.persistiEProgramma();
985
+ await this.persistiEProgramma(scaduti.length > 0 || this.dati.status !== statoPrima);
993
986
  }
994
987
  async preparaFlush() {
995
988
  const dati = this.richiediDati();
@@ -1049,7 +1042,7 @@ var NucleoStanza = class _NucleoStanza {
1049
1042
  }
1050
1043
  await this.concludiEvento();
1051
1044
  this.inviaGiocatori();
1052
- await this.persistiEProgramma();
1045
+ await this.persistiEProgramma(true);
1053
1046
  }
1054
1047
  }
1055
1048
  ruoloAutomatico() {
@@ -1104,6 +1097,7 @@ var NucleoStanza = class _NucleoStanza {
1104
1097
  if (player.team === null) player.team = this.squadraAutomatica();
1105
1098
  if (this.richiediDati().status === "lobby") player.ready = false;
1106
1099
  if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
1100
+ this.salvataggioImmediato = true;
1107
1101
  this.rivediVoce();
1108
1102
  }
1109
1103
  this.inviaGiocatori();
@@ -1117,7 +1111,10 @@ var NucleoStanza = class _NucleoStanza {
1117
1111
  const squadraPrecedente = player.team;
1118
1112
  player.team = team;
1119
1113
  if (this.richiediDati().status === "lobby") player.ready = false;
1120
- if (player.team !== squadraPrecedente) this.rivediVoce();
1114
+ if (player.team !== squadraPrecedente) {
1115
+ this.salvataggioImmediato = true;
1116
+ this.rivediVoce();
1117
+ }
1121
1118
  this.inviaGiocatori();
1122
1119
  this.rivalutaAvvio();
1123
1120
  return null;
@@ -1239,6 +1236,7 @@ var NucleoStanza = class _NucleoStanza {
1239
1236
  const indice = dati.giocatori.findIndex((item) => item.id === player.id);
1240
1237
  if (indice < 0) return;
1241
1238
  dati.giocatori.splice(indice, 1);
1239
+ this.salvataggioImmediato = true;
1242
1240
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
1243
1241
  this.rivediVoce();
1244
1242
  this.pulisciGuadagni(player.id);
@@ -1390,7 +1388,7 @@ var NucleoStanza = class _NucleoStanza {
1390
1388
  rematch: this.rivincitaProtocollo(),
1391
1389
  mode: dati.mode,
1392
1390
  tick: dati.tick,
1393
- tickRate: dati.tickRate,
1391
+ tickRate: this.tickRate,
1394
1392
  serverTime: this.adattatore.ora(),
1395
1393
  countdownAt: dati.countdownAt,
1396
1394
  configuration: {
@@ -1417,12 +1415,11 @@ var NucleoStanza = class _NucleoStanza {
1417
1415
  inviaDiff() {
1418
1416
  const dati = this.richiediDati();
1419
1417
  const patch = creaDiff(dati.statoSincronizzato, dati.state);
1420
- if (patch.length === 0 && this.tickRateSincronizzato === dati.tickRate) return;
1421
- this.tickRateSincronizzato = dati.tickRate;
1418
+ if (patch.length === 0) return;
1422
1419
  this.broadcast({
1423
1420
  t: "state",
1424
1421
  tick: dati.tick,
1425
- tickRate: dati.tickRate,
1422
+ tickRate: this.tickRate,
1426
1423
  base: dati.tickSincronizzato,
1427
1424
  serverTime: this.adattatore.ora(),
1428
1425
  patch
@@ -1437,10 +1434,9 @@ var NucleoStanza = class _NucleoStanza {
1437
1434
  dati.state = stato.valore;
1438
1435
  dati.statoSincronizzato = copiaJson(stato.valore);
1439
1436
  dati.tickSincronizzato = dati.tick;
1440
- this.tickRateSincronizzato = dati.tickRate;
1441
1437
  this.broadcast({
1442
1438
  t: "snapshot",
1443
- tickRate: dati.tickRate,
1439
+ tickRate: this.tickRate,
1444
1440
  tick: dati.tick,
1445
1441
  serverTime: this.adattatore.ora(),
1446
1442
  state: stato.valore
@@ -1488,7 +1484,7 @@ var NucleoStanza = class _NucleoStanza {
1488
1484
  if (stato === null || this.stanzaTerminata()) return;
1489
1485
  const precedente = JSON.stringify(this.dati.statoSincronizzato);
1490
1486
  this.dati.state = stato.valore;
1491
- if ((this.dati.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
1487
+ if ((this.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
1492
1488
  this.dati.tick++;
1493
1489
  this.inviaDiff();
1494
1490
  }
@@ -1525,7 +1521,7 @@ var NucleoStanza = class _NucleoStanza {
1525
1521
  const precedente = dati.voceGuadagni[playerId]?.[altroId] ?? 1;
1526
1522
  if (precedente === valore) return;
1527
1523
  if (precedente > 0 && valore === 0) this.rivediVoce();
1528
- this.voceDaPersistire = true;
1524
+ this.salvataggioImmediato = true;
1529
1525
  if (valore === 1) {
1530
1526
  const riga = dati.voceGuadagni[playerId];
1531
1527
  if (riga !== void 0) {
@@ -1558,15 +1554,12 @@ var NucleoStanza = class _NucleoStanza {
1558
1554
  pulisciGuadagni(playerId) {
1559
1555
  const guadagni = this.richiediDati().voceGuadagni;
1560
1556
  if (guadagni === void 0) return;
1561
- let cambiato = Object.hasOwn(guadagni, playerId);
1562
1557
  delete guadagni[playerId];
1563
1558
  this.voceGuadagniCambiati.delete(playerId);
1564
1559
  for (const [altroId, riga] of Object.entries(guadagni)) {
1565
- cambiato = Object.hasOwn(riga, playerId) || cambiato;
1566
1560
  delete riga[playerId];
1567
1561
  if (Object.keys(riga).length === 0) delete guadagni[altroId];
1568
1562
  }
1569
- if (cambiato) this.voceDaPersistire = true;
1570
1563
  }
1571
1564
  async terminaPerStato(code) {
1572
1565
  const dati = this.richiediDati();
@@ -1577,7 +1570,8 @@ var NucleoStanza = class _NucleoStanza {
1577
1570
  const dati = this.richiediDati();
1578
1571
  if (dati.status === "ended") return;
1579
1572
  const giaFinita = dati.status === "finished";
1580
- if (dati.origin === "matchmaking" && record(result)?.error === void 0) rematch = true;
1573
+ if (dati.giocatori.length === 0) rematch = false;
1574
+ else if (dati.origin === "matchmaking" && record(result)?.error === void 0) rematch = true;
1581
1575
  dati.status = rematch ? "finished" : "ended";
1582
1576
  dati.rivincita = rematch ? { keepSetup: typeof rematch === "object" && rematch.keepSetup === true } : null;
1583
1577
  dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
@@ -1620,41 +1614,34 @@ var NucleoStanza = class _NucleoStanza {
1620
1614
  }
1621
1615
  await this.persistiEProgramma();
1622
1616
  }
1623
- registraCpu(durata) {
1624
- const dati = this.richiediDati();
1625
- dati.durateCpu.push(durata);
1626
- if (dati.durateCpu.length > 50) dati.durateCpu.shift();
1627
- dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
1628
- if (dati.cpuOltreCento >= 20) {
1629
- this.fineRichiesta = { result: { error: "cpu_budget" }, rematch: false };
1630
- return;
1631
- }
1632
- if (dati.durateCpu.length === 50) {
1633
- const media = dati.durateCpu.reduce((somma, value) => somma + value, 0) / 50;
1634
- if (media > 20 && dati.tickRate > 5) {
1635
- dati.tickRate = Math.max(5, Math.floor(dati.tickRate / 2));
1636
- dati.durateCpu = [];
1637
- this.broadcast({
1638
- t: "error",
1639
- code: "tick_rate_reduced",
1640
- message: `Tick rate reduced to ${dati.tickRate} because the game exceeded its CPU budget.`
1641
- });
1617
+ async persistiEProgramma(immediato = false) {
1618
+ const dati = this.dati;
1619
+ const ora = this.adattatore.ora();
1620
+ const tick = this.serveTick(ora);
1621
+ if (dati !== null && (!tick || immediato || this.salvataggioImmediato || ora >= (dati.prossimoSalvataggioAt ?? 0))) {
1622
+ const scadenzaPrima = dati.prossimoSalvataggioAt;
1623
+ dati.prossimoSalvataggioAt = ora + INTERVALLO_SALVATAGGIO_MS;
1624
+ try {
1625
+ await this.adattatore.storage.put(CHIAVE_NUCLEO, dati);
1626
+ } catch (errore) {
1627
+ dati.prossimoSalvataggioAt = scadenzaPrima;
1628
+ this.salvataggioImmediato = true;
1629
+ throw errore;
1642
1630
  }
1631
+ this.salvataggioImmediato = false;
1643
1632
  }
1633
+ await this.aggiornaProgrammazione(tick);
1644
1634
  }
1645
- async persisti() {
1646
- if (this.dati !== null) {
1647
- await this.adattatore.storage.put(CHIAVE_NUCLEO, this.dati);
1648
- this.voceDaPersistire = false;
1649
- }
1650
- }
1651
- async persistiEProgramma() {
1652
- await this.persisti();
1653
- await this.aggiornaProgrammazione();
1635
+ serveTick(ora = this.adattatore.ora()) {
1636
+ const dati = this.dati;
1637
+ return dati !== null && dati.status === "playing" && this.tickRate > 0 && dati.giocatori.some((player) => player.connected) && ora - Math.max(dati.ultimoInputAt, dati.ultimoCambioStatoAt) < RIPOSO_TICK_MS;
1654
1638
  }
1655
- serveTick() {
1639
+ async terminaSeVuota() {
1656
1640
  const dati = this.dati;
1657
- 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;
1641
+ if (dati === null || dati.status === "ended" || dati.giocatori.length > 0 || dati.vuotaDa === null || dati.vuotaDa + STANZA_VUOTA_MS > this.adattatore.ora()) return false;
1642
+ dati.cancellaDopoFlush = true;
1643
+ await this.terminaInterna(null);
1644
+ return true;
1658
1645
  }
1659
1646
  async terminaSeInattiva() {
1660
1647
  if (this.dati?.status === "finished") {
@@ -1675,15 +1662,13 @@ var NucleoStanza = class _NucleoStanza {
1675
1662
  await this.terminaInterna({ error: "idle" });
1676
1663
  return true;
1677
1664
  }
1678
- async aggiornaProgrammazione() {
1665
+ async aggiornaProgrammazione(tick = this.serveTick()) {
1679
1666
  if (this.dati === null || this.dati.status === "ended") {
1680
1667
  this.adattatore.programmaTick(null);
1681
1668
  await this.adattatore.programmaSveglia(null);
1682
1669
  return;
1683
1670
  }
1684
- this.adattatore.programmaTick(
1685
- this.serveTick() ? 1e3 / this.dati.tickRate : null
1686
- );
1671
+ this.adattatore.programmaTick(tick ? 1e3 / this.tickRate : null);
1687
1672
  const prossime = [];
1688
1673
  if (this.dati.status === "finished") prossime.push(this.dati.rivincitaFinoA ?? this.adattatore.ora());
1689
1674
  if (this.manifest.persistent === true) {
@@ -1896,9 +1881,6 @@ var AdattatoreNode = class {
1896
1881
  giorno(ora) {
1897
1882
  return this.dailyDay ?? giornoUtc(ora);
1898
1883
  }
1899
- misuraCpu() {
1900
- return performance.now();
1901
- }
1902
1884
  rivediVoce() {
1903
1885
  }
1904
1886
  programmaTick(intervalloMs) {
@@ -2268,11 +2250,31 @@ var StanzaNode = class {
2268
2250
  this.adattatore.invia(connessione, { t: "voice", op, r, error: { code, message } });
2269
2251
  }
2270
2252
  };
2253
+ function conAvvisoTick(definizione, manifest) {
2254
+ const onTick = definizione?.onTick;
2255
+ if (onTick === void 0 || definizione.tickRate === 0) return definizione;
2256
+ const intervallo = 1e3 / definizione.tickRate;
2257
+ let oltre = false;
2258
+ const tickMisurato = async (room, deltaSeconds) => {
2259
+ const inizio = performance.now();
2260
+ try {
2261
+ await onTick(room, deltaSeconds);
2262
+ } finally {
2263
+ const durata = performance.now() - inizio;
2264
+ const sfora = durata > intervallo;
2265
+ if (sfora && !oltre) {
2266
+ console.warn(`Il tick di ${manifest.id} ha richiesto ${durata.toFixed(1)} ms (intervallo ${intervallo.toFixed(1)} ms).`);
2267
+ }
2268
+ oltre = sfora;
2269
+ }
2270
+ };
2271
+ return Object.create(definizione, { onTick: { value: tickMisurato } });
2272
+ }
2271
2273
  async function createNodeRoom(definition, manifest, options = {}) {
2272
2274
  if (options.dailyDay !== void 0 && !validDay(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
2273
2275
  const storage = await ArchivioNode.apri(options.storageFile ?? null);
2274
2276
  const adattatore = new AdattatoreNode(storage, options.dailyDay);
2275
- const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
2277
+ const nucleo = await NucleoStanza.apri(conAvvisoTick(definition, manifest), manifest, adattatore);
2276
2278
  return new StanzaNode(nucleo, adattatore, manifest);
2277
2279
  }
2278
2280
  export {