@caisual/kit 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +12 -9
  2. package/dist/host.d.ts +1 -0
  3. package/dist/host.js +169 -0
  4. package/dist/kit.js +2 -4
  5. package/dist/kit.js.map +4 -4
  6. package/dist/node.js +193 -427
  7. package/dist/runtime.js +241 -269
  8. package/dist/types/api.d.ts +1 -1
  9. package/dist/types/contracts/connessione.d.ts +1 -0
  10. package/dist/types/contracts/giornata.d.ts +1 -0
  11. package/dist/types/contracts/index.d.ts +3 -2
  12. package/dist/types/contracts/manifest.d.ts +7 -50
  13. package/dist/types/contracts/network-budget.d.ts +53 -0
  14. package/dist/types/contracts/versioni.d.ts +0 -1
  15. package/dist/types/crew/index.d.ts +4 -0
  16. package/dist/types/handshake.d.ts +0 -4
  17. package/dist/types/{overlay/host-bridge.d.ts → host/index.d.ts} +60 -37
  18. package/dist/types/index.d.ts +66 -57
  19. package/dist/types/node/index.d.ts +5 -25
  20. package/dist/types/protocollo.d.ts +2 -21
  21. package/dist/types/runtime/index.d.ts +3 -13
  22. package/dist/types/runtime/network-probe.d.ts +4 -0
  23. package/dist/types/server/index.d.ts +1 -11
  24. package/dist/types/stanza/nucleo.d.ts +8 -16
  25. package/dist/types/stanza/tipi.d.ts +3 -21
  26. package/dist/types/voce/index.d.ts +0 -1
  27. package/package.json +15 -17
  28. package/dist/overlay.d.ts +0 -1
  29. package/dist/overlay.js +0 -2157
  30. package/dist/overlay.js.map +0 -7
  31. package/dist/types/contracts/overlay.d.ts +0 -235
  32. package/dist/types/contracts/replay.d.ts +0 -83
  33. package/dist/types/overlay/bridge.d.ts +0 -3
  34. package/dist/types/overlay/i18n.d.ts +0 -128
  35. package/dist/types/overlay/index.d.ts +0 -9
  36. package/dist/types/overlay/locale.d.ts +0 -4
  37. package/dist/types/overlay/shortcut.d.ts +0 -4
  38. package/dist/types/overlay/styles.d.ts +0 -1
  39. package/dist/types/overlay/ui-model.d.ts +0 -53
  40. package/dist/types/overlay/ui.d.ts +0 -81
  41. package/dist/types/overlay/voice-panel.d.ts +0 -13
  42. package/dist/types/replay/index.d.ts +0 -65
  43. package/dist/types/session/index.d.ts +0 -49
  44. package/dist/types/session/resume.d.ts +0 -13
package/dist/node.js CHANGED
@@ -37,22 +37,15 @@ var RISERVATI = new Set(NOMI_RISERVATI);
37
37
  function risolviModalita(manifest, mode) {
38
38
  const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
39
39
  if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");
40
- return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
40
+ return { players: { ...scelta?.players ?? manifest.players } };
41
41
  }
42
42
  function modalitaLocale(manifest, mode) {
43
- return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
43
+ return risolviModalita(manifest, mode).players.max === 1;
44
44
  }
45
- var MASSIMO_SPETTATORI = 100;
46
- var RITARDO_SPETTATORI_MS = 3e3;
45
+ var MODE_LOCAL_MESSAGE = "Single-player modes run in the browser and have no room.";
47
46
 
48
- // ../contracts/src/replay.ts
49
- var REPLAY_MAX_BYTES = 10 * 1024 * 1024;
50
- var REPLAY_MAX_DURATION_MS = 30 * 60 * 1e3;
51
- var REPLAY_CHUNK_BYTES = 512 * 1024;
52
- var REPLAY_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
53
-
54
- // ../contracts/src/overlay.ts
55
- function validBoardDay(value) {
47
+ // ../contracts/src/giornata.ts
48
+ function validDay(value) {
56
49
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
57
50
  const at = Date.parse(`${value}T00:00:00Z`);
58
51
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
@@ -100,6 +93,83 @@ var LimiteMessaggiStanza = class {
100
93
  }
101
94
  };
102
95
 
96
+ // ../contracts/src/network-budget.ts
97
+ var NETWORK_BUDGET = Object.freeze({
98
+ recipientBytesPerSecond: 1e5,
99
+ roomBytesPerSecond: 2e6,
100
+ warningRatio: 0.8,
101
+ windowMs: 5e3,
102
+ blockingWindows: 3
103
+ });
104
+ var NETWORK_GUIDANCE = `Multiplayer budget: ${NETWORK_BUDGET.recipientBytesPerSecond / 1e3} kB/s per recipient, ${NETWORK_BUDGET.roomBytesPerSecond / 1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${NETWORK_BUDGET.recipientBytesPerSecond / 2e4} kB per update. Keep visual trails and animation on the client. Warnings start at 80%. Publication measures your server automatically; repeated excess in real matches blocks new rooms only. Game input: 30 messages/s per connection.`;
105
+ function networkLevel(measurement) {
106
+ const ratio = Math.max(
107
+ measurement.recipientBytesPerSecond / NETWORK_BUDGET.recipientBytesPerSecond,
108
+ measurement.roomBytesPerSecond / NETWORK_BUDGET.roomBytesPerSecond
109
+ );
110
+ return ratio > 1 ? "exceeded" : ratio >= NETWORK_BUDGET.warningRatio ? "warning" : "ok";
111
+ }
112
+ function networkMessage(measurement) {
113
+ return `Network ${networkLevel(measurement)}: ${measurement.recipientBytesPerSecond} B/s per recipient (limit ${NETWORK_BUDGET.recipientBytesPerSecond}), ${measurement.roomBytesPerSecond} B/s per room (limit ${NETWORK_BUDGET.roomBytesPerSecond}), before compression over 5 seconds. Send compact changes; keep visual trails and animation on the client. At 20 updates/s, budget ${NETWORK_BUDGET.recipientBytesPerSecond / 2e4} kB per update.`;
114
+ }
115
+ var NetworkMeter = class {
116
+ events = [];
117
+ head = 0;
118
+ recipients = /* @__PURE__ */ new Map();
119
+ total = 0;
120
+ peak = { recipientBytesPerSecond: 0, roomBytesPerSecond: 0 };
121
+ checkAt = null;
122
+ violations = 0;
123
+ blocked = false;
124
+ encoder = new TextEncoder();
125
+ record(recipient, text, now = Date.now()) {
126
+ this.advance(now);
127
+ const bytes = this.encoder.encode(text).byteLength;
128
+ this.events.push({ at: now, recipient, bytes });
129
+ const recipientBytes = (this.recipients.get(recipient) ?? 0) + bytes;
130
+ this.recipients.set(recipient, recipientBytes);
131
+ this.total += bytes;
132
+ this.peak.recipientBytesPerSecond = Math.max(this.peak.recipientBytesPerSecond, this.rate(recipientBytes));
133
+ this.peak.roomBytesPerSecond = Math.max(this.peak.roomBytesPerSecond, this.rate(this.total));
134
+ }
135
+ sample(now = Date.now()) {
136
+ this.advance(now);
137
+ return { current: this.current(), peak: { ...this.peak }, consecutiveViolations: this.violations, blocked: this.blocked };
138
+ }
139
+ rate(bytes) {
140
+ return Math.ceil(bytes * 1e3 / NETWORK_BUDGET.windowMs);
141
+ }
142
+ current() {
143
+ let maximum = 0;
144
+ for (const bytes of this.recipients.values()) maximum = Math.max(maximum, bytes);
145
+ return { recipientBytesPerSecond: this.rate(maximum), roomBytesPerSecond: this.rate(this.total) };
146
+ }
147
+ advance(now) {
148
+ this.checkAt ??= now;
149
+ this.expire(now - NETWORK_BUDGET.windowMs, false);
150
+ if (now - this.checkAt >= NETWORK_BUDGET.windowMs) {
151
+ if (now - this.checkAt >= NETWORK_BUDGET.windowMs * 2) this.violations = 0;
152
+ this.violations = networkLevel(this.current()) === "exceeded" ? this.violations + 1 : 0;
153
+ this.blocked ||= this.violations >= NETWORK_BUDGET.blockingWindows;
154
+ this.checkAt = now;
155
+ }
156
+ this.expire(now - NETWORK_BUDGET.windowMs, true);
157
+ if (this.head > 1024) {
158
+ this.events = this.events.slice(this.head);
159
+ this.head = 0;
160
+ }
161
+ }
162
+ expire(cutoff, inclusive) {
163
+ while (this.head < this.events.length && (inclusive ? this.events[this.head].at <= cutoff : this.events[this.head].at < cutoff)) {
164
+ const event = this.events[this.head++];
165
+ this.total -= event.bytes;
166
+ const remaining = this.recipients.get(event.recipient) - event.bytes;
167
+ if (remaining === 0) this.recipients.delete(event.recipient);
168
+ else this.recipients.set(event.recipient, remaining);
169
+ }
170
+ }
171
+ };
172
+
103
173
  // src/daily.ts
104
174
  function prossimaMezzanotteUtc(ora) {
105
175
  return (Math.floor(ora / 864e5) + 1) * 864e5;
@@ -345,8 +415,6 @@ var PREFISSO_SAVE = "save:";
345
415
  var LIMITE_FRAME = MASSIMO_BYTE_FRAME_STANZA;
346
416
  var LIMITE_STATO = 512 * 1024;
347
417
  var LIMITE_SAVE = 256 * 1024;
348
- var LIMITE_DEPOSITO = 256 * 1024;
349
- var LIMITE_OPERAZIONI_DEPOSITO = 120;
350
418
  var GRAZIA_MS = 6e4;
351
419
  var STANZA_VUOTA_MS = 5 * 6e4;
352
420
  var ATTESA_RIVINCITA_MS = 2 * 6e4;
@@ -359,16 +427,7 @@ function scadenzaInattivita(ultimoEvento, durata) {
359
427
  return Math.ceil((ultimoEvento + durata) / BLOCCO_INATTIVITA_MS) * BLOCCO_INATTIVITA_MS;
360
428
  }
361
429
  var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
362
- var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
363
430
  var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
364
- var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
365
- "store_invalid_key",
366
- "store_too_large",
367
- "store_full",
368
- "store_not_integer",
369
- "store_unavailable",
370
- "store_rate_limited"
371
- ]);
372
431
  function record(value) {
373
432
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
374
433
  }
