@caisual/kit 0.3.0 → 0.5.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.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { FotografiaStanza } from '../protocollo.js';
1
2
  import type { GameDefinition, JsonValue, RoomStatus } from './server.js';
2
3
  export interface RoomManifest {
3
4
  id: string;
@@ -6,6 +7,7 @@ export interface RoomManifest {
6
7
  max: number;
7
8
  };
8
9
  lobby: boolean;
10
+ persistent?: boolean;
9
11
  roles: Array<{
10
12
  id: string;
11
13
  min: number;
@@ -30,6 +32,7 @@ export interface Esito {
30
32
  connessione: string;
31
33
  testo: string;
32
34
  }>;
35
+ pubblici: string[];
33
36
  chiusure: Array<{
34
37
  connessione: string;
35
38
  codice: number;
@@ -38,6 +41,7 @@ export interface Esito {
38
41
  sveglia: number | null;
39
42
  tick: boolean;
40
43
  tickRate: number;
44
+ status: RoomStatus | null;
41
45
  }
42
46
  export interface InfoStanza {
43
47
  roomId: string;
@@ -45,6 +49,7 @@ export interface InfoStanza {
45
49
  players: number;
46
50
  max: number;
47
51
  mode: string | null;
52
+ member: boolean;
48
53
  }
49
54
  export type EsitoIngresso = {
50
55
  ok: true;
@@ -70,9 +75,9 @@ export interface FacetStanza {
70
75
  creator: IdentitaGiocatore;
71
76
  }): Promise<Esito & {
72
77
  ok: boolean;
73
- status: 'lobby' | 'playing';
74
78
  }>;
75
- info(): Promise<InfoStanza | null>;
79
+ info(playerId?: string): Promise<InfoStanza | null>;
80
+ fotografia(): Promise<FotografiaStanza | null>;
76
81
  puoEntrare(identita: IdentitaGiocatore): Promise<EsitoIngresso>;
77
82
  entra(identita: IdentitaGiocatore, connessione: string): Promise<Esito>;
78
83
  ricevi(connessione: string, testo: string): Promise<Esito>;
package/dist/runtime.js CHANGED
@@ -152,9 +152,8 @@ var COSTANTI_SHA256 = [
152
152
  function ruotaDestra(value, bits) {
153
153
  return value >>> bits | value << 32 - bits;
154
154
  }
155
- function seedGiornata(slug, day) {
156
- const testo = `caisual:${slug}:${day}`;
157
- const bytes = Array.from(testo, (carattere) => carattere.charCodeAt(0));
155
+ function hashSeed(testo) {
156
+ const bytes = Array.from(new TextEncoder().encode(testo));
158
157
  const bitLength = bytes.length * 8;
159
158
  bytes.push(128);
160
159
  while (bytes.length % 64 !== 56) bytes.push(0);
@@ -217,6 +216,12 @@ function seedGiornata(slug, day) {
217
216
  }
218
217
  return h0 >>> 0;
219
218
  }
219
+ function seedGiornata(slug, day) {
220
+ return hashSeed(`caisual:${slug}:${day}`);
221
+ }
222
+ function seedStanza(roomId) {
223
+ return hashSeed(`caisual:room:${roomId}`);
224
+ }
220
225
 
221
226
  // src/stanza/nucleo.ts
222
227
  var CHIAVE_NUCLEO = "nucleo";
@@ -224,13 +229,25 @@ var PREFISSO_SAVE = "save:";
224
229
  var LIMITE_FRAME = 16 * 1024;
225
230
  var LIMITE_STATO = 256 * 1024;
226
231
  var LIMITE_SAVE = 128 * 1024;
232
+ var LIMITE_DEPOSITO = 64 * 1024;
233
+ var LIMITE_OPERAZIONI_DEPOSITO = 120;
227
234
  var GRAZIA_MS = 6e4;
228
235
  var STANZA_VUOTA_MS = 5 * 6e4;
229
236
  var COUNTDOWN_MS = 3e3;
230
237
  var RIPOSO_TICK_MS = 3e4;
231
238
  var INATTIVITA_MS = 10 * 6e4;
239
+ var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
232
240
  var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
241
+ var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
233
242
  var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
243
+ var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
244
+ "store_invalid_key",
245
+ "store_too_large",
246
+ "store_full",
247
+ "store_not_integer",
248
+ "store_unavailable",
249
+ "store_rate_limited"
250
+ ]);
234
251
  function record(value) {
235
252
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
236
253
  }
@@ -253,6 +270,9 @@ function copiaGiocatore(player) {
253
270
  function copiaJson(value) {
254
271
  return JSON.parse(JSON.stringify(value));
255
272
  }
273
+ function erroreConCodice(code, message) {
274
+ return Object.assign(new Error(message), { code });
275
+ }
256
276
  function codiceIngresso(code) {
257
277
  if (code === "room_not_found") return 4001;
258
278
  if (code === "room_full") return 4e3;
@@ -265,6 +285,7 @@ var NucleoStanza = class _NucleoStanza {
265
285
  this.adattatore = adattatore;
266
286
  this.dati = null;
267
287
  this.frequenza = /* @__PURE__ */ new Map();
288
+ this.frequenzaDeposito = [];
268
289
  this.kickRichiesti = /* @__PURE__ */ new Set();
269
290
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
270
291
  this.fineRichiesta = null;
@@ -284,6 +305,9 @@ var NucleoStanza = class _NucleoStanza {
284
305
  get id() {
285
306
  return nucleo.richiediDati().id;
286
307
  },
308
+ get seed() {
309
+ return seedStanza(nucleo.richiediDati().id);
310
+ },
287
311
  get mode() {
288
312
  return nucleo.richiediDati().mode;
289
313
  },
@@ -293,6 +317,12 @@ var NucleoStanza = class _NucleoStanza {
293
317
  get tick() {
294
318
  return nucleo.richiediDati().tick;
295
319
  },
320
+ get tickRate() {
321
+ return nucleo.richiediDati().tickRate;
322
+ },
323
+ get result() {
324
+ return nucleo.richiediDati().result;
325
+ },
296
326
  get state() {
297
327
  return nucleo.richiediDati().state;
298
328
  },
@@ -316,6 +346,12 @@ var NucleoStanza = class _NucleoStanza {
316
346
  kick(player) {
317
347
  nucleo.kickRichiesti.add(idGiocatore(player));
318
348
  },
349
+ setRole(player, role) {
350
+ nucleo.impostaRuoloDalServer(idGiocatore(player), role);
351
+ },
352
+ setTeam(player, team) {
353
+ nucleo.impostaSquadraDalServer(idGiocatore(player), team);
354
+ },
319
355
  end(result) {
320
356
  nucleo.richiediFine(result);
321
357
  },
@@ -325,6 +361,23 @@ var NucleoStanza = class _NucleoStanza {
325
361
  load(key) {
326
362
  return nucleo.caricaSave(key);
327
363
  },
364
+ shared: {
365
+ get(key) {
366
+ return nucleo.leggiDeposito(key);
367
+ },
368
+ set(key, value) {
369
+ return nucleo.scriviDeposito(key, value);
370
+ },
371
+ delete(key) {
372
+ return nucleo.eliminaDeposito(key);
373
+ },
374
+ list(prefix) {
375
+ return nucleo.elencaDeposito(prefix);
376
+ },
377
+ increment(key, amount = 1) {
378
+ return nucleo.incrementaDeposito(key, amount);
379
+ }
380
+ },
328
381
  schedule(milliseconds, handler, payload) {
329
382
  nucleo.pianifica(milliseconds, handler, payload);
330
383
  },
@@ -339,8 +392,14 @@ var NucleoStanza = class _NucleoStanza {
339
392
  get mode() {
340
393
  return nucleo.manifest.voice ?? "none";
341
394
  },
395
+ setGain(listener, speaker, gain) {
396
+ nucleo.impostaGuadagno(idGiocatore(listener), idGiocatore(speaker), gain);
397
+ },
342
398
  setProximity(a, b, gain) {
343
- nucleo.impostaProssimita(idGiocatore(a), idGiocatore(b), gain);
399
+ const primo = idGiocatore(a);
400
+ const secondo = idGiocatore(b);
401
+ nucleo.impostaGuadagno(primo, secondo, gain);
402
+ nucleo.impostaGuadagno(secondo, primo, gain);
344
403
  }
345
404
  }
346
405
  };
@@ -365,7 +424,7 @@ var NucleoStanza = class _NucleoStanza {
365
424
  return nucleo;
366
425
  }
367
426
  static verificaManifest(manifest) {
368
- 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" || !Array.isArray(manifest.roles) || !Array.isArray(manifest.modes) || manifest.voice !== void 0 && !["none", "room", "team", "proximity"].includes(manifest.voice)) {
427
+ 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)) {
369
428
  throw new TypeError("The room manifest is invalid.");
370
429
  }
371
430
  }
@@ -428,16 +487,25 @@ var NucleoStanza = class _NucleoStanza {
428
487
  await this.persistiEProgramma();
429
488
  return true;
430
489
  }
431
- info() {
490
+ info(playerId) {
432
491
  if (this.dati === null) return null;
433
492
  return {
434
493
  roomId: this.dati.id,
435
494
  status: this.dati.status,
436
- players: this.dati.giocatori.filter(
495
+ players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
437
496
  (player) => player.connected || player.graziaFinoA !== null
438
497
  ).length,
439
498
  max: this.manifest.players.max,
440
- mode: this.dati.mode
499
+ mode: this.dati.mode,
500
+ member: playerId === void 0 ? false : this.dati.giocatori.some((player) => player.id === playerId)
501
+ };
502
+ }
503
+ fotografia() {
504
+ if (this.dati === null) return null;
505
+ return {
506
+ room: this.stanzaProtocollo(),
507
+ players: this.giocatoriProtocollo(),
508
+ state: this.dati.state
441
509
  };
442
510
  }
443
511
  giocatoreConnesso(connessione) {
@@ -483,7 +551,6 @@ var NucleoStanza = class _NucleoStanza {
483
551
  seq: 0
484
552
  };
485
553
  dati.giocatori.push(player);
486
- dati.hostId ??= player.id;
487
554
  } else {
488
555
  if (player.connected && player.connessione !== null && player.connessione !== connessione) {
489
556
  this.adattatore.chiudi(player.connessione, 4006, "replaced");
@@ -495,6 +562,7 @@ var NucleoStanza = class _NucleoStanza {
495
562
  player.connessione = connessione;
496
563
  player.seq = 0;
497
564
  }
565
+ dati.hostId ??= player.id;
498
566
  dati.vuotaDa = null;
499
567
  dati.ultimoInputAt = ora;
500
568
  const primaConnessione = !this.manifest.lobby && dati.status === "lobby";
@@ -528,6 +596,7 @@ var NucleoStanza = class _NucleoStanza {
528
596
  player.connected = false;
529
597
  player.connessione = null;
530
598
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
599
+ if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
531
600
  this.frequenza.delete(connessione);
532
601
  if (this.dati.hostId === player.id) this.assegnaHost();
533
602
  this.verificaCountdown();
@@ -597,7 +666,8 @@ var NucleoStanza = class _NucleoStanza {
597
666
  if (typeof message.role !== "string") return this.messaggioErrato(player);
598
667
  if (!this.inLobby(player)) return;
599
668
  this.dati.ultimoInputAt = ora;
600
- this.scegliRuolo(player, message.role);
669
+ const errore = this.cambiaRuolo(player, message.role);
670
+ if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
601
671
  await this.persistiEProgramma();
602
672
  return;
603
673
  }
@@ -605,7 +675,8 @@ var NucleoStanza = class _NucleoStanza {
605
675
  if (!Number.isInteger(message.team)) return this.messaggioErrato(player);
606
676
  if (!this.inLobby(player)) return;
607
677
  this.dati.ultimoInputAt = ora;
608
- this.scegliSquadra(player, message.team);
678
+ const errore = this.cambiaSquadra(player, message.team);
679
+ if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
609
680
  await this.persistiEProgramma();
610
681
  return;
611
682
  }
@@ -695,7 +766,10 @@ var NucleoStanza = class _NucleoStanza {
695
766
  const scaduti = this.dati.giocatori.filter(
696
767
  (player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
697
768
  );
698
- for (const player of scaduti) await this.rimuoviGiocatore(player, "timeout");
769
+ for (const player of scaduti) {
770
+ if (this.manifest.persistent === true) player.graziaFinoA = null;
771
+ else await this.rimuoviGiocatore(player, "timeout");
772
+ }
699
773
  if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
700
774
  const errore = this.erroreMinimi();
701
775
  if (errore !== null) {
@@ -755,6 +829,7 @@ var NucleoStanza = class _NucleoStanza {
755
829
  player.connected = false;
756
830
  player.connessione = null;
757
831
  player.graziaFinoA = ora + GRAZIA_MS;
832
+ if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
758
833
  cambiato = true;
759
834
  }
760
835
  }
@@ -798,37 +873,52 @@ var NucleoStanza = class _NucleoStanza {
798
873
  this.inviaErrore(player, "not_in_lobby", "This action is only available in the lobby.");
799
874
  return false;
800
875
  }
801
- scegliRuolo(player, roleId) {
876
+ cambiaRuolo(player, roleId) {
802
877
  const ruolo = this.manifest.roles.find((item) => item.id === roleId);
803
878
  if (ruolo === void 0 && roleId !== "spectator") {
804
- this.inviaErrore(player, "invalid_role", "This role does not exist.");
805
- return;
879
+ return { code: "invalid_role", message: "This role does not exist." };
806
880
  }
807
881
  const occupati = this.richiediDati().giocatori.filter(
808
882
  (item) => item.id !== player.id && item.role === roleId
809
883
  ).length;
810
884
  if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
811
- this.inviaErrore(player, "role_full", "This role is full.");
812
- return;
885
+ return { code: "role_full", message: "This role is full." };
813
886
  }
814
887
  player.role = roleId;
815
888
  if (roleId === "spectator") player.team = null;
816
889
  else if (player.team === null) player.team = this.squadraAutomatica();
817
- player.ready = false;
890
+ if (this.richiediDati().status === "lobby") player.ready = false;
818
891
  this.inviaGiocatori();
892
+ return null;
819
893
  }
820
- scegliSquadra(player, team) {
821
- if (this.manifest.teams === null || team < 1 || team > this.manifest.teams.max) {
822
- this.inviaErrore(player, "invalid_team", "This team does not exist.");
823
- return;
894
+ cambiaSquadra(player, team) {
895
+ if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
896
+ return { code: "invalid_team", message: "This team does not exist." };
824
897
  }
825
898
  if (player.role === "spectator") {
826
- this.inviaErrore(player, "spectator", "Spectators cannot join a team.");
827
- return;
899
+ return { code: "spectator", message: "Spectators cannot join a team." };
828
900
  }
829
901
  player.team = team;
830
- player.ready = false;
902
+ if (this.richiediDati().status === "lobby") player.ready = false;
831
903
  this.inviaGiocatori();
904
+ return null;
905
+ }
906
+ impostaRuoloDalServer(playerId, roleId) {
907
+ const player = this.giocatorePerModificaDalServer(playerId);
908
+ const errore = this.cambiaRuolo(player, roleId);
909
+ if (errore !== null) throw erroreConCodice(errore.code, errore.message);
910
+ }
911
+ impostaSquadraDalServer(playerId, team) {
912
+ const player = this.giocatorePerModificaDalServer(playerId);
913
+ const errore = this.cambiaSquadra(player, team);
914
+ if (errore !== null) throw erroreConCodice(errore.code, errore.message);
915
+ }
916
+ giocatorePerModificaDalServer(playerId) {
917
+ const dati = this.richiediDati();
918
+ if (dati.status === "ended") throw new Error("The room has ended.");
919
+ const player = dati.giocatori.find((item) => item.id === playerId);
920
+ if (player === void 0) throw erroreConCodice("player_not_found", "Player not found.");
921
+ return player;
832
922
  }
833
923
  erroreMinimi() {
834
924
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
@@ -972,6 +1062,91 @@ var NucleoStanza = class _NucleoStanza {
972
1062
  if (!json.ok) throw new Error("The saved value is invalid.");
973
1063
  return json.valore;
974
1064
  }
1065
+ verificaChiaveDeposito(key) {
1066
+ if (typeof key !== "string" || !CHIAVE.test(key)) {
1067
+ throw erroreConCodice(
1068
+ "store_invalid_key",
1069
+ "Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
1070
+ );
1071
+ }
1072
+ }
1073
+ verificaPrefissoDeposito(prefix) {
1074
+ if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
1075
+ throw erroreConCodice(
1076
+ "store_invalid_key",
1077
+ "Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
1078
+ );
1079
+ }
1080
+ }
1081
+ contaOperazioneDeposito() {
1082
+ const ora = this.adattatore.ora();
1083
+ this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
1084
+ if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
1085
+ throw erroreConCodice(
1086
+ "store_rate_limited",
1087
+ "The shared store allows at most 120 operations per minute for each room."
1088
+ );
1089
+ }
1090
+ this.frequenzaDeposito.push(ora);
1091
+ }
1092
+ async usaDeposito(operazione) {
1093
+ this.contaOperazioneDeposito();
1094
+ const deposito = this.adattatore.deposito;
1095
+ if (deposito === null) {
1096
+ throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1097
+ }
1098
+ try {
1099
+ return await operazione(deposito);
1100
+ } catch (cause) {
1101
+ const code = cause instanceof Error ? cause.code : void 0;
1102
+ if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
1103
+ throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1104
+ }
1105
+ }
1106
+ async leggiDeposito(key) {
1107
+ this.verificaChiaveDeposito(key);
1108
+ const value = await this.usaDeposito((deposito) => deposito.get(key));
1109
+ if (value === null) return null;
1110
+ try {
1111
+ return JSON.parse(JSON.stringify(value));
1112
+ } catch {
1113
+ throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
1114
+ }
1115
+ }
1116
+ async scriviDeposito(key, value) {
1117
+ this.verificaChiaveDeposito(key);
1118
+ const json = analizzaJson(value);
1119
+ if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
1120
+ throw erroreConCodice(
1121
+ "store_too_large",
1122
+ "Shared store values must be valid JSON of at most 65536 bytes."
1123
+ );
1124
+ }
1125
+ await this.usaDeposito((deposito) => deposito.set(key, json.valore));
1126
+ }
1127
+ async eliminaDeposito(key) {
1128
+ this.verificaChiaveDeposito(key);
1129
+ await this.usaDeposito((deposito) => deposito.delete(key));
1130
+ }
1131
+ async elencaDeposito(prefix) {
1132
+ this.verificaPrefissoDeposito(prefix);
1133
+ const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
1134
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
1135
+ throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
1136
+ }
1137
+ return [...keys].sort().slice(0, 1024);
1138
+ }
1139
+ async incrementaDeposito(key, amount) {
1140
+ this.verificaChiaveDeposito(key);
1141
+ if (!Number.isSafeInteger(amount)) {
1142
+ throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
1143
+ }
1144
+ const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
1145
+ if (!Number.isSafeInteger(value)) {
1146
+ throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
1147
+ }
1148
+ return value;
1149
+ }
975
1150
  broadcastCreatore(message) {
976
1151
  const json = analizzaJson(message);
977
1152
  if (!json.ok) throw new TypeError("Messages must be valid JSON.");
@@ -992,6 +1167,7 @@ var NucleoStanza = class _NucleoStanza {
992
1167
  this.adattatore.invia(player.connessione, message);
993
1168
  }
994
1169
  }
1170
+ if (message.t !== "flush") this.adattatore.pubblica(message);
995
1171
  }
996
1172
  inviaErrore(player, code, message) {
997
1173
  if (player.connected && player.connessione !== null) {
@@ -1015,15 +1191,7 @@ var NucleoStanza = class _NucleoStanza {
1015
1191
  this.adattatore.invia(player.connessione, {
1016
1192
  t: "welcome",
1017
1193
  you: player.id,
1018
- room: {
1019
- id: dati.id,
1020
- status: dati.status,
1021
- mode: dati.mode,
1022
- tick: dati.tick,
1023
- tickRate: dati.tickRate,
1024
- serverTime: this.adattatore.ora(),
1025
- host: dati.hostId
1026
- },
1194
+ room: this.stanzaProtocollo(),
1027
1195
  players: this.giocatoriProtocollo(),
1028
1196
  state: dati.state
1029
1197
  });
@@ -1032,6 +1200,19 @@ var NucleoStanza = class _NucleoStanza {
1032
1200
  this.adattatore.invia(player.connessione, { t: "voice", op: "gain", gains: { ...gains } });
1033
1201
  }
1034
1202
  }
1203
+ stanzaProtocollo() {
1204
+ const dati = this.richiediDati();
1205
+ return {
1206
+ id: dati.id,
1207
+ seed: seedStanza(dati.id),
1208
+ status: dati.status,
1209
+ mode: dati.mode,
1210
+ tick: dati.tick,
1211
+ tickRate: dati.tickRate,
1212
+ serverTime: this.adattatore.ora(),
1213
+ host: dati.hostId
1214
+ };
1215
+ }
1035
1216
  inviaGiocatori() {
1036
1217
  this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
1037
1218
  }
@@ -1117,16 +1298,15 @@ var NucleoStanza = class _NucleoStanza {
1117
1298
  }
1118
1299
  return stato;
1119
1300
  }
1120
- impostaProssimita(a, b, gain) {
1121
- if ((this.manifest.voice ?? "none") !== "proximity") return;
1301
+ impostaGuadagno(listener, speaker, gain) {
1302
+ if ((this.manifest.voice ?? "none") === "none") return;
1122
1303
  const dati = this.richiediDati();
1123
- if (!dati.giocatori.some((player) => player.id === a) || !dati.giocatori.some((player) => player.id === b)) throw new Error("Player not found.");
1304
+ if (!dati.giocatori.some((player) => player.id === listener) || !dati.giocatori.some((player) => player.id === speaker)) throw new Error("Player not found.");
1124
1305
  if (Number.isNaN(gain)) throw new TypeError("Voice gain must be a number.");
1125
- if (a === b) return;
1306
+ if (listener === speaker) return;
1126
1307
  const valore = Math.round(Math.min(1, Math.max(0, gain)) * 100) / 100;
1127
1308
  dati.voceGuadagni ??= {};
1128
- this.salvaGuadagno(a, b, valore);
1129
- this.salvaGuadagno(b, a, valore);
1309
+ this.salvaGuadagno(listener, speaker, valore);
1130
1310
  }
1131
1311
  salvaGuadagno(playerId, altroId, valore) {
1132
1312
  const dati = this.richiediDati();
@@ -1250,6 +1430,11 @@ var NucleoStanza = class _NucleoStanza {
1250
1430
  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;
1251
1431
  }
1252
1432
  async terminaSeInattiva() {
1433
+ if (this.manifest.persistent === true) {
1434
+ if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
1435
+ await this.terminaInterna({ error: "expired" });
1436
+ return true;
1437
+ }
1253
1438
  if (this.dati?.status !== "playing" || this.adattatore.ora() < this.dati.ultimoInputAt + INATTIVITA_MS) return false;
1254
1439
  await this.terminaInterna({ error: "idle" });
1255
1440
  return true;
@@ -1264,7 +1449,13 @@ var NucleoStanza = class _NucleoStanza {
1264
1449
  this.serveTick() ? 1e3 / this.dati.tickRate : null
1265
1450
  );
1266
1451
  const prossime = [];
1267
- if (this.dati.status === "playing") prossime.push(this.dati.ultimoInputAt + INATTIVITA_MS);
1452
+ if (this.manifest.persistent === true) {
1453
+ prossime.push(
1454
+ Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
1455
+ );
1456
+ } else if (this.dati.status === "playing") {
1457
+ prossime.push(this.dati.ultimoInputAt + INATTIVITA_MS);
1458
+ }
1268
1459
  if (this.dati.countdownAt !== null) prossime.push(this.dati.countdownAt);
1269
1460
  for (const player of this.dati.giocatori) {
1270
1461
  if (!player.connected && player.graziaFinoA !== null) prossime.push(player.graziaFinoA);
@@ -1297,16 +1488,18 @@ var ArchivioFacet = class {
1297
1488
  }
1298
1489
  };
1299
1490
  var AdattatoreFacet = class {
1300
- constructor(archivio, tickRate) {
1491
+ constructor(archivio, tickRate, deposito) {
1301
1492
  this.connessioni = /* @__PURE__ */ new Set();
1302
1493
  this.cpuMessaggiOltreCento = 0;
1303
1494
  this.frames = [];
1495
+ this.pubblici = [];
1304
1496
  this.chiusure = [];
1305
1497
  this.sveglia = null;
1306
1498
  this.tick = false;
1307
1499
  this.salvato = "";
1308
1500
  this.storage = new ArchivioFacet(archivio);
1309
1501
  this.tickRate = tickRate;
1502
+ this.deposito = deposito;
1310
1503
  }
1311
1504
  async ripristina() {
1312
1505
  const dati = await this.storage.get(CHIAVE_ADATTATORE);
@@ -1330,6 +1523,9 @@ var AdattatoreFacet = class {
1330
1523
  invia(connessione, messaggio) {
1331
1524
  this.frames.push({ connessione, testo: JSON.stringify(messaggio) });
1332
1525
  }
1526
+ pubblica(messaggio) {
1527
+ this.pubblici.push(JSON.stringify(messaggio));
1528
+ }
1333
1529
  chiudi(connessione, codice, motivo) {
1334
1530
  this.chiusure.push({ connessione, codice, motivo });
1335
1531
  this.connessioni.delete(connessione);
@@ -1350,15 +1546,18 @@ var AdattatoreFacet = class {
1350
1546
  async programmaSveglia(ora) {
1351
1547
  this.sveglia = ora;
1352
1548
  }
1353
- esito() {
1549
+ esito(status) {
1354
1550
  const risultato = {
1355
1551
  frames: this.frames,
1552
+ pubblici: this.pubblici,
1356
1553
  chiusure: this.chiusure,
1357
1554
  sveglia: this.sveglia,
1358
1555
  tick: this.tick,
1359
- tickRate: this.tickRate
1556
+ tickRate: this.tickRate,
1557
+ status
1360
1558
  };
1361
1559
  this.frames = [];
1560
+ this.pubblici = [];
1362
1561
  this.chiusure = [];
1363
1562
  return risultato;
1364
1563
  }
@@ -1372,7 +1571,8 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1372
1571
  constructor(stato, ambiente) {
1373
1572
  super(stato, ambiente);
1374
1573
  this.#roomId = typeof stato.id === "string" ? stato.id : stato.id.name ?? stato.id.toString();
1375
- const adattatore = new AdattatoreFacet(stato.storage, definizione.tickRate);
1574
+ const deposito = ambiente?.DEPOSITO ?? null;
1575
+ const adattatore = new AdattatoreFacet(stato.storage, definizione.tickRate, deposito);
1376
1576
  this.#adattatore = adattatore;
1377
1577
  const misurata = Object.create(definizione);
1378
1578
  if (definizione.onMessage !== void 0) {
@@ -1402,7 +1602,7 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1402
1602
  return this.#serializza(async (nucleo) => {
1403
1603
  await operazione(nucleo);
1404
1604
  await this.#adattatore.persisti();
1405
- return this.#adattatore.esito();
1605
+ return this.#adattatore.esito(nucleo.info()?.status ?? null);
1406
1606
  });
1407
1607
  }
1408
1608
  crea(input) {
@@ -1410,14 +1610,16 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1410
1610
  const ok = await nucleo.crea(this.#roomId, input.mode, input.creator);
1411
1611
  await this.#adattatore.persisti();
1412
1612
  return {
1413
- ...this.#adattatore.esito(),
1414
- ok,
1415
- status: nucleo.info()?.status === "playing" ? "playing" : "lobby"
1613
+ ...this.#adattatore.esito(nucleo.info()?.status ?? null),
1614
+ ok
1416
1615
  };
1417
1616
  });
1418
1617
  }
1419
- info() {
1420
- return this.#serializza((nucleo) => nucleo.info());
1618
+ info(playerId) {
1619
+ return this.#serializza((nucleo) => nucleo.info(playerId));
1620
+ }
1621
+ fotografia() {
1622
+ return this.#serializza((nucleo) => nucleo.fotografia());
1421
1623
  }
1422
1624
  puoEntrare(identita) {
1423
1625
  return this.#serializza((nucleo) => nucleo.puoEntrare(identita));
package/dist/server.d.ts CHANGED
@@ -4,6 +4,13 @@ export type JsonValue = null | boolean | number | string | JsonValue[] | {
4
4
  export type RoomStatus = 'lobby' | 'countdown' | 'playing' | 'ended';
5
5
  export type VoiceMode = 'none' | 'room' | 'team' | 'proximity';
6
6
  export type LeaveReason = 'left' | 'timeout' | 'kicked';
7
+ export interface SharedGameStore {
8
+ get(key: string): Promise<JsonValue | null>;
9
+ set(key: string, value: JsonValue): Promise<void>;
10
+ delete(key: string): Promise<void>;
11
+ list(prefix?: string): Promise<string[]>;
12
+ increment(key: string, amount?: number): Promise<number>;
13
+ }
7
14
  export interface Player {
8
15
  readonly id: string;
9
16
  readonly name: string;
@@ -14,18 +21,24 @@ export interface Player {
14
21
  }
15
22
  export interface Room<State extends JsonValue = JsonValue> {
16
23
  readonly id: string;
24
+ readonly seed: number;
17
25
  readonly mode: string | null;
18
26
  readonly status: RoomStatus;
19
27
  readonly tick: number;
28
+ readonly tickRate: number;
29
+ readonly result: JsonValue | null;
20
30
  state: State;
21
31
  readonly players: readonly Player[];
22
32
  readonly host: Player | null;
23
33
  broadcast(message: JsonValue): void;
24
34
  send(player: Player | string, message: JsonValue): void;
25
35
  kick(player: Player | string): void;
36
+ setRole(player: Player | string, role: string): void;
37
+ setTeam(player: Player | string, team: number): void;
26
38
  end(result: JsonValue): void;
27
39
  save(key: string, value: JsonValue): Promise<void>;
28
40
  load(key: string): Promise<JsonValue | null>;
41
+ readonly shared: SharedGameStore;
29
42
  schedule(milliseconds: number, handler: string, payload: JsonValue): void;
30
43
  readonly board: {
31
44
  submit(player: Player | string, board: string, score: number, options?: {
@@ -41,6 +54,7 @@ export interface Room<State extends JsonValue = JsonValue> {
41
54
  };
42
55
  readonly voice: {
43
56
  readonly mode: VoiceMode;
57
+ setGain(listener: Player | string, speaker: Player | string, gain: number): void;
44
58
  setProximity(a: Player | string, b: Player | string, gain: number): void;
45
59
  };
46
60
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caisual/kit",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Client and server kit for Caisual games",
5
5
  "type": "module",
6
6
  "files": [
@@ -43,6 +43,7 @@
43
43
  "test": "pnpm build && vitest run && WRANGLER_LOG_PATH=/tmp/caisual-kit-wrangler.log vitest run --config vitest.workers.config.ts"
44
44
  },
45
45
  "devDependencies": {
46
+ "@caisual/contracts": "workspace:*",
46
47
  "@cloudflare/vitest-pool-workers": "^0.20.3",
47
48
  "@types/node": "^26.2.0",
48
49
  "esbuild": "^0.28.1",