@@ -406,7 +465,6 @@ var NucleoStanza = class _NucleoStanza {
406
465
  this.adattatore = adattatore;
407
466
  this.dati = null;
408
467
  this.frequenza = new LimiteMessaggiStanza();
409
- this.frequenzaDeposito = [];
410
468
  this.kickRichiesti = /* @__PURE__ */ new Set();
411
469
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
412
470
  this.fineRichiesta = null;
@@ -457,11 +515,6 @@ var NucleoStanza = class _NucleoStanza {
457
515
  get players() {
458
516
  return nucleo.richiediDati().giocatori.map(copiaGiocatore);
459
517
  },
460
- get host() {
461
- const dati = nucleo.richiediDati();
462
- const host = dati.giocatori.find((player) => player.id === dati.hostId);
463
- return host === void 0 ? null : copiaGiocatore(host);
464
- },
465
518
  broadcast(message) {
466
519
  nucleo.broadcastCreatore(message);
467
520
  },
@@ -486,23 +539,6 @@ var NucleoStanza = class _NucleoStanza {
486
539
  load(key) {
487
540
  return nucleo.caricaSave(key);
488
541
  },
489
- shared: {
490
- get(key) {
491
- return nucleo.leggiDeposito(key);
492
- },
493
- set(key, value) {
494
- return nucleo.scriviDeposito(key, value);
495
- },
496
- delete(key) {
497
- return nucleo.eliminaDeposito(key);
498
- },
499
- list(prefix) {
500
- return nucleo.elencaDeposito(prefix);
501
- },
502
- increment(key, amount = 1) {
503
- return nucleo.incrementaDeposito(key, amount);
504
- }
505
- },
506
542
  schedule(milliseconds, handler, payload) {
507
543
  nucleo.pianifica(milliseconds, handler, payload);
508
544
  },
@@ -532,21 +568,28 @@ var NucleoStanza = class _NucleoStanza {
532
568
  const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
533
569
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
534
570
  if (salvato !== void 0) {
571
+ if (modalitaLocale(manifest, salvato.mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE), { code: "mode_local" });
535
572
  nucleo.dati = salvato;
536
573
  nucleo.tickRateSincronizzato = salvato.tickRate;
537
- const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0;
574
+ let daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0 || salvato.origin === void 0;
575
+ salvato.origin ??= "player";
576
+ if (salvato.origin === "matchmaking" && salvato.status === "lobby") {
577
+ salvato.status = "waiting";
578
+ daAggiornare = true;
579
+ }
538
580
  salvato.daily ??= nucleo.contestoGiornaliero();
539
581
  salvato.ultimoInputAt ??= adattatore.ora();
540
582
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
541
583
  nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
542
584
  await nucleo.riconciliaConnessioni();
585
+ if (salvato.origin === "matchmaking") nucleo.rivalutaAvvio();
543
586
  if (daAggiornare) await nucleo.persisti();
544
587
  }
545
588
  await nucleo.aggiornaProgrammazione();
546
589
  return nucleo;
547
590
  }
548
591
  static verificaManifest(manifest) {
549
- if (typeof manifest?.id !== "string" || !Number.isInteger(manifest.players?.min) || !Number.isInteger(manifest.players?.max) || manifest.players.min < 1 || manifest.players.max < manifest.players.min || typeof manifest.lobby !== "boolean" || manifest.persistent !== void 0 && typeof manifest.persistent !== "boolean" || !Array.isArray(manifest.roles) || !Array.isArray(manifest.modes) || manifest.voice !== void 0 && !["none", "room", "team", "proximity"].includes(manifest.voice)) {
592
+ if (typeof manifest?.id !== "string" || !Number.isInteger(manifest.players?.min) || !Number.isInteger(manifest.players?.max) || manifest.players.min < 1 || manifest.players.max < manifest.players.min || manifest.persistent !== void 0 && typeof manifest.persistent !== "boolean" || !Array.isArray(manifest.roles) || !Array.isArray(manifest.modes) || manifest.voice !== void 0 && !["none", "room", "team", "proximity"].includes(manifest.voice)) {
550
593
  throw new TypeError("The room manifest is invalid.");
551
594
  }
552
595
  }
@@ -560,30 +603,28 @@ var NucleoStanza = class _NucleoStanza {
560
603
  get esiste() {
561
604
  return this.dati !== null;
562
605
  }
563
- async crea(id, mode, _creator) {
606
+ async crea(id, mode, _creator, origin = "player") {
564
607
  if (this.dati !== null) return false;
565
- risolviModalita(this.manifest, mode);
566
- if (modalitaLocale(this.manifest, mode)) throw new Error("Local modes cannot create rooms.");
608
+ if (modalitaLocale(this.manifest, mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE), { code: "mode_local" });
567
609
  const ora = this.adattatore.ora();
568
610
  this.dati = {
569
611
  versione: 1,
612
+ origin,
570
613
  daily: this.contestoGiornaliero(ora),
571
614
  id,
572
615
  mode,
573
- status: "lobby",
616
+ status: origin === "matchmaking" ? "waiting" : "lobby",
574
617
  tick: 0,
575
618
  tickRate: this.definizione.tickRate,
576
619
  ultimoInputAt: ora,
577
620
  ultimoCambioStatoAt: ora,
578
621
  state: {},
579
622
  giocatori: [],
580
- hostId: null,
581
623
  result: null,
582
624
  resultAt: null,
583
625
  countdownAt: null,
584
626
  timer: [],
585
627
  prossimoTimerId: 1,
586
- punteggi: [],
587
628
  fineInCoda: null,
588
629
  vuotaDa: ora,
589
630
  cancellaDopoFlush: false,
@@ -610,13 +651,13 @@ var NucleoStanza = class _NucleoStanza {
610
651
  return true;
611
652
  }
612
653
  get configurazione() {
613
- const mode = risolviModalita(this.manifest, this.dati?.mode ?? null);
614
- return mode.players.max === 1 ? { ...mode, lobby: false } : mode;
654
+ return risolviModalita(this.manifest, this.dati?.mode ?? null);
615
655
  }
616
656
  info(playerId) {
617
657
  if (this.dati === null) return null;
618
658
  return {
619
659
  roomId: this.dati.id,
660
+ origin: this.dati.origin,
620
661
  status: this.dati.status,
621
662
  players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
622
663
  (player) => player.connected || player.graziaFinoA !== null
@@ -650,7 +691,7 @@ var NucleoStanza = class _NucleoStanza {
650
691
  if (ascoltatore === void 0 || speaker === void 0 || listener === speakerId) {
651
692
  return { ok: false, reason: "unknown" };
652
693
  }
653
- if (mode === "team" && ascoltatore.role !== "spectator" && ascoltatore.team !== speaker.team) {
694
+ if (mode === "team" && ascoltatore.team !== speaker.team) {
654
695
  return { ok: false, reason: "team" };
655
696
  }
656
697
  if ((dati.voceGuadagni?.[listener]?.[speakerId] ?? 1) <= 0) {
@@ -661,15 +702,18 @@ var NucleoStanza = class _NucleoStanza {
661
702
  }
662
703
  puoEntrare(identity) {
663
704
  if (this.dati === null) return { ok: false, code: "room_not_found" };
664
- if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
705
+ if (this.dati.status === "ended" || this.dati.origin === "matchmaking" && this.dati.status === "finished") return { ok: false, code: "room_ended" };
665
706
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
666
707
  if (esistente !== void 0) return { ok: true };
667
- if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
708
+ if (this.dati?.origin === "player" && !["lobby", "countdown", "finished"].includes(this.dati.status)) {
668
709
  return { ok: false, code: "room_playing" };
669
710
  }
670
711
  if (this.dati.giocatori.length >= this.configurazione.players.max) {
671
712
  return { ok: false, code: "room_full" };
672
713
  }
714
+ if (this.manifest.roles.length > 0 && this.ruoloAutomatico() === null) {
715
+ return { ok: false, code: "room_full" };
716
+ }
673
717
  return { ok: true };
674
718
  }
675
719
  async entra(identity, connessione) {
@@ -709,11 +753,8 @@ var NucleoStanza = class _NucleoStanza {
709
753
  player.connessione = connessione;
710
754
  player.seq = 0;
711
755
  }
712
- dati.hostId ??= player.id;
713
756
  dati.vuotaDa = null;
714
757
  dati.ultimoInputAt = ora;
715
- const primaConnessione = !this.configurazione.lobby && dati.status === "lobby";
716
- if (primaConnessione) dati.status = "playing";
717
758
  if (nuovo) {
718
759
  await this.chiama(
719
760
  this.definizione.onJoin,
@@ -724,16 +765,12 @@ var NucleoStanza = class _NucleoStanza {
724
765
  if (riconnesso) {
725
766
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), true);
726
767
  }
727
- if (primaConnessione) {
728
- await this.chiama(this.definizione.onStart, this.room);
729
- this.iniziaReplay();
730
- this.inviaStatus(ora);
731
- }
732
768
  await this.concludiEvento();
733
769
  if (dati.status !== "ended") {
734
770
  this.inviaWelcome(player);
735
771
  this.inviaSnapshotTutti();
736
772
  this.inviaGiocatori();
773
+ this.rivalutaAvvio();
737
774
  }
738
775
  await this.persistiEProgramma();
739
776
  return { ok: true };
@@ -747,10 +784,9 @@ var NucleoStanza = class _NucleoStanza {
747
784
  player.connected = false;
748
785
  player.connessione = null;
749
786
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
750
- if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
787
+ if (this.dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(this.dati.status)) player.ready = false;
751
788
  this.frequenza.delete(connessione);
752
- if (this.dati.hostId === player.id) this.assegnaHost();
753
- this.verificaCountdown();
789
+ this.rivalutaAvvio();
754
790
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
755
791
  await this.concludiEvento();
756
792
  this.inviaGiocatori();
@@ -807,6 +843,11 @@ var NucleoStanza = class _NucleoStanza {
807
843
  await this.persistiEProgramma();
808
844
  return;
809
845
  }
846
+ if (this.dati.origin === "matchmaking" && (message.t === "ready" || message.t === "restart")) return;
847
+ if (this.dati.origin === "matchmaking" && (message.t === "role" || message.t === "team")) {
848
+ this.inviaErrore(player, "matchmaking_room", "Roles and teams are assigned by the server in matchmaking rooms.");
849
+ return;
850
+ }
810
851
  if (message.t === "restart") {
811
852
  await this.rivincita(player);
812
853
  return;
@@ -817,6 +858,7 @@ var NucleoStanza = class _NucleoStanza {
817
858
  this.dati.ultimoInputAt = ora;
818
859
  player.ready = message.ready;
819
860
  this.inviaGiocatori();
861
+ this.rivalutaAvvio();
820
862
  await this.persistiEProgramma();
821
863
  return;
822
864
  }
@@ -858,12 +900,6 @@ var NucleoStanza = class _NucleoStanza {
858
900
  await this.persistiEProgramma();
859
901
  return;
860
902
  }
861
- if (message.t === "start") {
862
- if (!this.inLobby(player)) return;
863
- this.dati.ultimoInputAt = ora;
864
- await this.avviaCountdown(player);
865
- return;
866
- }
867
903
  if (message.t === "msg") {
868
904
  if (!Number.isSafeInteger(message.seq) || message.seq < 1) {
869
905
  await this.messaggioErrato(player);
@@ -877,11 +913,6 @@ var NucleoStanza = class _NucleoStanza {
877
913
  return;
878
914
  }
879
915
  player.seq = seq;
880
- if (player.role === "spectator") {
881
- this.inviaErrore(player, "spectator", "Spectators cannot send game input.");
882
- await this.persistiEProgramma();
883
- return;
884
- }
885
916
  if (this.dati.status === "finished") return;
886
917
  this.dati.ultimoInputAt = ora;
887
918
  await this.chiama(
@@ -937,7 +968,7 @@ var NucleoStanza = class _NucleoStanza {
937
968
  if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
938
969
  const errore = this.erroreMinimi(this.dati.countdownRivincita);
939
970
  if (errore !== null) {
940
- this.dati.status = "lobby";
971
+ this.dati.status = this.dati.origin === "matchmaking" ? "waiting" : "lobby";
941
972
  this.dati.countdownAt = null;
942
973
  this.broadcast({ t: "error", code: errore.code, message: errore.message });
943
974
  this.inviaStatus(ora);
@@ -946,7 +977,6 @@ var NucleoStanza = class _NucleoStanza {
946
977
  this.dati.ultimoInputAt = ora;
947
978
  this.dati.countdownAt = null;
948
979
  await this.chiama(this.definizione.onStart, this.room);
949
- this.iniziaReplay();
950
980
  this.inviaStatus(ora);
951
981
  }
952
982
  }
@@ -975,9 +1005,8 @@ var NucleoStanza = class _NucleoStanza {
975
1005
  await this.persistiEProgramma();
976
1006
  return dati.flushInAttesa;
977
1007
  }
978
- if (dati.punteggi.length === 0 && dati.fineInCoda === null) return null;
979
- dati.flushInAttesa = { id: crypto.randomUUID(), scores: dati.punteggi, ended: dati.fineInCoda };
980
- dati.punteggi = [];
1008
+ if (dati.fineInCoda === null) return null;
1009
+ dati.flushInAttesa = { id: crypto.randomUUID(), ended: dati.fineInCoda };
981
1010
  dati.fineInCoda = null;
982
1011
  await this.persistiEProgramma();
983
1012
  return dati.flushInAttesa;
@@ -991,10 +1020,8 @@ var NucleoStanza = class _NucleoStanza {
991
1020
  async flush() {
992
1021
  const dati = this.richiediDati();
993
1022
  const esito = {
994
- scores: dati.punteggi.map((score) => ({ ...score })),
995
1023
  ended: dati.fineInCoda === null ? null : { result: dati.fineInCoda.result, at: dati.fineInCoda.at }
996
1024
  };
997
- dati.punteggi = [];
998
1025
  dati.fineInCoda = null;
999
1026
  if (dati.cancellaDopoFlush && dati.status === "ended") {
1000
1027
  const chiavi = await this.adattatore.storage.list();
@@ -1019,13 +1046,12 @@ var NucleoStanza = class _NucleoStanza {
1019
1046
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
1020
1047
  player.connessione = null;
1021
1048
  player.graziaFinoA = ora + GRAZIA_MS;
1022
- if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
1049
+ if (dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(dati.status)) player.ready = false;
1023
1050
  disconnessi.push(player);
1024
1051
  }
1025
1052
  }
1026
1053
  if (disconnessi.length > 0) {
1027
- this.assegnaHost();
1028
- this.verificaCountdown();
1054
+ this.rivalutaAvvio();
1029
1055
  for (const player of disconnessi) {
1030
1056
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
1031
1057
  }
@@ -1048,7 +1074,7 @@ var NucleoStanza = class _NucleoStanza {
1048
1074
  const mancaB = countB < b.min ? 0 : 1;
1049
1075
  return mancaA - mancaB || countA - countB;
1050
1076
  });
1051
- return candidati[0]?.id ?? "spectator";
1077
+ return candidati[0]?.id ?? null;
1052
1078
  }
1053
1079
  squadraAutomatica() {
1054
1080
  if (this.manifest.teams === null) return null;
@@ -1071,39 +1097,37 @@ var NucleoStanza = class _NucleoStanza {
1071
1097
  }
1072
1098
  cambiaRuolo(player, roleId) {
1073
1099
  const ruolo = this.manifest.roles.find((item) => item.id === roleId);
1074
- if (ruolo === void 0 && roleId !== "spectator") {
1100
+ if (ruolo === void 0) {
1075
1101
  return { code: "invalid_role", message: "This role does not exist." };
1076
1102
  }
1077
1103
  const occupati = this.richiediDati().giocatori.filter(
1078
1104
  (item) => item.id !== player.id && item.role === roleId
1079
1105
  ).length;
1080
- if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
1106
+ if (ruolo.max !== void 0 && occupati >= ruolo.max) {
1081
1107
  return { code: "role_full", message: "This role is full." };
1082
1108
  }
1083
1109
  const ruoloPrecedente = player.role;
1084
1110
  const squadraPrecedente = player.team;
1085
1111
  player.role = roleId;
1086
- if (roleId === "spectator") player.team = null;
1087
- else if (player.team === null) player.team = this.squadraAutomatica();
1112
+ if (player.team === null) player.team = this.squadraAutomatica();
1088
1113
  if (this.richiediDati().status === "lobby") player.ready = false;
1089
1114
  if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
1090
1115
  this.rivediVoce();
1091
1116
  }
1092
1117
  this.inviaGiocatori();
1118
+ this.rivalutaAvvio();
1093
1119
  return null;
1094
1120
  }
1095
1121
  cambiaSquadra(player, team) {
1096
1122
  if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
1097
1123
  return { code: "invalid_team", message: "This team does not exist." };
1098
1124
  }
1099
- if (player.role === "spectator") {
1100
- return { code: "spectator", message: "Spectators cannot join a team." };
1101
- }
1102
1125
  const squadraPrecedente = player.team;
1103
1126
  player.team = team;
1104
1127
  if (this.richiediDati().status === "lobby") player.ready = false;
1105
1128
  if (player.team !== squadraPrecedente) this.rivediVoce();
1106
1129
  this.inviaGiocatori();
1130
+ this.rivalutaAvvio();
1107
1131
  return null;
1108
1132
  }
1109
1133
  impostaRuoloDalServer(playerId, roleId) {
@@ -1125,21 +1149,21 @@ var NucleoStanza = class _NucleoStanza {
1125
1149
  }
1126
1150
  erroreMinimi(saltaPronti = false) {
1127
1151
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
1128
- const attivi = connessi.filter((player) => player.role !== "spectator");
1129
- if (attivi.length < this.configurazione.players.min) {
1152
+ if (connessi.length < this.configurazione.players.min) {
1130
1153
  return { code: "not_enough_players", message: "The room does not have enough players." };
1131
1154
  }
1155
+ if (this.dati?.origin === "matchmaking") return null;
1132
1156
  if (!saltaPronti && connessi.some((player) => !player.ready)) {
1133
1157
  return { code: "players_not_ready", message: "Every connected player must be ready." };
1134
1158
  }
1135
1159
  for (const role of this.manifest.roles) {
1136
- if (attivi.filter((player) => player.role === role.id).length < role.min) {
1160
+ if (connessi.filter((player) => player.role === role.id).length < role.min) {
1137
1161
  return { code: "role_minimum", message: `Role ${role.id} does not meet its minimum.` };
1138
1162
  }
1139
1163
  }
1140
1164
  if (this.manifest.teams !== null) {
1141
- const squadre = new Set(attivi.map((player) => player.team).filter((team) => team !== null));
1142
- if (attivi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
1165
+ const squadre = new Set(connessi.map((player) => player.team).filter((team) => team !== null));
1166
+ if (connessi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
1143
1167
  return { code: "team_minimum", message: "The room does not have enough teams." };
1144
1168
  }
1145
1169
  }
@@ -1151,32 +1175,25 @@ var NucleoStanza = class _NucleoStanza {
1151
1175
  this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1152
1176
  return;
1153
1177
  }
1154
- if (this.configurazione.players.max === 1) {
1155
- await this.avviaRivincita();
1156
- return;
1157
- }
1158
- if (player.role !== "spectator" && !player.ready) {
1159
- player.ready = true;
1160
- this.inviaGiocatori();
1161
- if (dati.rivincita?.autoStart && this.prontiRivincita()) await this.avviaRivincita();
1162
- else await this.persistiEProgramma();
1163
- return;
1164
- }
1165
- if (dati.hostId !== player.id) return;
1166
- if (!this.prontiRivincita(dati.rivincita?.autoStart === true)) {
1167
- this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1168
- return;
1169
- }
1170
- await this.avviaRivincita();
1178
+ if (player.ready) return;
1179
+ player.ready = true;
1180
+ this.inviaGiocatori();
1181
+ if (this.prontiRivincita()) await this.avviaRivincita();
1182
+ else await this.persistiEProgramma();
1171
1183
  }
1172
- prontiRivincita(anticipata = false) {
1173
- const attivi = this.richiediDati().giocatori.filter((item) => item.connected && item.role !== "spectator");
1174
- return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && (anticipata || attivi.every((item) => item.ready));
1184
+ prontiRivincita() {
1185
+ const attivi = this.richiediDati().giocatori.filter((item) => item.connected);
1186
+ return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && attivi.every((item) => item.ready);
1175
1187
  }
1176
1188
  async avviaRivincita() {
1177
- const dati = this.richiediDati(), solo = this.configurazione.players.max === 1;
1178
- const keepSetup = dati.rivincita?.keepSetup === true && !solo;
1179
- dati.status = solo ? "playing" : keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
1189
+ const dati = this.richiediDati();
1190
+ if (dati.origin === "matchmaking") {
1191
+ for (const player of dati.giocatori.filter((item) => !item.connected)) await this.rimuoviGiocatore(player, "timeout");
1192
+ await this.applicaAzioni();
1193
+ if (this.stanzaTerminata()) return;
1194
+ }
1195
+ const keepSetup = dati.origin === "player" && dati.rivincita?.keepSetup === true;
1196
+ dati.status = dati.origin === "matchmaking" ? "waiting" : keepSetup ? "countdown" : "lobby";
1180
1197
  dati.countdownRivincita = keepSetup;
1181
1198
  dati.countdownAt = keepSetup ? this.adattatore.ora() + COUNTDOWN_MS : null;
1182
1199
  dati.rivincitaFinoA = null;
@@ -1188,41 +1205,34 @@ var NucleoStanza = class _NucleoStanza {
1188
1205
  dati.prontiPrecedenti = [];
1189
1206
  await this.chiama(this.definizione.onRestart, this.room);
1190
1207
  await this.applicaAzioni();
1191
- if (dati.status === "playing") {
1192
- await this.chiama(this.definizione.onStart, this.room);
1193
- this.iniziaReplay();
1194
- }
1195
1208
  await this.concludiEvento();
1196
- if (dati.status === "lobby" || dati.status === "playing" || dati.status === "countdown") {
1209
+ this.rivalutaAvvio();
1210
+ if (["waiting", "lobby", "playing", "countdown"].includes(dati.status)) {
1197
1211
  this.inviaSnapshotTutti();
1198
1212
  this.inviaGiocatori();
1199
1213
  this.inviaStatus(this.adattatore.ora());
1200
1214
  }
1201
1215
  await this.persistiEProgramma();
1202
1216
  }
1203
- async avviaCountdown(player) {
1217
+ /**
1218
+ * Nessuno ospita e nessuno preme "inizia": appena tutti i connessi sono pronti e i
1219
+ * minimi di giocatori, ruoli e squadre sono rispettati parte il countdown; se la
1220
+ * condizione cade durante il countdown si torna in lobby.
1221
+ */
1222
+ rivalutaAvvio() {
1204
1223
  const dati = this.richiediDati();
1205
- if (dati.hostId !== player.id) {
1206
- this.inviaErrore(player, "not_host", "Only the host can start the game.");
1207
- return;
1208
- }
1209
- const errore = this.erroreMinimi();
1210
- if (errore !== null) {
1211
- this.inviaErrore(player, errore.code, errore.message);
1224
+ if (dati.status === "countdown") {
1225
+ if (this.erroreMinimi(dati.countdownRivincita) === null) return;
1226
+ dati.status = dati.origin === "matchmaking" ? "waiting" : "lobby";
1227
+ dati.countdownAt = null;
1228
+ this.inviaStatus(this.adattatore.ora());
1212
1229
  return;
1213
1230
  }
1231
+ if (!["lobby", "waiting"].includes(dati.status) || this.erroreMinimi() !== null) return;
1214
1232
  dati.status = "countdown";
1215
1233
  dati.countdownRivincita = false;
1216
1234
  dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
1217
1235
  this.inviaStatus(dati.countdownAt);
1218
- await this.persistiEProgramma();
1219
- }
1220
- verificaCountdown() {
1221
- const dati = this.richiediDati();
1222
- if (dati.status !== "countdown" || this.erroreMinimi(dati.countdownRivincita) === null) return;
1223
- dati.status = "lobby";
1224
- dati.countdownAt = null;
1225
- this.inviaStatus(this.adattatore.ora());
1226
1236
  }
1227
1237
  async messaggioErrato(player) {
1228
1238
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -1240,7 +1250,6 @@ var NucleoStanza = class _NucleoStanza {
1240
1250
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
1241
1251
  this.rivediVoce();
1242
1252
  this.pulisciGuadagni(player.id);
1243
- if (dati.hostId === player.id) this.assegnaHost();
1244
1253
  if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
1245
1254
  await this.chiama(
1246
1255
  this.definizione.onLeave,
@@ -1248,12 +1257,7 @@ var NucleoStanza = class _NucleoStanza {
1248
1257
  copiaGiocatore({ ...player, connected: false, connessione: null }),
1249
1258
  reason
1250
1259
  );
1251
- this.verificaCountdown();
1252
- }
1253
- assegnaHost() {
1254
- const dati = this.richiediDati();
1255
- const host = dati.giocatori.filter((player) => player.connected).sort((a, b) => a.entratoAt - b.entratoAt)[0];
1256
- dati.hostId = host?.id ?? null;
1260
+ this.rivalutaAvvio();
1257
1261
  }
1258
1262
  async eseguiTimer(timer) {
1259
1263
  const value = this.definizione[timer.handler];
@@ -1319,91 +1323,6 @@ var NucleoStanza = class _NucleoStanza {
1319
1323
  if (!json.ok) throw new Error("The saved value is invalid.");
1320
1324
  return json.valore;
1321
1325
  }
1322
- verificaChiaveDeposito(key) {
1323
- if (typeof key !== "string" || !CHIAVE.test(key)) {
1324
- throw erroreConCodice(
1325
- "store_invalid_key",
1326
- "Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
1327
- );
1328
- }
1329
- }
1330
- verificaPrefissoDeposito(prefix) {
1331
- if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
1332
- throw erroreConCodice(
1333
- "store_invalid_key",
1334
- "Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
1335
- );
1336
- }
1337
- }
1338
- contaOperazioneDeposito() {
1339
- const ora = this.adattatore.ora();
1340
- this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
1341
- if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
1342
- throw erroreConCodice(
1343
- "store_rate_limited",
1344
- "The shared store allows at most 120 operations per minute for each room."
1345
- );
1346
- }
1347
- this.frequenzaDeposito.push(ora);
1348
- }
1349
- async usaDeposito(operazione) {
1350
- this.contaOperazioneDeposito();
1351
- const deposito = this.adattatore.deposito;
1352
- if (deposito === null) {
1353
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1354
- }
1355
- try {
1356
- return await operazione(deposito);
1357
- } catch (cause) {
1358
- const code = cause instanceof Error ? cause.code : void 0;
1359
- if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
1360
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1361
- }
1362
- }
1363
- async leggiDeposito(key) {
1364
- this.verificaChiaveDeposito(key);
1365
- const value = await this.usaDeposito((deposito) => deposito.get(key));
1366
- if (value === null) return null;
1367
- try {
1368
- return JSON.parse(JSON.stringify(value));
1369
- } catch {
1370
- throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
1371
- }
1372
- }
1373
- async scriviDeposito(key, value) {
1374
- this.verificaChiaveDeposito(key);
1375
- const json = analizzaJson(value);
1376
- if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
1377
- throw erroreConCodice(
1378
- "store_too_large",
1379
- "Shared store values must be valid JSON of at most 262144 bytes."
1380
- );
1381
- }
1382
- await this.usaDeposito((deposito) => deposito.set(key, json.valore));
1383
- }
1384
- async eliminaDeposito(key) {
1385
- this.verificaChiaveDeposito(key);
1386
- await this.usaDeposito((deposito) => deposito.delete(key));
1387
- }
1388
- async elencaDeposito(prefix) {
1389
- this.verificaPrefissoDeposito(prefix);
1390
- const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
1391
- if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
1392
- throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
1393
- }
1394
- return [...keys].sort().slice(0, 4096);
1395
- }
1396
- async incrementaDeposito(key, amount) {
1397
- this.verificaChiaveDeposito(key);
1398
- if (!Number.isSafeInteger(amount)) {
1399
- throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
1400
- }
1401
- const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
1402
- if (!Number.isSafeInteger(value)) {
1403
- throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
1404
- }
1405
- return value;
1406
- }
1407
1326
  messaggioCreatore(message) {
1408
1327
  const json = analizzaJson(message);
1409
1328
  if (!json.ok) throw new TypeError("Messages must be valid JSON.");
@@ -1430,7 +1349,6 @@ var NucleoStanza = class _NucleoStanza {
1430
1349
  this.adattatore.invia(player.connessione, message);
1431
1350
  }
1432
1351
  }
1433
- if (message.t !== "flush") this.adattatore.pubblica(message);
1434
1352
  }
1435
1353
  inviaErrore(player, code, message) {
1436
1354
  if (player.connected && player.connessione !== null) {
@@ -1467,6 +1385,7 @@ var NucleoStanza = class _NucleoStanza {
1467
1385
  const dati = this.richiediDati();
1468
1386
  return {
1469
1387
  id: dati.id,
1388
+ origin: dati.origin,
1470
1389
  seed: seedStanza(dati.id),
1471
1390
  status: dati.status,
1472
1391
  result: dati.result,
@@ -1475,18 +1394,16 @@ var NucleoStanza = class _NucleoStanza {
1475
1394
  tick: dati.tick,
1476
1395
  tickRate: dati.tickRate,
1477
1396
  serverTime: this.adattatore.ora(),
1478
- host: dati.hostId,
1479
1397
  countdownAt: dati.countdownAt,
1480
1398
  configuration: {
1481
1399
  players: { ...this.configurazione.players },
1482
- lobby: this.configurazione.lobby,
1483
1400
  persistent: this.manifest.persistent === true,
1484
1401
  requestRole: this.definizione.onRoleRequest !== void 0
1485
1402
  }
1486
1403
  };
1487
1404
  }
1488
1405
  inviaGiocatori() {
1489
- this.broadcast({ t: "players", players: this.giocatoriProtocollo(), host: this.richiediDati().hostId });
1406
+ this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
1490
1407
  }
1491
1408
  inviaStatus(at) {
1492
1409
  const dati = this.richiediDati();
@@ -1494,7 +1411,6 @@ var NucleoStanza = class _NucleoStanza {
1494
1411
  t: "status",
1495
1412
  rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1496
1413
  status: dati.status,
1497
- host: dati.hostId,
1498
1414
  countdownAt: dati.countdownAt,
1499
1415
  at,
1500
1416
  result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
@@ -1516,13 +1432,6 @@ var NucleoStanza = class _NucleoStanza {
1516
1432
  dati.statoSincronizzato = copiaJson(dati.state);
1517
1433
  dati.tickSincronizzato = dati.tick;
1518
1434
  }
1519
- iniziaReplay() {
1520
- if (!this.manifest.replays || !this.adattatore.inizioReplay) return;
1521
- const json = analizzaJson(this.richiediDati().state);
1522
- if (!json.ok || json.bytes > LIMITE_STATO) return;
1523
- this.inviaSnapshotTutti();
1524
- this.adattatore.inizioReplay(this.fotografia());
1525
- }
1526
1435
  inviaSnapshotTutti() {
1527
1436
  const dati = this.richiediDati();
1528
1437
  const stato = analizzaJson(dati.state);
@@ -1572,7 +1481,7 @@ var NucleoStanza = class _NucleoStanza {
1572
1481
  async concludiEvento() {
1573
1482
  await this.applicaAzioni();
1574
1483
  if (this.dati === null || this.dati.status === "ended") return;
1575
- if (this.dati.status === "finished" && this.dati.rivincita?.autoStart && this.prontiRivincita()) {
1484
+ if (this.dati.origin === "player" && this.dati.status === "finished" && this.dati.rivincita !== null && this.prontiRivincita()) {
1576
1485
  await this.avviaRivincita();
1577
1486
  return;
1578
1487
  }
@@ -1670,13 +1579,11 @@ var NucleoStanza = class _NucleoStanza {
1670
1579
  const dati = this.richiediDati();
1671
1580
  if (dati.status === "ended") return;
1672
1581
  const giaFinita = dati.status === "finished";
1582
+ if (dati.origin === "matchmaking" && record(result)?.error === void 0) rematch = true;
1673
1583
  dati.status = rematch ? "finished" : "ended";
1674
- dati.rivincita = rematch ? {
1675
- keepSetup: typeof rematch === "object" && rematch.keepSetup === true,
1676
- autoStart: typeof rematch === "object" && rematch.autoStart === true
1677
- } : null;
1584
+ dati.rivincita = rematch ? { keepSetup: typeof rematch === "object" && rematch.keepSetup === true } : null;
1678
1585
  dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
1679
- dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1586
+ dati.rivincitaFinoA = rematch ? this.adattatore.ora() + (dati.origin === "matchmaking" ? 8e3 : ATTESA_RIVINCITA_MS) : null;
1680
1587
  dati.timer = [];
1681
1588
  if (rematch) for (const player of dati.giocatori) player.ready = false;
1682
1589
  dati.countdownAt = null;
@@ -1754,6 +1661,10 @@ var NucleoStanza = class _NucleoStanza {
1754
1661
  async terminaSeInattiva() {
1755
1662
  if (this.dati?.status === "finished") {
1756
1663
  if (this.adattatore.ora() < (this.dati.rivincitaFinoA ?? 0)) return false;
1664
+ if (this.dati.origin === "matchmaking") {
1665
+ await this.avviaRivincita();
1666
+ return false;
1667
+ }
1757
1668
  await this.terminaInterna(this.dati.result);
1758
1669
  return true;
1759
1670
  }
@@ -2067,14 +1978,10 @@ var ArchivioNode = class _ArchivioNode {
2067
1978
  }
2068
1979
  };
2069
1980
  var AdattatoreNode = class {
2070
- constructor(storage, deposito, ritardoSpettatori, dailyDay) {
1981
+ constructor(storage, dailyDay) {
2071
1982
  this.storage = storage;
2072
- this.deposito = deposito;
2073
- this.ritardoSpettatori = ritardoSpettatori;
2074
1983
  this.dailyDay = dailyDay;
2075
1984
  this.connessioni = /* @__PURE__ */ new Map();
2076
- this.spettatori = /* @__PURE__ */ new Map();
2077
- this.timerSpettatori = /* @__PURE__ */ new Set();
2078
1985
  this.tickTimer = null;
2079
1986
  this.tickIntervallo = null;
2080
1987
  this.tickGenerazione = 0;
@@ -2082,6 +1989,8 @@ var AdattatoreNode = class {
2082
1989
  this.svegliaAt = null;
2083
1990
  this.eseguiTick = async () => void 0;
2084
1991
  this.eseguiSveglia = async () => void 0;
1992
+ this.network = new NetworkMeter();
1993
+ this.networkWarning = "ok";
2085
1994
  }
2086
1995
  collega(input) {
2087
1996
  this.eseguiTick = input.tick;
@@ -2093,65 +2002,21 @@ var AdattatoreNode = class {
2093
2002
  rimuovi(id) {
2094
2003
  this.connessioni.delete(id);
2095
2004
  }
2096
- aggiungiSpettatore(id, socket) {
2097
- this.spettatori.set(id, socket);
2098
- }
2099
- rimuoviSpettatore(id) {
2100
- this.spettatori.delete(id);
2101
- }
2102
- numeroSpettatori() {
2103
- return this.spettatori.size;
2104
- }
2105
- elencoSpettatori() {
2106
- return [...this.spettatori];
2107
- }
2108
2005
  elencoConnessioni() {
2109
2006
  return [...this.connessioni];
2110
2007
  }
2111
- invia(connessione, messaggio) {
2112
- this.connessioni.get(connessione)?.send(JSON.stringify(messaggio));
2113
- }
2114
- pubblica(messaggio) {
2115
- const testo = JSON.stringify(messaggio);
2116
- for (const [connessione] of this.spettatori) {
2117
- this.inviaSpettatore(connessione, testo);
2118
- if (messaggio.t === "status" && messaggio.status === "ended") {
2119
- this.chiudiSpettatoreRitardato(connessione);
2120
- }
2121
- }
2008
+ sendMeasured(socket, connection, text) {
2009
+ if (!socket) return;
2010
+ socket.send(text);
2011
+ this.network.record(connection, text);
2012
+ const report = this.network.sample();
2013
+ const warning = networkLevel(report.current);
2014
+ if (warning !== "ok" && warning !== this.networkWarning) process.stderr.write(`${networkMessage(report.current)}
2015
+ `);
2016
+ this.networkWarning = warning;
2122
2017
  }
2123
- inviaSpettatore(connessione, testo) {
2124
- this.accodaSpettatore(connessione, (socket) => {
2125
- socket.send(testo);
2126
- });
2127
- }
2128
- inviaSpettatoreSubito(connessione, testo) {
2129
- this.spettatori.get(connessione)?.send(testo);
2130
- }
2131
- chiudiSpettatore(connessione, codice, motivo) {
2132
- const socket = this.spettatori.get(connessione);
2133
- this.spettatori.delete(connessione);
2134
- socket?.close(codice, motivo);
2135
- }
2136
- chiudiSpettatoreRitardato(connessione) {
2137
- this.accodaSpettatore(connessione, (socket) => {
2138
- this.spettatori.delete(connessione);
2139
- socket.close(4004, "room_ended");
2140
- });
2141
- }
2142
- accodaSpettatore(connessione, azione) {
2143
- if (this.ritardoSpettatori === 0) {
2144
- const socket = this.spettatori.get(connessione);
2145
- if (socket !== void 0) azione(socket);
2146
- return;
2147
- }
2148
- const timer = setTimeout(() => {
2149
- this.timerSpettatori.delete(timer);
2150
- const socket = this.spettatori.get(connessione);
2151
- if (socket !== void 0) azione(socket);
2152
- }, this.ritardoSpettatori ?? RITARDO_SPETTATORI_MS);
2153
- this.timerSpettatori.add(timer);
2154
- timer.unref();
2018
+ invia(connessione, messaggio) {
2019
+ this.sendMeasured(this.connessioni.get(connessione), connessione, JSON.stringify(messaggio));
2155
2020
  }
2156
2021
  chiudi(connessione, codice, motivo) {
2157
2022
  this.connessioni.get(connessione)?.close(codice, motivo);
@@ -2191,8 +2056,6 @@ var AdattatoreNode = class {
2191
2056
  this.tickGenerazione += 1;
2192
2057
  if (this.tickTimer !== null) clearTimeout(this.tickTimer);
2193
2058
  if (this.svegliaTimer !== null) clearTimeout(this.svegliaTimer);
2194
- for (const timer of this.timerSpettatori) clearTimeout(timer);
2195
- this.timerSpettatori.clear();
2196
2059
  this.tickTimer = null;
2197
2060
  this.svegliaTimer = null;
2198
2061
  }
@@ -2242,8 +2105,11 @@ var StanzaNode = class {
2242
2105
  sveglia: () => this.serializza(() => nucleo.sveglia())
2243
2106
  });
2244
2107
  }
2245
- create(roomId, mode, creator) {
2246
- return this.serializza(() => this.nucleo.crea(roomId, mode, creator));
2108
+ network() {
2109
+ return this.adattatore.network.sample();
2110
+ }
2111
+ create(roomId, mode, creator, origin = "player") {
2112
+ return this.serializza(() => this.nucleo.crea(roomId, mode, creator, origin));
2247
2113
  }
2248
2114
  info() {
2249
2115
  return this.serializza(() => Promise.resolve(this.nucleo.info()));
@@ -2251,9 +2117,6 @@ var StanzaNode = class {
2251
2117
  canJoin(identity) {
2252
2118
  return this.serializza(() => Promise.resolve(this.nucleo.puoEntrare(identity)));
2253
2119
  }
2254
- canWatch() {
2255
- return this.serializza(() => Promise.resolve(this.permessoSpettatore()));
2256
- }
2257
2120
  async connect(socket, identity) {
2258
2121
  const connessione = randomUUID();
2259
2122
  this.adattatore.aggiungi(connessione, socket);
@@ -2284,28 +2147,6 @@ var StanzaNode = class {
2284
2147
  throw cause;
2285
2148
  }
2286
2149
  }
2287
- watch(socket, _identity) {
2288
- return this.serializza(async () => {
2289
- const permesso = this.permessoSpettatore();
2290
- if (!permesso.ok) return permesso;
2291
- const connessione = randomUUID();
2292
- this.adattatore.aggiungiSpettatore(connessione, socket);
2293
- socket.on("message", (message) => {
2294
- void this.serializza(() => this.riceviSpettatore(connessione, message));
2295
- });
2296
- socket.on("close", () => {
2297
- this.adattatore.rimuoviSpettatore(connessione);
2298
- this.frameFrequenza.delete(connessione);
2299
- });
2300
- const fotografia = this.nucleo.fotografia();
2301
- if (fotografia === null) {
2302
- this.adattatore.rimuoviSpettatore(connessione);
2303
- return { ok: false, code: "room_not_found" };
2304
- }
2305
- this.inviaWatching(connessione, fotografia);
2306
- return { ok: true };
2307
- });
2308
- }
2309
2150
  flush() {
2310
2151
  return this.serializza(() => this.nucleo.flush());
2311
2152
  }
@@ -2320,11 +2161,6 @@ var StanzaNode = class {
2320
2161
  socket.close(1001, "server_shutdown");
2321
2162
  await this.serializza(() => this.nucleo.disconnetti(connessione));
2322
2163
  }
2323
- for (const [connessione, socket] of this.adattatore.elencoSpettatori()) {
2324
- this.adattatore.rimuoviSpettatore(connessione);
2325
- this.frameFrequenza.delete(connessione);
2326
- socket.close(1001, "server_shutdown");
2327
- }
2328
2164
  }
2329
2165
  serializza(operazione) {
2330
2166
  const risultato = this.coda.then(operazione);
@@ -2368,74 +2204,9 @@ var StanzaNode = class {
2368
2204
  this.riconciliaRoster();
2369
2205
  return;
2370
2206
  }
2371
- await this.riceviVoce(connessione, player.id, player.role, message);
2372
- }
2373
- permessoSpettatore() {
2374
- const info = this.nucleo.info();
2375
- if (info === null) return { ok: false, code: "room_not_found" };
2376
- if (info.status === "ended") return { ok: false, code: "room_ended" };
2377
- if (this.manifest.spectators === null) {
2378
- return { ok: false, code: "spectators_disabled" };
2379
- }
2380
- if (this.adattatore.numeroSpettatori() >= MASSIMO_SPETTATORI) {
2381
- return { ok: false, code: "spectators_full" };
2382
- }
2383
- return { ok: true };
2207
+ await this.riceviVoce(connessione, player.id, message);
2384
2208
  }
2385
- inviaWatching(connessione, fotografia) {
2386
- this.adattatore.inviaSpettatore(connessione, JSON.stringify({
2387
- t: "watching",
2388
- ...fotografia,
2389
- delayMs: this.manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS
2390
- }));
2391
- }
2392
- async riceviSpettatore(connessione, frame) {
2393
- if (Buffer.byteLength(frame, "utf8") > MASSIMO_BYTE_FRAME_STANZA) {
2394
- this.adattatore.chiudiSpettatore(connessione, 4009, "message_too_large");
2395
- this.frameFrequenza.delete(connessione);
2396
- return;
2397
- }
2398
- const ora = Date.now();
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
- }
2410
- return;
2411
- }
2412
- let message = null;
2413
- try {
2414
- const value = JSON.parse(frame);
2415
- message = typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2416
- } catch {
2417
- }
2418
- if (message?.t === "ping" && typeof message.c === "number" && Number.isFinite(message.c)) {
2419
- this.adattatore.inviaSpettatoreSubito(
2420
- connessione,
2421
- JSON.stringify({ t: "pong", c: message.c, s: ora })
2422
- );
2423
- return;
2424
- }
2425
- if (message?.t === "resync") {
2426
- const fotografia = this.nucleo.fotografia();
2427
- if (fotografia !== null) this.inviaWatching(connessione, fotografia);
2428
- return;
2429
- }
2430
- if (message?.t === "leave") {
2431
- this.adattatore.chiudiSpettatore(connessione, 1e3, "left");
2432
- this.frameFrequenza.delete(connessione);
2433
- return;
2434
- }
2435
- this.adattatore.chiudiSpettatore(connessione, 4009, "bad_message");
2436
- this.frameFrequenza.delete(connessione);
2437
- }
2438
- async riceviVoce(connessione, playerId, role, value) {
2209
+ async riceviVoce(connessione, playerId, value) {
2439
2210
  const richiesta = this.richiestaVoce(value);
2440
2211
  if (richiesta === null) {
2441
2212
  this.inviaErroreVoce(connessione, value, "invalid_request", "The voice request is invalid.");
@@ -2483,10 +2254,6 @@ var StanzaNode = class {
2483
2254
  }
2484
2255
  if (richiesta.op === "publish") {
2485
2256
  const mic = richiesta.mic !== false;
2486
- if (role === "spectator" && mic) {
2487
- this.inviaErroreVoce(connessione, richiesta, "spectator", "Spectators cannot join voice.");
2488
- return;
2489
- }
2490
2257
  if (mic) {
2491
2258
  this.voceListeners.delete(playerId);
2492
2259
  this.voceRoster.set(playerId, {
@@ -2601,7 +2368,7 @@ var StanzaNode = class {
2601
2368
  let cambiato = false;
2602
2369
  for (const [playerId, peer] of this.voceRoster) {
2603
2370
  const player = this.nucleo.giocatoreConnesso(peer.connessione);
2604
- if (player?.id === playerId && player.role !== "spectator") continue;
2371
+ if (player?.id === playerId) continue;
2605
2372
  this.voceRoster.delete(playerId);
2606
2373
  cambiato = true;
2607
2374
  }
@@ -2637,10 +2404,9 @@ var StanzaNode = class {
2637
2404
  }
2638
2405
  };
2639
2406
  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.");
2407
+ if (options.dailyDay !== void 0 && !validDay(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
2641
2408
  const storage = await ArchivioNode.apri(options.storageFile ?? null);
2642
- const ritardoSpettatori = manifest.spectators === null ? null : manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS;
2643
- const adattatore = new AdattatoreNode(storage, options.deposito ?? null, ritardoSpettatori, options.dailyDay);
2409
+ const adattatore = new AdattatoreNode(storage, options.dailyDay);
2644
2410
  const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
2645
2411
  return new StanzaNode(nucleo, adattatore, manifest);
2646
2412
  }