@caisual/kit 0.1.0 → 0.4.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/kit.d.ts +86 -0
- package/dist/kit.js +1789 -33
- package/dist/node.d.ts +77 -0
- package/dist/node.js +2131 -0
- package/dist/runtime.d.ts +108 -0
- package/dist/runtime.js +1638 -0
- package/dist/server.d.ts +71 -0
- package/dist/server.js +38 -0
- package/package.json +34 -6
package/dist/kit.js
CHANGED
|
@@ -1,4 +1,169 @@
|
|
|
1
|
-
// Caisual game kit v0.
|
|
1
|
+
// Caisual game kit v0.4.0
|
|
2
|
+
|
|
3
|
+
// ../contracts/src/slug.ts
|
|
4
|
+
var NOMI_RISERVATI = [
|
|
5
|
+
"www",
|
|
6
|
+
"api",
|
|
7
|
+
"app",
|
|
8
|
+
"play",
|
|
9
|
+
"live",
|
|
10
|
+
"multi",
|
|
11
|
+
"cdn",
|
|
12
|
+
"assets",
|
|
13
|
+
"static",
|
|
14
|
+
"mail",
|
|
15
|
+
"mx",
|
|
16
|
+
"ns1",
|
|
17
|
+
"ns2",
|
|
18
|
+
"autodiscover",
|
|
19
|
+
"_dmarc",
|
|
20
|
+
"admin",
|
|
21
|
+
"login",
|
|
22
|
+
"account",
|
|
23
|
+
"auth",
|
|
24
|
+
"pay",
|
|
25
|
+
"secure",
|
|
26
|
+
"support",
|
|
27
|
+
"help",
|
|
28
|
+
"blog",
|
|
29
|
+
"status",
|
|
30
|
+
"dev",
|
|
31
|
+
"staging",
|
|
32
|
+
"test",
|
|
33
|
+
"caisual",
|
|
34
|
+
"shipz"
|
|
35
|
+
];
|
|
36
|
+
var RISERVATI = new Set(NOMI_RISERVATI);
|
|
37
|
+
|
|
38
|
+
// ../contracts/src/device.ts
|
|
39
|
+
function deviceTier(report) {
|
|
40
|
+
if (report.gpu !== "hardware" || report.memoryMb !== null && report.memoryMb <= 2048) return "low";
|
|
41
|
+
if (report.mobile || report.memoryMb !== null && report.memoryMb <= 4096 || report.cores !== null && report.cores <= 4) return "mid";
|
|
42
|
+
return "high";
|
|
43
|
+
}
|
|
44
|
+
function perdiContesto(context) {
|
|
45
|
+
try {
|
|
46
|
+
context?.getExtension("WEBGL_lose_context")?.loseContext();
|
|
47
|
+
} catch {
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function valoriSincroni(ambiente) {
|
|
51
|
+
let navigator2;
|
|
52
|
+
try {
|
|
53
|
+
navigator2 = ambiente.navigator;
|
|
54
|
+
} catch {
|
|
55
|
+
navigator2 = void 0;
|
|
56
|
+
}
|
|
57
|
+
let memoryMb = null;
|
|
58
|
+
try {
|
|
59
|
+
const memory = navigator2?.deviceMemory;
|
|
60
|
+
const converted = typeof memory === "number" ? memory * 1024 : NaN;
|
|
61
|
+
if (Number.isFinite(converted)) memoryMb = converted;
|
|
62
|
+
} catch {
|
|
63
|
+
memoryMb = null;
|
|
64
|
+
}
|
|
65
|
+
let cores = null;
|
|
66
|
+
try {
|
|
67
|
+
const value = navigator2?.hardwareConcurrency;
|
|
68
|
+
if (typeof value === "number" && Number.isFinite(value)) cores = value;
|
|
69
|
+
} catch {
|
|
70
|
+
cores = null;
|
|
71
|
+
}
|
|
72
|
+
let mobile = false;
|
|
73
|
+
try {
|
|
74
|
+
mobile = typeof navigator2?.userAgentData?.mobile === "boolean" ? navigator2.userAgentData.mobile : /Android|iPhone|iPad|iPod|Mobile/i.test(navigator2?.userAgent ?? "");
|
|
75
|
+
} catch {
|
|
76
|
+
mobile = false;
|
|
77
|
+
}
|
|
78
|
+
let isolated = false;
|
|
79
|
+
try {
|
|
80
|
+
isolated = ambiente.crossOriginIsolated === true;
|
|
81
|
+
} catch {
|
|
82
|
+
isolated = false;
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
webgl2: false,
|
|
86
|
+
webgpu: false,
|
|
87
|
+
wasm: false,
|
|
88
|
+
threads: false,
|
|
89
|
+
isolated,
|
|
90
|
+
gpu: "none",
|
|
91
|
+
memoryMb,
|
|
92
|
+
cores,
|
|
93
|
+
mobile
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
async function probeDevice(globals, timeoutMs = 1500) {
|
|
97
|
+
const ambiente = globals ?? globalThis;
|
|
98
|
+
const report = valoriSincroni(ambiente);
|
|
99
|
+
const webgl = Promise.resolve().then(() => {
|
|
100
|
+
try {
|
|
101
|
+
const canvas = ambiente.document?.createElement("canvas");
|
|
102
|
+
if (canvas === void 0) return;
|
|
103
|
+
const hardware = canvas.getContext("webgl2", { failIfMajorPerformanceCaveat: true });
|
|
104
|
+
if (hardware !== null) {
|
|
105
|
+
report.webgl2 = true;
|
|
106
|
+
report.gpu = "hardware";
|
|
107
|
+
perdiContesto(hardware);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const software = canvas.getContext("webgl2");
|
|
111
|
+
if (software !== null) {
|
|
112
|
+
report.webgl2 = true;
|
|
113
|
+
report.gpu = "software";
|
|
114
|
+
perdiContesto(software);
|
|
115
|
+
}
|
|
116
|
+
} catch {
|
|
117
|
+
report.webgl2 = false;
|
|
118
|
+
report.gpu = "none";
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
const webgpu = Promise.resolve().then(async () => {
|
|
122
|
+
let device;
|
|
123
|
+
try {
|
|
124
|
+
const gpu = ambiente.navigator?.gpu;
|
|
125
|
+
if (gpu === void 0) return;
|
|
126
|
+
const adapter = await gpu.requestAdapter();
|
|
127
|
+
if (adapter === null) return;
|
|
128
|
+
device = await adapter.requestDevice();
|
|
129
|
+
report.webgpu = true;
|
|
130
|
+
} catch {
|
|
131
|
+
report.webgpu = false;
|
|
132
|
+
} finally {
|
|
133
|
+
try {
|
|
134
|
+
device?.destroy?.();
|
|
135
|
+
} catch {
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
const wasm = Promise.resolve().then(() => {
|
|
140
|
+
try {
|
|
141
|
+
report.wasm = ambiente.WebAssembly?.validate(
|
|
142
|
+
new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
|
|
143
|
+
) === true;
|
|
144
|
+
} catch {
|
|
145
|
+
report.wasm = false;
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
const threads = Promise.resolve().then(() => {
|
|
149
|
+
try {
|
|
150
|
+
if (ambiente.WebAssembly === void 0) return;
|
|
151
|
+
new ambiente.WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
|
|
152
|
+
report.threads = true;
|
|
153
|
+
} catch {
|
|
154
|
+
report.threads = false;
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
let timer;
|
|
158
|
+
await Promise.race([
|
|
159
|
+
Promise.all([webgl, webgpu, wasm, threads]),
|
|
160
|
+
new Promise((resolve) => {
|
|
161
|
+
timer = setTimeout(resolve, Math.max(0, timeoutMs));
|
|
162
|
+
})
|
|
163
|
+
]);
|
|
164
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
165
|
+
return { ...report, tier: deviceTier(report) };
|
|
166
|
+
}
|
|
2
167
|
|
|
3
168
|
// src/errors.ts
|
|
4
169
|
function creaErrore(code, message) {
|
|
@@ -11,25 +176,19 @@ function codiceErrore(valore) {
|
|
|
11
176
|
return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
|
|
12
177
|
}
|
|
13
178
|
|
|
14
|
-
// src/
|
|
15
|
-
async function leggiJson(response) {
|
|
16
|
-
try {
|
|
17
|
-
return await response.json();
|
|
18
|
-
} catch {
|
|
19
|
-
throw creaErrore("internal_error", "The service returned an invalid response.");
|
|
20
|
-
}
|
|
21
|
-
}
|
|
179
|
+
// src/http.ts
|
|
22
180
|
async function leggiErrore(response) {
|
|
23
181
|
let corpo = {};
|
|
24
182
|
try {
|
|
25
183
|
corpo = await response.json();
|
|
26
184
|
} catch {
|
|
27
185
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
186
|
+
return creaErrore(
|
|
187
|
+
typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error",
|
|
188
|
+
typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`
|
|
189
|
+
);
|
|
31
190
|
}
|
|
32
|
-
function
|
|
191
|
+
function creaRichiedente(origin, prefix, fetcher, biglietto) {
|
|
33
192
|
async function manda(path, metodo, ticket, corpo) {
|
|
34
193
|
const headers = new Headers({ Authorization: `Bearer ${ticket}` });
|
|
35
194
|
let body;
|
|
@@ -42,7 +201,7 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
42
201
|
}
|
|
43
202
|
}
|
|
44
203
|
try {
|
|
45
|
-
return await fetcher(new URL(
|
|
204
|
+
return await fetcher(new URL(prefix + path, origin), {
|
|
46
205
|
method: metodo,
|
|
47
206
|
headers,
|
|
48
207
|
body,
|
|
@@ -52,10 +211,10 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
52
211
|
throw erroreOffline();
|
|
53
212
|
}
|
|
54
213
|
}
|
|
55
|
-
async function richiesta(path, metodo, corpo) {
|
|
214
|
+
return async function richiesta(path, metodo, corpo, forzaRinnovo = false) {
|
|
56
215
|
let ticket;
|
|
57
216
|
try {
|
|
58
|
-
ticket = await biglietto.ottieni();
|
|
217
|
+
ticket = forzaRinnovo ? await biglietto.rinnova() : await biglietto.ottieni();
|
|
59
218
|
} catch {
|
|
60
219
|
throw erroreOffline();
|
|
61
220
|
}
|
|
@@ -69,8 +228,17 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
|
69
228
|
response = await manda(path, metodo, ticket, corpo);
|
|
70
229
|
}
|
|
71
230
|
if (!response.ok) throw await leggiErrore(response);
|
|
72
|
-
|
|
73
|
-
|
|
231
|
+
try {
|
|
232
|
+
return await response.json();
|
|
233
|
+
} catch {
|
|
234
|
+
throw creaErrore("internal_error", "The service returned an invalid response.");
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// src/api.ts
|
|
240
|
+
function creaClienteApi(appOrigin, fetcher, biglietto) {
|
|
241
|
+
const richiesta = creaRichiedente(appOrigin, "/api/kit", fetcher, biglietto);
|
|
74
242
|
return {
|
|
75
243
|
me: () => richiesta("/me", "GET"),
|
|
76
244
|
saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),
|
|
@@ -135,6 +303,15 @@ function record(valore) {
|
|
|
135
303
|
function eTipo(valore, tipo) {
|
|
136
304
|
return record(valore)?.type === tipo;
|
|
137
305
|
}
|
|
306
|
+
function leggiOrigine(valore) {
|
|
307
|
+
if (typeof valore !== "string") return null;
|
|
308
|
+
try {
|
|
309
|
+
const url = new URL(valore);
|
|
310
|
+
return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;
|
|
311
|
+
} catch {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
138
315
|
function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
|
|
139
316
|
return new Promise((resolve) => {
|
|
140
317
|
let concluso = false;
|
|
@@ -159,7 +336,12 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
|
|
|
159
336
|
const porta = evento.ports[0];
|
|
160
337
|
if (typeof dati?.ticket !== "string" || porta === void 0) return;
|
|
161
338
|
porta.start();
|
|
162
|
-
termina({
|
|
339
|
+
termina({
|
|
340
|
+
ticket: dati.ticket,
|
|
341
|
+
live: leggiOrigine(dati.live),
|
|
342
|
+
invite: typeof dati.invite === "string" ? dati.invite : null,
|
|
343
|
+
porta
|
|
344
|
+
});
|
|
163
345
|
};
|
|
164
346
|
finestra.addEventListener("message", ascolta);
|
|
165
347
|
const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
|
|
@@ -180,7 +362,7 @@ function scadenzaJwt(ticket) {
|
|
|
180
362
|
return null;
|
|
181
363
|
}
|
|
182
364
|
}
|
|
183
|
-
function chiediBiglietto(porta, finestra, timeoutMs) {
|
|
365
|
+
function chiediBiglietto(porta, finestra, timeoutMs, aud) {
|
|
184
366
|
return new Promise((resolve, reject) => {
|
|
185
367
|
let concluso = false;
|
|
186
368
|
const termina = (ticket) => {
|
|
@@ -193,25 +375,26 @@ function chiediBiglietto(porta, finestra, timeoutMs) {
|
|
|
193
375
|
};
|
|
194
376
|
const ascolta = (evento) => {
|
|
195
377
|
const dati = record(evento.data);
|
|
196
|
-
|
|
378
|
+
const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;
|
|
379
|
+
if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {
|
|
197
380
|
termina(dati.ticket);
|
|
198
381
|
}
|
|
199
382
|
};
|
|
200
383
|
porta.addEventListener("message", ascolta);
|
|
201
384
|
const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
|
|
202
385
|
try {
|
|
203
|
-
porta.postMessage({ type: "caisual:ticket" });
|
|
386
|
+
porta.postMessage(aud === "live" ? { type: "caisual:ticket", aud: "live" } : { type: "caisual:ticket" });
|
|
204
387
|
} catch {
|
|
205
388
|
termina(null);
|
|
206
389
|
}
|
|
207
390
|
});
|
|
208
391
|
}
|
|
209
|
-
function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3) {
|
|
392
|
+
function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3, aud = "portal") {
|
|
210
393
|
let ticket = ticketIniziale;
|
|
211
394
|
let rinnovo = null;
|
|
212
395
|
const rinnova = () => {
|
|
213
396
|
if (rinnovo !== null) return rinnovo;
|
|
214
|
-
const richiesta = chiediBiglietto(porta, finestra, timeoutMs).then((nuovo) => {
|
|
397
|
+
const richiesta = chiediBiglietto(porta, finestra, timeoutMs, aud).then((nuovo) => {
|
|
215
398
|
ticket = nuovo;
|
|
216
399
|
return nuovo;
|
|
217
400
|
});
|
|
@@ -223,6 +406,7 @@ function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs =
|
|
|
223
406
|
};
|
|
224
407
|
return {
|
|
225
408
|
async ottieni() {
|
|
409
|
+
if (ticket === null) return rinnova();
|
|
226
410
|
const scadenza = scadenzaJwt(ticket);
|
|
227
411
|
return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;
|
|
228
412
|
},
|
|
@@ -230,6 +414,1517 @@ function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs =
|
|
|
230
414
|
};
|
|
231
415
|
}
|
|
232
416
|
|
|
417
|
+
// src/voce/index.ts
|
|
418
|
+
var SOGLIA_AUDIO = 0.02;
|
|
419
|
+
var DURATA_PARLANTE = 300;
|
|
420
|
+
var INTERVALLO_AUDIO = 200;
|
|
421
|
+
var DURATA_ZERO = 3e3;
|
|
422
|
+
var TIMEOUT_CONNESSIONE = 1e4;
|
|
423
|
+
var RITARDI_RICONNESSIONE = [1e3, 2e3, 4e3];
|
|
424
|
+
function limita(value) {
|
|
425
|
+
return Number.isNaN(value) ? 1 : Math.min(1, Math.max(0, value));
|
|
426
|
+
}
|
|
427
|
+
function dipendenzeReali(input) {
|
|
428
|
+
const globali = globalThis;
|
|
429
|
+
const AudioContextClass = globali.AudioContext ?? globali.webkitAudioContext;
|
|
430
|
+
if (typeof RTCPeerConnection === "undefined" || typeof MediaStream === "undefined" || AudioContextClass === void 0 || typeof navigator === "undefined" || navigator.mediaDevices?.getUserMedia === void 0 || typeof document === "undefined") return null;
|
|
431
|
+
return {
|
|
432
|
+
...input,
|
|
433
|
+
creaPeerConnection: (configuration) => new RTCPeerConnection(configuration),
|
|
434
|
+
getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),
|
|
435
|
+
creaAudioContext: () => new AudioContextClass(),
|
|
436
|
+
creaAudioElement: () => document.createElement("audio"),
|
|
437
|
+
creaMediaStream: (tracks) => new MediaStream(tracks)
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
var VoceClient = class {
|
|
441
|
+
constructor(contesto, timer, dipendenze) {
|
|
442
|
+
this.contesto = contesto;
|
|
443
|
+
this.modeCorrente = "none";
|
|
444
|
+
this.stateCorrente = "off";
|
|
445
|
+
this.mutedCorrente = false;
|
|
446
|
+
this.speakingCorrente = false;
|
|
447
|
+
this.roster = [];
|
|
448
|
+
this.gains = /* @__PURE__ */ new Map();
|
|
449
|
+
this.volumi = /* @__PURE__ */ new Map();
|
|
450
|
+
this.speakingPeers = /* @__PURE__ */ new Map();
|
|
451
|
+
this.ultimoAudio = /* @__PURE__ */ new Map();
|
|
452
|
+
this.zeroDa = /* @__PURE__ */ new Map();
|
|
453
|
+
this.timerZero = /* @__PURE__ */ new Map();
|
|
454
|
+
this.ascoltatoriPeers = /* @__PURE__ */ new Set();
|
|
455
|
+
this.ascoltatoriState = /* @__PURE__ */ new Set();
|
|
456
|
+
this.richieste = /* @__PURE__ */ new Map();
|
|
457
|
+
this.riproduzioni = /* @__PURE__ */ new Map();
|
|
458
|
+
this.sfuAttive = /* @__PURE__ */ new Map();
|
|
459
|
+
this.midGiocatori = /* @__PURE__ */ new Map();
|
|
460
|
+
this.mesh = /* @__PURE__ */ new Map();
|
|
461
|
+
this.stream = null;
|
|
462
|
+
this.tracciaMic = null;
|
|
463
|
+
this.audioContext = null;
|
|
464
|
+
this.analyser = null;
|
|
465
|
+
this.peerSfu = null;
|
|
466
|
+
this.sessioneSfu = null;
|
|
467
|
+
this.connessioneSfuAttesa = false;
|
|
468
|
+
this.trasporto = null;
|
|
469
|
+
this.intervalloAudio = null;
|
|
470
|
+
this.timerConnessione = null;
|
|
471
|
+
this.cancellaAttesaConnessione = null;
|
|
472
|
+
this.timerRiconnessione = null;
|
|
473
|
+
this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
|
|
474
|
+
this.sequenzaRichieste = 0;
|
|
475
|
+
this.generazione = 0;
|
|
476
|
+
this.tentativoRiconnessione = 0;
|
|
477
|
+
this.desiderata = false;
|
|
478
|
+
this.micDesiderato = true;
|
|
479
|
+
this.promessaIngresso = null;
|
|
480
|
+
this.negoziazione = Promise.resolve();
|
|
481
|
+
this.dipendenze = dipendenze ?? dipendenzeReali(timer);
|
|
482
|
+
}
|
|
483
|
+
get mode() {
|
|
484
|
+
return this.modeCorrente;
|
|
485
|
+
}
|
|
486
|
+
get state() {
|
|
487
|
+
return this.stateCorrente;
|
|
488
|
+
}
|
|
489
|
+
get mic() {
|
|
490
|
+
return this.stateCorrente === "on" && this.tracciaMic !== null;
|
|
491
|
+
}
|
|
492
|
+
get muted() {
|
|
493
|
+
return this.mutedCorrente;
|
|
494
|
+
}
|
|
495
|
+
get speaking() {
|
|
496
|
+
return this.speakingCorrente;
|
|
497
|
+
}
|
|
498
|
+
get peers() {
|
|
499
|
+
return this.copiaPeers();
|
|
500
|
+
}
|
|
501
|
+
async join(options = {}) {
|
|
502
|
+
if (this.stateCorrente === "on") return;
|
|
503
|
+
if (this.stateCorrente === "joining") {
|
|
504
|
+
if (this.promessaIngresso !== null) await this.promessaIngresso;
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
if (this.stateCorrente === "reconnecting" && this.desiderata) return;
|
|
508
|
+
const mic = this.scegliMic(options);
|
|
509
|
+
this.verificaIngresso(mic);
|
|
510
|
+
this.micDesiderato = mic;
|
|
511
|
+
this.desiderata = true;
|
|
512
|
+
this.tentativoRiconnessione = 0;
|
|
513
|
+
this.aggiornaState("joining");
|
|
514
|
+
const generazione = ++this.generazione;
|
|
515
|
+
const promessa = this.completaIngresso(generazione);
|
|
516
|
+
this.promessaIngresso = promessa;
|
|
517
|
+
try {
|
|
518
|
+
await promessa;
|
|
519
|
+
} finally {
|
|
520
|
+
if (this.promessaIngresso === promessa) this.promessaIngresso = null;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
async completaIngresso(generazione) {
|
|
524
|
+
try {
|
|
525
|
+
await this.entra(generazione);
|
|
526
|
+
} catch (cause) {
|
|
527
|
+
if (generazione !== this.generazione) return;
|
|
528
|
+
this.desiderata = false;
|
|
529
|
+
this.chiudiRisorse();
|
|
530
|
+
this.aggiornaState("off");
|
|
531
|
+
throw this.mappaErrore(cause);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
leave() {
|
|
535
|
+
const deveFermare = this.desiderata || this.stateCorrente !== "off";
|
|
536
|
+
this.desiderata = false;
|
|
537
|
+
this.generazione++;
|
|
538
|
+
this.fermaRiconnessione();
|
|
539
|
+
if (deveFermare && this.contesto.connessa()) {
|
|
540
|
+
void this.richiedi({ t: "voice", op: "stop" }).catch(() => void 0);
|
|
541
|
+
}
|
|
542
|
+
this.rifiutaRichieste(creaErrore("offline", "Voice has stopped."));
|
|
543
|
+
this.chiudiRisorse();
|
|
544
|
+
this.aggiornaState("off");
|
|
545
|
+
}
|
|
546
|
+
mute(muted = true) {
|
|
547
|
+
if (this.stateCorrente !== "on" || this.tracciaMic === null) {
|
|
548
|
+
throw creaErrore("not_publishing", "Join voice before changing mute.");
|
|
549
|
+
}
|
|
550
|
+
this.mutedCorrente = muted;
|
|
551
|
+
this.tracciaMic.enabled = !muted;
|
|
552
|
+
void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
|
|
553
|
+
}
|
|
554
|
+
setVolume(playerId, volume) {
|
|
555
|
+
const valore = limita(volume);
|
|
556
|
+
this.volumi.set(playerId, valore);
|
|
557
|
+
this.aggiornaGuadagno(playerId);
|
|
558
|
+
this.notificaPeers();
|
|
559
|
+
}
|
|
560
|
+
onPeers(listener) {
|
|
561
|
+
this.ascoltatoriPeers.add(listener);
|
|
562
|
+
return () => {
|
|
563
|
+
this.ascoltatoriPeers.delete(listener);
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
onState(listener) {
|
|
567
|
+
this.ascoltatoriState.add(listener);
|
|
568
|
+
return () => {
|
|
569
|
+
this.ascoltatoriState.delete(listener);
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
ricevi(message) {
|
|
573
|
+
if ("r" in message) {
|
|
574
|
+
const pending = this.richieste.get(message.r);
|
|
575
|
+
if (pending !== void 0) {
|
|
576
|
+
this.richieste.delete(message.r);
|
|
577
|
+
if ("error" in message) {
|
|
578
|
+
pending.reject(creaErrore(message.error.code, message.error.message));
|
|
579
|
+
} else pending.resolve(message);
|
|
580
|
+
}
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
if (message.op === "roster") {
|
|
584
|
+
this.modeCorrente = message.mode;
|
|
585
|
+
const publisher = new Set(message.peers.map((peer) => peer.id));
|
|
586
|
+
this.roster = [
|
|
587
|
+
...message.peers.map((peer) => ({ ...peer, mic: true })),
|
|
588
|
+
...message.listeners.flatMap((id) => publisher.has(id) ? [] : [{ id, mic: false, muted: true }])
|
|
589
|
+
];
|
|
590
|
+
for (const peer of this.roster) {
|
|
591
|
+
if (peer.muted) this.speakingPeers.set(peer.id, false);
|
|
592
|
+
}
|
|
593
|
+
this.pulisciPeerAssenti();
|
|
594
|
+
this.contesto.rosterPronto();
|
|
595
|
+
this.notificaPeers();
|
|
596
|
+
this.accodaRiconciliazione();
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (message.op === "gain") {
|
|
600
|
+
for (const [playerId, gain] of Object.entries(message.gains)) {
|
|
601
|
+
this.gains.set(playerId, limita(gain));
|
|
602
|
+
this.aggiornaZero(playerId);
|
|
603
|
+
this.aggiornaGuadagno(playerId);
|
|
604
|
+
}
|
|
605
|
+
this.notificaPeers();
|
|
606
|
+
this.accodaRiconciliazione();
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (message.op === "signal") void this.riceviSegnale(message.from, message.data);
|
|
610
|
+
}
|
|
611
|
+
giocatoriCambiati() {
|
|
612
|
+
const presenti = new Set(this.contesto.giocatori().map((player) => player.id));
|
|
613
|
+
for (const playerId of this.gains.keys()) {
|
|
614
|
+
if (presenti.has(playerId)) continue;
|
|
615
|
+
this.gains.delete(playerId);
|
|
616
|
+
this.zeroDa.delete(playerId);
|
|
617
|
+
const timer = this.timerZero.get(playerId);
|
|
618
|
+
if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
|
|
619
|
+
this.timerZero.delete(playerId);
|
|
620
|
+
this.aggiornaGuadagno(playerId);
|
|
621
|
+
}
|
|
622
|
+
this.notificaPeers();
|
|
623
|
+
this.accodaRiconciliazione();
|
|
624
|
+
}
|
|
625
|
+
socketDisconnesso() {
|
|
626
|
+
this.sequenzaRichieste = 0;
|
|
627
|
+
this.rifiutaRichieste(creaErrore("offline", "The room is reconnecting."));
|
|
628
|
+
if (!this.desiderata) return;
|
|
629
|
+
this.generazione++;
|
|
630
|
+
this.chiudiRisorse();
|
|
631
|
+
this.tentativoRiconnessione = 0;
|
|
632
|
+
this.aggiornaState("reconnecting");
|
|
633
|
+
}
|
|
634
|
+
socketRiconnesso() {
|
|
635
|
+
this.sequenzaRichieste = 0;
|
|
636
|
+
if (this.desiderata && this.stateCorrente === "reconnecting") this.programmaRiconnessione();
|
|
637
|
+
}
|
|
638
|
+
termina() {
|
|
639
|
+
this.desiderata = false;
|
|
640
|
+
this.generazione++;
|
|
641
|
+
this.fermaRiconnessione();
|
|
642
|
+
this.rifiutaRichieste(creaErrore("offline", "The room connection ended."));
|
|
643
|
+
this.chiudiRisorse();
|
|
644
|
+
this.aggiornaState("off");
|
|
645
|
+
}
|
|
646
|
+
scegliMic(options) {
|
|
647
|
+
if (options.mic !== void 0) return options.mic;
|
|
648
|
+
const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
|
|
649
|
+
return you?.role !== "spectator";
|
|
650
|
+
}
|
|
651
|
+
verificaIngresso(mic = this.micDesiderato) {
|
|
652
|
+
if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");
|
|
653
|
+
if (this.modeCorrente === "none") {
|
|
654
|
+
throw creaErrore("voice_disabled", "Voice is disabled for this room.");
|
|
655
|
+
}
|
|
656
|
+
const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
|
|
657
|
+
if (you?.role === "spectator" && mic) {
|
|
658
|
+
throw creaErrore("spectator", "Spectators cannot publish voice.");
|
|
659
|
+
}
|
|
660
|
+
if (this.dipendenze === null) {
|
|
661
|
+
throw creaErrore("unsupported", "Voice is not supported in this browser.");
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async entra(generazione) {
|
|
665
|
+
this.verificaIngresso();
|
|
666
|
+
const dipendenze = this.richiediDipendenze();
|
|
667
|
+
const audioContext = dipendenze.creaAudioContext();
|
|
668
|
+
this.audioContext = audioContext;
|
|
669
|
+
try {
|
|
670
|
+
await audioContext.resume();
|
|
671
|
+
} catch {
|
|
672
|
+
}
|
|
673
|
+
if (this.micDesiderato) {
|
|
674
|
+
let stream;
|
|
675
|
+
try {
|
|
676
|
+
stream = await dipendenze.getUserMedia({ audio: true });
|
|
677
|
+
} catch (cause) {
|
|
678
|
+
if (this.permessoNegato(cause)) {
|
|
679
|
+
throw creaErrore("permission_denied", "Microphone permission was denied.");
|
|
680
|
+
}
|
|
681
|
+
throw creaErrore("voice_error", "The microphone could not be opened.");
|
|
682
|
+
}
|
|
683
|
+
try {
|
|
684
|
+
this.controllaGenerazione(generazione);
|
|
685
|
+
} catch (cause) {
|
|
686
|
+
for (const track of stream.getTracks()) track.stop();
|
|
687
|
+
throw cause;
|
|
688
|
+
}
|
|
689
|
+
const mic = stream.getAudioTracks()[0];
|
|
690
|
+
if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");
|
|
691
|
+
this.stream = stream;
|
|
692
|
+
this.tracciaMic = mic;
|
|
693
|
+
mic.enabled = !this.mutedCorrente;
|
|
694
|
+
this.preparaAnalizzatore(stream);
|
|
695
|
+
}
|
|
696
|
+
const risposta = await this.richiedi({ t: "voice", op: "ice" });
|
|
697
|
+
this.controllaGenerazione(generazione);
|
|
698
|
+
if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
699
|
+
this.modeCorrente = risposta.mode;
|
|
700
|
+
if (risposta.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
|
|
701
|
+
this.trasporto = risposta.transport;
|
|
702
|
+
if (risposta.transport === "sfu") {
|
|
703
|
+
await this.entraSfu(risposta.iceServers, generazione);
|
|
704
|
+
} else {
|
|
705
|
+
await this.richiedi({ t: "voice", op: "publish", mic: this.micDesiderato });
|
|
706
|
+
}
|
|
707
|
+
if (this.micDesiderato && this.mutedCorrente) {
|
|
708
|
+
await this.richiedi({ t: "voice", op: "mute", muted: true });
|
|
709
|
+
}
|
|
710
|
+
this.controllaGenerazione(generazione);
|
|
711
|
+
this.tentativoRiconnessione = 0;
|
|
712
|
+
this.aggiornaState("on");
|
|
713
|
+
this.avviaMisuraAudio();
|
|
714
|
+
for (const playerId of this.gains.keys()) this.aggiornaZero(playerId);
|
|
715
|
+
this.accodaRiconciliazione();
|
|
716
|
+
}
|
|
717
|
+
async entraSfu(iceServers, generazione) {
|
|
718
|
+
const pc = this.richiediDipendenze().creaPeerConnection({
|
|
719
|
+
iceServers,
|
|
720
|
+
bundlePolicy: "max-bundle"
|
|
721
|
+
});
|
|
722
|
+
this.peerSfu = pc;
|
|
723
|
+
pc.ontrack = (event) => {
|
|
724
|
+
const mid = event.transceiver.mid;
|
|
725
|
+
const playerId = mid === null ? void 0 : this.midGiocatori.get(mid);
|
|
726
|
+
if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);
|
|
727
|
+
};
|
|
728
|
+
this.osservaCaduta(pc);
|
|
729
|
+
let risposta;
|
|
730
|
+
if (this.micDesiderato) {
|
|
731
|
+
const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });
|
|
732
|
+
const offer = await pc.createOffer();
|
|
733
|
+
await pc.setLocalDescription(offer);
|
|
734
|
+
this.controllaGenerazione(generazione);
|
|
735
|
+
const mid = transceiver.mid;
|
|
736
|
+
const sdp = pc.localDescription?.sdp;
|
|
737
|
+
if (mid === null || sdp === void 0) {
|
|
738
|
+
throw creaErrore("voice_error", "The voice connection could not create an offer.");
|
|
739
|
+
}
|
|
740
|
+
risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });
|
|
741
|
+
} else {
|
|
742
|
+
risposta = await this.richiedi({ t: "voice", op: "session" });
|
|
743
|
+
}
|
|
744
|
+
if (risposta.op !== "session") {
|
|
745
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
746
|
+
}
|
|
747
|
+
this.sessioneSfu = risposta.session;
|
|
748
|
+
if (this.micDesiderato) {
|
|
749
|
+
if (risposta.sdp === null) {
|
|
750
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
751
|
+
}
|
|
752
|
+
await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });
|
|
753
|
+
await this.attendiConnessione(pc, generazione);
|
|
754
|
+
this.connessioneSfuAttesa = true;
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
if (risposta.sdp !== null) {
|
|
758
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
759
|
+
}
|
|
760
|
+
if (this.publisherDesiderati().length > 0) {
|
|
761
|
+
await this.riconciliaSfu();
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
attendiConnessione(pc, generazione) {
|
|
765
|
+
if (pc.connectionState === "connected") return Promise.resolve();
|
|
766
|
+
const dipendenze = this.richiediDipendenze();
|
|
767
|
+
return new Promise((resolve, reject) => {
|
|
768
|
+
const pulisci = () => {
|
|
769
|
+
pc.removeEventListener("connectionstatechange", cambiata);
|
|
770
|
+
if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
|
|
771
|
+
this.timerConnessione = null;
|
|
772
|
+
this.cancellaAttesaConnessione = null;
|
|
773
|
+
};
|
|
774
|
+
const cambiata = () => {
|
|
775
|
+
if (generazione !== this.generazione) {
|
|
776
|
+
pulisci();
|
|
777
|
+
reject(creaErrore("offline", "Voice was stopped."));
|
|
778
|
+
} else if (pc.connectionState === "connected") {
|
|
779
|
+
pulisci();
|
|
780
|
+
resolve();
|
|
781
|
+
} else if (pc.connectionState === "failed" || pc.connectionState === "closed") {
|
|
782
|
+
pulisci();
|
|
783
|
+
reject(creaErrore("voice_error", "The voice connection failed."));
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
pc.addEventListener("connectionstatechange", cambiata);
|
|
787
|
+
this.cancellaAttesaConnessione = () => {
|
|
788
|
+
pulisci();
|
|
789
|
+
reject(creaErrore("offline", "Voice was stopped."));
|
|
790
|
+
};
|
|
791
|
+
this.timerConnessione = dipendenze.setTimeout(() => {
|
|
792
|
+
pulisci();
|
|
793
|
+
reject(creaErrore("voice_error", "The voice connection timed out."));
|
|
794
|
+
}, TIMEOUT_CONNESSIONE);
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
accodaRiconciliazione() {
|
|
798
|
+
if (this.stateCorrente !== "on") return;
|
|
799
|
+
this.negoziazione = this.negoziazione.then(async () => {
|
|
800
|
+
if (this.stateCorrente !== "on") return;
|
|
801
|
+
if (this.trasporto === "sfu") await this.riconciliaSfu();
|
|
802
|
+
else if (this.trasporto === "mesh") this.riconciliaMesh();
|
|
803
|
+
}).catch(() => this.avviaRiconnessione());
|
|
804
|
+
}
|
|
805
|
+
async riconciliaSfu() {
|
|
806
|
+
const sessione = this.sessioneSfu;
|
|
807
|
+
const pc = this.peerSfu;
|
|
808
|
+
if (sessione === null || pc === null) return;
|
|
809
|
+
const desiderati = new Map(this.publisherDesiderati().map((peer) => [peer.id, peer]));
|
|
810
|
+
const daChiudere = [];
|
|
811
|
+
for (const [playerId, attiva] of this.sfuAttive) {
|
|
812
|
+
const peer = desiderati.get(playerId);
|
|
813
|
+
if (peer !== void 0 && peer.session === attiva.session && peer.track === attiva.track) continue;
|
|
814
|
+
daChiudere.push(attiva);
|
|
815
|
+
if (!this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
|
|
816
|
+
this.sfuAttive.delete(playerId);
|
|
817
|
+
this.midGiocatori.delete(attiva.mid);
|
|
818
|
+
this.scollegaTraccia(playerId);
|
|
819
|
+
}
|
|
820
|
+
if (daChiudere.length > 0) {
|
|
821
|
+
await this.richiedi({
|
|
822
|
+
t: "voice",
|
|
823
|
+
op: "close",
|
|
824
|
+
session: sessione,
|
|
825
|
+
mids: daChiudere.map((item) => item.mid)
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));
|
|
829
|
+
if (nuove.length === 0) return;
|
|
830
|
+
const risposta = await this.richiedi({
|
|
831
|
+
t: "voice",
|
|
832
|
+
op: "subscribe",
|
|
833
|
+
session: sessione,
|
|
834
|
+
tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
|
|
835
|
+
});
|
|
836
|
+
if (risposta.op !== "subscribe") {
|
|
837
|
+
throw creaErrore("voice_error", "The voice service returned an invalid response.");
|
|
838
|
+
}
|
|
839
|
+
for (const risultato of risposta.tracks) {
|
|
840
|
+
const peer = nuove.find(
|
|
841
|
+
(item) => item.session === risultato.session && item.track === risultato.track
|
|
842
|
+
);
|
|
843
|
+
if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;
|
|
844
|
+
this.midGiocatori.set(risultato.mid, peer.id);
|
|
845
|
+
this.sfuAttive.set(peer.id, {
|
|
846
|
+
session: peer.session,
|
|
847
|
+
track: peer.track,
|
|
848
|
+
mid: risultato.mid,
|
|
849
|
+
receiver: null
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
await pc.setRemoteDescription({ type: "offer", sdp: risposta.sdp });
|
|
853
|
+
const answer = await pc.createAnswer();
|
|
854
|
+
await pc.setLocalDescription(answer);
|
|
855
|
+
const sdp = pc.localDescription?.sdp;
|
|
856
|
+
if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");
|
|
857
|
+
await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });
|
|
858
|
+
if (!this.connessioneSfuAttesa) {
|
|
859
|
+
await this.attendiConnessione(pc, this.generazione);
|
|
860
|
+
this.connessioneSfuAttesa = true;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
riconciliaMesh() {
|
|
864
|
+
const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
|
|
865
|
+
for (const [playerId, item] of this.mesh) {
|
|
866
|
+
if (desiderati.has(playerId)) continue;
|
|
867
|
+
item.pc.close();
|
|
868
|
+
this.mesh.delete(playerId);
|
|
869
|
+
this.scollegaTraccia(playerId);
|
|
870
|
+
}
|
|
871
|
+
for (const peer of desiderati.values()) {
|
|
872
|
+
if (!this.mesh.has(peer.id)) this.creaMesh(peer);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
creaMesh(peer) {
|
|
876
|
+
const playerId = peer.id;
|
|
877
|
+
const pc = this.richiediDipendenze().creaPeerConnection();
|
|
878
|
+
const item = {
|
|
879
|
+
pc,
|
|
880
|
+
makingOffer: false,
|
|
881
|
+
ignoreOffer: false,
|
|
882
|
+
settingRemoteAnswer: false,
|
|
883
|
+
polite: this.contesto.you() > playerId,
|
|
884
|
+
receiver: null
|
|
885
|
+
};
|
|
886
|
+
this.mesh.set(playerId, item);
|
|
887
|
+
pc.onicecandidate = (event) => {
|
|
888
|
+
if (event.candidate === null) return;
|
|
889
|
+
void this.inviaSegnale(playerId, { kind: "candidate", candidate: event.candidate.toJSON() });
|
|
890
|
+
};
|
|
891
|
+
if (!item.polite) pc.onnegotiationneeded = () => {
|
|
892
|
+
void this.offriMesh(playerId, item);
|
|
893
|
+
};
|
|
894
|
+
pc.ontrack = (event) => {
|
|
895
|
+
item.receiver = event.receiver;
|
|
896
|
+
this.collegaTraccia(playerId, event.track, event.receiver);
|
|
897
|
+
};
|
|
898
|
+
this.osservaCaduta(pc);
|
|
899
|
+
if (this.micDesiderato) {
|
|
900
|
+
pc.addTransceiver(this.richiediMic(), {
|
|
901
|
+
direction: peer.mic ? "sendrecv" : "sendonly"
|
|
902
|
+
});
|
|
903
|
+
} else {
|
|
904
|
+
pc.addTransceiver("audio", { direction: "recvonly" });
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
async offriMesh(playerId, item) {
|
|
908
|
+
try {
|
|
909
|
+
item.makingOffer = true;
|
|
910
|
+
const offer = await item.pc.createOffer();
|
|
911
|
+
await item.pc.setLocalDescription(offer);
|
|
912
|
+
const sdp = item.pc.localDescription?.sdp;
|
|
913
|
+
if (sdp !== void 0) await this.inviaSegnale(playerId, { kind: "offer", sdp });
|
|
914
|
+
} finally {
|
|
915
|
+
item.makingOffer = false;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
async riceviSegnale(from, data) {
|
|
919
|
+
if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;
|
|
920
|
+
const peer = this.peerDesiderati().find((item2) => item2.id === from);
|
|
921
|
+
if (peer === void 0) return;
|
|
922
|
+
if (!this.mesh.has(from)) this.creaMesh(peer);
|
|
923
|
+
const item = this.mesh.get(from);
|
|
924
|
+
if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;
|
|
925
|
+
const segnale = data;
|
|
926
|
+
try {
|
|
927
|
+
if (segnale.kind === "candidate") {
|
|
928
|
+
if (!item.ignoreOffer) await item.pc.addIceCandidate(segnale.candidate);
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
if (segnale.kind !== "offer" && segnale.kind !== "answer" || typeof segnale.sdp !== "string") return;
|
|
932
|
+
const pronta = !item.makingOffer && (item.pc.signalingState === "stable" || item.settingRemoteAnswer);
|
|
933
|
+
const collisione = segnale.kind === "offer" && !pronta;
|
|
934
|
+
item.ignoreOffer = !item.polite && collisione;
|
|
935
|
+
if (item.ignoreOffer) return;
|
|
936
|
+
item.settingRemoteAnswer = segnale.kind === "answer";
|
|
937
|
+
await item.pc.setRemoteDescription({ type: segnale.kind, sdp: segnale.sdp });
|
|
938
|
+
item.settingRemoteAnswer = false;
|
|
939
|
+
if (segnale.kind === "offer") {
|
|
940
|
+
const answer = await item.pc.createAnswer();
|
|
941
|
+
await item.pc.setLocalDescription(answer);
|
|
942
|
+
const sdp = item.pc.localDescription?.sdp;
|
|
943
|
+
if (sdp !== void 0) await this.inviaSegnale(from, { kind: "answer", sdp });
|
|
944
|
+
}
|
|
945
|
+
} catch {
|
|
946
|
+
this.avviaRiconnessione();
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
inviaSegnale(to, data) {
|
|
950
|
+
return this.richiedi({ t: "voice", op: "signal", to, data });
|
|
951
|
+
}
|
|
952
|
+
peerDesiderati() {
|
|
953
|
+
const you = this.contesto.you();
|
|
954
|
+
const giocatori = this.contesto.giocatori();
|
|
955
|
+
const player = giocatori.find((item) => item.id === you);
|
|
956
|
+
return this.roster.filter((peer) => {
|
|
957
|
+
if (peer.id === you) return false;
|
|
958
|
+
if (!this.micDesiderato && !peer.mic) return false;
|
|
959
|
+
if (this.modeCorrente === "team") {
|
|
960
|
+
const altro = giocatori.find((item) => item.id === peer.id);
|
|
961
|
+
if (player?.role !== "spectator" && altro?.team !== player?.team) return false;
|
|
962
|
+
}
|
|
963
|
+
return true;
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
publisherDesiderati() {
|
|
967
|
+
return this.peerDesiderati().filter(
|
|
968
|
+
(peer) => {
|
|
969
|
+
if (!peer.mic) return false;
|
|
970
|
+
const zeroAt = this.zeroDa.get(peer.id);
|
|
971
|
+
return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;
|
|
972
|
+
}
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
aggiornaZero(playerId) {
|
|
976
|
+
const dipendenze = this.dipendenze;
|
|
977
|
+
if (dipendenze === null) return;
|
|
978
|
+
const precedente = this.timerZero.get(playerId);
|
|
979
|
+
if (precedente !== void 0) dipendenze.clearTimeout(precedente);
|
|
980
|
+
this.timerZero.delete(playerId);
|
|
981
|
+
if ((this.gains.get(playerId) ?? 1) > 0) {
|
|
982
|
+
this.zeroDa.delete(playerId);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
if (!this.zeroDa.has(playerId)) this.zeroDa.set(playerId, dipendenze.ora());
|
|
986
|
+
const trascorso = dipendenze.ora() - (this.zeroDa.get(playerId) ?? dipendenze.ora());
|
|
987
|
+
const timer = dipendenze.setTimeout(() => {
|
|
988
|
+
this.timerZero.delete(playerId);
|
|
989
|
+
this.accodaRiconciliazione();
|
|
990
|
+
}, Math.max(0, DURATA_ZERO - trascorso));
|
|
991
|
+
this.timerZero.set(playerId, timer);
|
|
992
|
+
}
|
|
993
|
+
collegaTraccia(playerId, track, receiver) {
|
|
994
|
+
this.scollegaTraccia(playerId);
|
|
995
|
+
const dipendenze = this.richiediDipendenze();
|
|
996
|
+
const media = dipendenze.creaMediaStream([track]);
|
|
997
|
+
const source = this.richiediAudioContext().createMediaStreamSource(media);
|
|
998
|
+
const gain = this.richiediAudioContext().createGain();
|
|
999
|
+
source.connect(gain);
|
|
1000
|
+
gain.connect(this.richiediAudioContext().destination);
|
|
1001
|
+
let analyser = null;
|
|
1002
|
+
try {
|
|
1003
|
+
analyser = this.richiediAudioContext().createAnalyser();
|
|
1004
|
+
analyser.fftSize = 256;
|
|
1005
|
+
source.connect(analyser);
|
|
1006
|
+
} catch {
|
|
1007
|
+
analyser = null;
|
|
1008
|
+
}
|
|
1009
|
+
const audio = dipendenze.creaAudioElement();
|
|
1010
|
+
audio.srcObject = media;
|
|
1011
|
+
audio.muted = true;
|
|
1012
|
+
audio.playsInline = true;
|
|
1013
|
+
void audio.play().catch(() => void 0);
|
|
1014
|
+
this.riproduzioni.set(playerId, { source, gain, analyser, audio, track, receiver });
|
|
1015
|
+
const attiva = this.sfuAttive.get(playerId);
|
|
1016
|
+
if (attiva !== void 0) attiva.receiver = receiver;
|
|
1017
|
+
this.aggiornaGuadagno(playerId);
|
|
1018
|
+
}
|
|
1019
|
+
scollegaTraccia(playerId) {
|
|
1020
|
+
const riproduzione = this.riproduzioni.get(playerId);
|
|
1021
|
+
if (riproduzione === void 0) return;
|
|
1022
|
+
riproduzione.source.disconnect();
|
|
1023
|
+
riproduzione.gain.disconnect();
|
|
1024
|
+
riproduzione.analyser?.disconnect();
|
|
1025
|
+
riproduzione.track.stop();
|
|
1026
|
+
riproduzione.audio.pause();
|
|
1027
|
+
riproduzione.audio.srcObject = null;
|
|
1028
|
+
this.riproduzioni.delete(playerId);
|
|
1029
|
+
this.speakingPeers.delete(playerId);
|
|
1030
|
+
this.ultimoAudio.delete(playerId);
|
|
1031
|
+
}
|
|
1032
|
+
aggiornaGuadagno(playerId) {
|
|
1033
|
+
const riproduzione = this.riproduzioni.get(playerId);
|
|
1034
|
+
if (riproduzione !== void 0) {
|
|
1035
|
+
riproduzione.gain.gain.value = (this.volumi.get(playerId) ?? 1) * (this.gains.get(playerId) ?? 1);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
preparaAnalizzatore(stream) {
|
|
1039
|
+
const context = this.richiediAudioContext();
|
|
1040
|
+
const analyser = context.createAnalyser();
|
|
1041
|
+
analyser.fftSize = 256;
|
|
1042
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
1043
|
+
this.analyser = analyser;
|
|
1044
|
+
}
|
|
1045
|
+
avviaMisuraAudio() {
|
|
1046
|
+
const dipendenze = this.richiediDipendenze();
|
|
1047
|
+
if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
|
|
1048
|
+
this.intervalloAudio = dipendenze.setInterval(() => this.misuraAudio(), INTERVALLO_AUDIO);
|
|
1049
|
+
}
|
|
1050
|
+
misuraAudio() {
|
|
1051
|
+
const dipendenze = this.dipendenze;
|
|
1052
|
+
if (dipendenze === null) return;
|
|
1053
|
+
let sopraSoglia = false;
|
|
1054
|
+
if (this.analyser !== null) sopraSoglia = this.livelloAnalizzatore(this.analyser) > SOGLIA_AUDIO;
|
|
1055
|
+
if (sopraSoglia) this.ultimoAudioMic = dipendenze.ora();
|
|
1056
|
+
const parlando = !this.mutedCorrente && dipendenze.ora() - this.ultimoAudioMic <= DURATA_PARLANTE;
|
|
1057
|
+
if (parlando !== this.speakingCorrente) {
|
|
1058
|
+
this.speakingCorrente = parlando;
|
|
1059
|
+
this.notificaPeers();
|
|
1060
|
+
}
|
|
1061
|
+
let cambiato = false;
|
|
1062
|
+
for (const peer of this.copiaPeers()) {
|
|
1063
|
+
const riproduzione = this.riproduzioni.get(peer.id);
|
|
1064
|
+
if (this.livelloAnalizzatore(riproduzione?.analyser ?? null) > SOGLIA_AUDIO) {
|
|
1065
|
+
this.ultimoAudio.set(peer.id, dipendenze.ora());
|
|
1066
|
+
} else if (riproduzione?.analyser === null || riproduzione?.analyser === void 0) {
|
|
1067
|
+
const sources = riproduzione?.receiver?.getSynchronizationSources?.() ?? [];
|
|
1068
|
+
if (sources.some((source) => (source.audioLevel ?? 0) > SOGLIA_AUDIO)) {
|
|
1069
|
+
this.ultimoAudio.set(peer.id, dipendenze.ora());
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
const speaking = !peer.muted && dipendenze.ora() - (this.ultimoAudio.get(peer.id) ?? 0) <= DURATA_PARLANTE;
|
|
1073
|
+
if ((this.speakingPeers.get(peer.id) ?? false) !== speaking) {
|
|
1074
|
+
this.speakingPeers.set(peer.id, speaking);
|
|
1075
|
+
cambiato = true;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
if (cambiato) this.notificaPeers();
|
|
1079
|
+
}
|
|
1080
|
+
livelloAnalizzatore(analyser) {
|
|
1081
|
+
const nodo = analyser;
|
|
1082
|
+
if (nodo?.getFloatTimeDomainData === void 0) return 0;
|
|
1083
|
+
const campioni = new Float32Array(nodo.fftSize);
|
|
1084
|
+
nodo.getFloatTimeDomainData(campioni);
|
|
1085
|
+
return Math.sqrt(campioni.reduce((somma, valore) => somma + valore * valore, 0) / Math.max(1, campioni.length));
|
|
1086
|
+
}
|
|
1087
|
+
copiaPeers() {
|
|
1088
|
+
const you = this.contesto.you();
|
|
1089
|
+
const giocatori = this.contesto.giocatori();
|
|
1090
|
+
const player = giocatori.find((item) => item.id === you);
|
|
1091
|
+
return this.roster.flatMap((peer) => {
|
|
1092
|
+
if (peer.id === you) return [];
|
|
1093
|
+
if (this.modeCorrente === "team") {
|
|
1094
|
+
const altro = giocatori.find((item) => item.id === peer.id);
|
|
1095
|
+
if (player?.role !== "spectator" && altro?.team !== player?.team) return [];
|
|
1096
|
+
}
|
|
1097
|
+
return [{
|
|
1098
|
+
id: peer.id,
|
|
1099
|
+
mic: peer.mic,
|
|
1100
|
+
muted: peer.muted,
|
|
1101
|
+
speaking: peer.mic && !peer.muted && (this.speakingPeers.get(peer.id) ?? false),
|
|
1102
|
+
volume: this.volumi.get(peer.id) ?? 1,
|
|
1103
|
+
gain: this.gains.get(peer.id) ?? 1
|
|
1104
|
+
}];
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
pulisciPeerAssenti() {
|
|
1108
|
+
const presenti = new Set(this.roster.map((peer) => peer.id));
|
|
1109
|
+
for (const playerId of this.speakingPeers.keys()) {
|
|
1110
|
+
if (!presenti.has(playerId)) this.speakingPeers.delete(playerId);
|
|
1111
|
+
}
|
|
1112
|
+
for (const playerId of this.zeroDa.keys()) {
|
|
1113
|
+
if (presenti.has(playerId)) continue;
|
|
1114
|
+
this.zeroDa.delete(playerId);
|
|
1115
|
+
const timer = this.timerZero.get(playerId);
|
|
1116
|
+
if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
|
|
1117
|
+
this.timerZero.delete(playerId);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
osservaCaduta(pc) {
|
|
1121
|
+
pc.addEventListener("connectionstatechange", () => {
|
|
1122
|
+
if (this.stateCorrente === "on" && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) this.avviaRiconnessione();
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
avviaRiconnessione() {
|
|
1126
|
+
if (!this.desiderata || this.stateCorrente === "reconnecting") return;
|
|
1127
|
+
this.generazione++;
|
|
1128
|
+
this.rifiutaRichieste(creaErrore("voice_error", "The voice connection was restarted."));
|
|
1129
|
+
this.chiudiRisorse();
|
|
1130
|
+
this.tentativoRiconnessione = 0;
|
|
1131
|
+
this.aggiornaState("reconnecting");
|
|
1132
|
+
this.programmaRiconnessione();
|
|
1133
|
+
}
|
|
1134
|
+
programmaRiconnessione() {
|
|
1135
|
+
if (!this.desiderata || !this.contesto.connessa() || this.timerRiconnessione !== null || this.stateCorrente !== "reconnecting") return;
|
|
1136
|
+
const ritardo = RITARDI_RICONNESSIONE[this.tentativoRiconnessione];
|
|
1137
|
+
if (ritardo === void 0) {
|
|
1138
|
+
this.desiderata = false;
|
|
1139
|
+
this.aggiornaState("off");
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
this.tentativoRiconnessione++;
|
|
1143
|
+
this.timerRiconnessione = this.richiediDipendenze().setTimeout(() => {
|
|
1144
|
+
this.timerRiconnessione = null;
|
|
1145
|
+
const generazione = ++this.generazione;
|
|
1146
|
+
void this.entra(generazione).catch(() => {
|
|
1147
|
+
if (generazione !== this.generazione || !this.desiderata) return;
|
|
1148
|
+
this.chiudiRisorse();
|
|
1149
|
+
this.aggiornaState("reconnecting");
|
|
1150
|
+
this.programmaRiconnessione();
|
|
1151
|
+
});
|
|
1152
|
+
}, ritardo);
|
|
1153
|
+
}
|
|
1154
|
+
fermaRiconnessione() {
|
|
1155
|
+
if (this.timerRiconnessione === null || this.dipendenze === null) return;
|
|
1156
|
+
this.dipendenze.clearTimeout(this.timerRiconnessione);
|
|
1157
|
+
this.timerRiconnessione = null;
|
|
1158
|
+
}
|
|
1159
|
+
chiudiRisorse() {
|
|
1160
|
+
const dipendenze = this.dipendenze;
|
|
1161
|
+
this.cancellaAttesaConnessione?.();
|
|
1162
|
+
this.cancellaAttesaConnessione = null;
|
|
1163
|
+
if (dipendenze !== null) {
|
|
1164
|
+
if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
|
|
1165
|
+
if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
|
|
1166
|
+
for (const timer of this.timerZero.values()) dipendenze.clearTimeout(timer);
|
|
1167
|
+
}
|
|
1168
|
+
this.intervalloAudio = null;
|
|
1169
|
+
this.timerConnessione = null;
|
|
1170
|
+
this.timerZero.clear();
|
|
1171
|
+
for (const playerId of [...this.riproduzioni.keys()]) this.scollegaTraccia(playerId);
|
|
1172
|
+
this.peerSfu?.close();
|
|
1173
|
+
this.peerSfu = null;
|
|
1174
|
+
for (const item of this.mesh.values()) item.pc.close();
|
|
1175
|
+
this.mesh.clear();
|
|
1176
|
+
this.sfuAttive.clear();
|
|
1177
|
+
this.midGiocatori.clear();
|
|
1178
|
+
for (const track of this.stream?.getTracks() ?? []) track.stop();
|
|
1179
|
+
this.stream = null;
|
|
1180
|
+
this.tracciaMic = null;
|
|
1181
|
+
this.analyser = null;
|
|
1182
|
+
void this.audioContext?.close().catch(() => void 0);
|
|
1183
|
+
this.audioContext = null;
|
|
1184
|
+
this.sessioneSfu = null;
|
|
1185
|
+
this.connessioneSfuAttesa = false;
|
|
1186
|
+
this.trasporto = null;
|
|
1187
|
+
this.speakingCorrente = false;
|
|
1188
|
+
this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
|
|
1189
|
+
this.speakingPeers.clear();
|
|
1190
|
+
this.ultimoAudio.clear();
|
|
1191
|
+
this.negoziazione = Promise.resolve();
|
|
1192
|
+
}
|
|
1193
|
+
richiedi(message) {
|
|
1194
|
+
if (!this.contesto.connessa()) return Promise.reject(creaErrore("offline", "The room is reconnecting."));
|
|
1195
|
+
const r = ++this.sequenzaRichieste;
|
|
1196
|
+
return new Promise((resolve, reject) => {
|
|
1197
|
+
this.richieste.set(r, { resolve, reject });
|
|
1198
|
+
try {
|
|
1199
|
+
this.contesto.invia({ ...message, r });
|
|
1200
|
+
} catch (cause) {
|
|
1201
|
+
this.richieste.delete(r);
|
|
1202
|
+
reject(cause);
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
rifiutaRichieste(reason) {
|
|
1207
|
+
for (const richiesta of this.richieste.values()) richiesta.reject(reason);
|
|
1208
|
+
this.richieste.clear();
|
|
1209
|
+
}
|
|
1210
|
+
aggiornaState(state) {
|
|
1211
|
+
if (state === this.stateCorrente) return;
|
|
1212
|
+
this.stateCorrente = state;
|
|
1213
|
+
for (const listener of this.ascoltatoriState) {
|
|
1214
|
+
try {
|
|
1215
|
+
listener(state);
|
|
1216
|
+
} catch {
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
notificaPeers() {
|
|
1221
|
+
const peers = this.copiaPeers();
|
|
1222
|
+
for (const listener of this.ascoltatoriPeers) {
|
|
1223
|
+
try {
|
|
1224
|
+
listener(peers);
|
|
1225
|
+
} catch {
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
controllaGenerazione(generazione) {
|
|
1230
|
+
if (generazione !== this.generazione || !this.desiderata) {
|
|
1231
|
+
throw creaErrore("offline", "Voice was stopped.");
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
richiediDipendenze() {
|
|
1235
|
+
if (this.dipendenze === null) throw creaErrore("unsupported", "Voice is not supported.");
|
|
1236
|
+
return this.dipendenze;
|
|
1237
|
+
}
|
|
1238
|
+
richiediMic() {
|
|
1239
|
+
if (this.tracciaMic === null) throw creaErrore("voice_error", "The microphone is not ready.");
|
|
1240
|
+
return this.tracciaMic;
|
|
1241
|
+
}
|
|
1242
|
+
richiediAudioContext() {
|
|
1243
|
+
if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");
|
|
1244
|
+
return this.audioContext;
|
|
1245
|
+
}
|
|
1246
|
+
permessoNegato(cause) {
|
|
1247
|
+
return typeof cause === "object" && cause !== null && "name" in cause && (cause.name === "NotAllowedError" || cause.name === "SecurityError");
|
|
1248
|
+
}
|
|
1249
|
+
mappaErrore(cause) {
|
|
1250
|
+
if (typeof cause === "object" && cause !== null && "code" in cause) {
|
|
1251
|
+
const code = cause.code;
|
|
1252
|
+
if (code === "voice_disabled" || code === "permission_denied" || code === "unsupported" || code === "spectator" || code === "offline" || code === "voice_error") return cause;
|
|
1253
|
+
return creaErrore("voice_error", "Voice could not be started.");
|
|
1254
|
+
}
|
|
1255
|
+
return creaErrore("voice_error", "Voice could not be started.");
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
// src/stanza-client/index.ts
|
|
1260
|
+
var APERTO = 1;
|
|
1261
|
+
var RITARDI_RICONNESSIONE2 = [1e3, 2e3, 4e3, 8e3];
|
|
1262
|
+
var GRAZIA_RICONNESSIONE = 6e4;
|
|
1263
|
+
var INTERVALLO_PING = 5e3;
|
|
1264
|
+
var RITARDO_FLUSH = 500;
|
|
1265
|
+
var ATTESA_ROSTER = 2e3;
|
|
1266
|
+
var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
|
|
1267
|
+
function record2(value) {
|
|
1268
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
1269
|
+
}
|
|
1270
|
+
function ingressoValido(value) {
|
|
1271
|
+
const dati = record2(value);
|
|
1272
|
+
return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
|
|
1273
|
+
}
|
|
1274
|
+
function rispostaMatchValida(value) {
|
|
1275
|
+
const dati = record2(value);
|
|
1276
|
+
const players = record2(dati?.players);
|
|
1277
|
+
return dati !== null && typeof dati.url === "string" && Number.isInteger(dati.timeoutMs) && dati.timeoutMs >= 1e3 && dati.timeoutMs <= 3e5 && players !== null && Number.isInteger(players.min) && Number.isInteger(players.max) && players.min >= 1 && players.max >= players.min;
|
|
1278
|
+
}
|
|
1279
|
+
function copiaJson(value) {
|
|
1280
|
+
return JSON.parse(JSON.stringify(value));
|
|
1281
|
+
}
|
|
1282
|
+
function applicaPatch(state, value) {
|
|
1283
|
+
let risultato = copiaJson(state);
|
|
1284
|
+
for (const operazione of value) {
|
|
1285
|
+
if (operazione.path.length === 0) {
|
|
1286
|
+
if (operazione.op !== "set") return { ok: false };
|
|
1287
|
+
risultato = copiaJson(operazione.value);
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
let contenitore = risultato;
|
|
1291
|
+
const percorso = operazione.path;
|
|
1292
|
+
for (let indice = 0; indice < percorso.length - 1; indice++) {
|
|
1293
|
+
const parte = percorso[indice];
|
|
1294
|
+
if (Array.isArray(contenitore)) {
|
|
1295
|
+
if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };
|
|
1296
|
+
contenitore = contenitore[parte];
|
|
1297
|
+
} else {
|
|
1298
|
+
const oggetto = record2(contenitore);
|
|
1299
|
+
if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {
|
|
1300
|
+
return { ok: false };
|
|
1301
|
+
}
|
|
1302
|
+
contenitore = oggetto[parte];
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
const ultima = percorso.at(-1);
|
|
1306
|
+
if (Array.isArray(contenitore)) {
|
|
1307
|
+
if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };
|
|
1308
|
+
contenitore[ultima] = copiaJson(operazione.value);
|
|
1309
|
+
} else {
|
|
1310
|
+
const oggetto = record2(contenitore);
|
|
1311
|
+
if (oggetto === null || typeof ultima !== "string") return { ok: false };
|
|
1312
|
+
if (operazione.op === "del") {
|
|
1313
|
+
if (!Object.hasOwn(oggetto, ultima)) return { ok: false };
|
|
1314
|
+
delete oggetto[ultima];
|
|
1315
|
+
} else {
|
|
1316
|
+
Object.defineProperty(oggetto, ultima, {
|
|
1317
|
+
configurable: true,
|
|
1318
|
+
enumerable: true,
|
|
1319
|
+
value: copiaJson(operazione.value),
|
|
1320
|
+
writable: true
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return { ok: true, state: risultato };
|
|
1326
|
+
}
|
|
1327
|
+
function creaApiLive(input) {
|
|
1328
|
+
const richiesta = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);
|
|
1329
|
+
async function ingresso(path, body, rinnova = false) {
|
|
1330
|
+
const value = await richiesta(path, "POST", body, rinnova);
|
|
1331
|
+
if (!ingressoValido(value)) {
|
|
1332
|
+
throw creaErrore("internal_error", "The room service returned an invalid response.");
|
|
1333
|
+
}
|
|
1334
|
+
return value;
|
|
1335
|
+
}
|
|
1336
|
+
async function match(options) {
|
|
1337
|
+
const value = await richiesta("/match", "POST", {
|
|
1338
|
+
mode: options.mode,
|
|
1339
|
+
key: options.key
|
|
1340
|
+
});
|
|
1341
|
+
if (!rispostaMatchValida(value)) {
|
|
1342
|
+
throw creaErrore("internal_error", "The matchmaking service returned an invalid response.");
|
|
1343
|
+
}
|
|
1344
|
+
return value;
|
|
1345
|
+
}
|
|
1346
|
+
return {
|
|
1347
|
+
create: (mode) => ingresso("/rooms", { mode }),
|
|
1348
|
+
joinCode: (code) => ingresso("/rooms/join", { code }),
|
|
1349
|
+
joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),
|
|
1350
|
+
match,
|
|
1351
|
+
flush: (roomId) => richiesta(
|
|
1352
|
+
`/rooms/${encodeURIComponent(roomId)}/flush`,
|
|
1353
|
+
"POST"
|
|
1354
|
+
)
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
var StanzaClient = class {
|
|
1358
|
+
constructor(roomId, codice, url, input, api, segnalaStanza) {
|
|
1359
|
+
this.roomId = roomId;
|
|
1360
|
+
this.codice = codice;
|
|
1361
|
+
this.input = input;
|
|
1362
|
+
this.api = api;
|
|
1363
|
+
this.segnalaStanza = segnalaStanza;
|
|
1364
|
+
this.statoPubblico = null;
|
|
1365
|
+
this.statoSincronizzato = null;
|
|
1366
|
+
this.tickCorrente = 0;
|
|
1367
|
+
this.seedCorrente = 0;
|
|
1368
|
+
this.statusCorrente = "lobby";
|
|
1369
|
+
this.giocatoriCorrenti = [];
|
|
1370
|
+
this.youCorrente = "";
|
|
1371
|
+
this.hostCorrente = null;
|
|
1372
|
+
this.resultCorrente = null;
|
|
1373
|
+
this.socket = null;
|
|
1374
|
+
this.seq = 0;
|
|
1375
|
+
this.scartoOrario = 0;
|
|
1376
|
+
this.timerPing = null;
|
|
1377
|
+
this.timerRiconnessione = null;
|
|
1378
|
+
this.timerFlush = null;
|
|
1379
|
+
this.flushInCorso = false;
|
|
1380
|
+
this.flushRichiesto = false;
|
|
1381
|
+
this.ritardoIndice = 0;
|
|
1382
|
+
this.tempoRiconnessione = 0;
|
|
1383
|
+
this.resyncRichiesto = false;
|
|
1384
|
+
this.terminata = false;
|
|
1385
|
+
this.lasciata = false;
|
|
1386
|
+
this.prontaRisolta = false;
|
|
1387
|
+
this.welcomeRicevuto = false;
|
|
1388
|
+
this.rosterRicevuto = false;
|
|
1389
|
+
this.timerRoster = null;
|
|
1390
|
+
this.risolviPronta = () => void 0;
|
|
1391
|
+
this.rifiutaPronta = () => void 0;
|
|
1392
|
+
this.ascoltatoriStato = /* @__PURE__ */ new Set();
|
|
1393
|
+
this.ascoltatoriGiocatori = /* @__PURE__ */ new Set();
|
|
1394
|
+
this.ascoltatoriStatus = /* @__PURE__ */ new Set();
|
|
1395
|
+
this.ascoltatoriMessaggi = /* @__PURE__ */ new Set();
|
|
1396
|
+
this.promessaPronta = new Promise((resolve, reject) => {
|
|
1397
|
+
this.risolviPronta = resolve;
|
|
1398
|
+
this.rifiutaPronta = reject;
|
|
1399
|
+
});
|
|
1400
|
+
this.voice = new VoceClient({
|
|
1401
|
+
invia: (message) => this.invia(message),
|
|
1402
|
+
connessa: () => this.socket?.readyState === APERTO && this.welcomeRicevuto && !this.terminata && !this.lasciata,
|
|
1403
|
+
you: () => this.youCorrente,
|
|
1404
|
+
giocatori: () => this.copiaGiocatori(),
|
|
1405
|
+
rosterPronto: () => {
|
|
1406
|
+
this.rosterRicevuto = true;
|
|
1407
|
+
this.risolviProntaSePossibile();
|
|
1408
|
+
}
|
|
1409
|
+
}, input, input.voce);
|
|
1410
|
+
this.apri(url);
|
|
1411
|
+
}
|
|
1412
|
+
get state() {
|
|
1413
|
+
return this.statoPubblico;
|
|
1414
|
+
}
|
|
1415
|
+
get tick() {
|
|
1416
|
+
return this.tickCorrente;
|
|
1417
|
+
}
|
|
1418
|
+
get seed() {
|
|
1419
|
+
return this.seedCorrente;
|
|
1420
|
+
}
|
|
1421
|
+
get status() {
|
|
1422
|
+
return this.statusCorrente;
|
|
1423
|
+
}
|
|
1424
|
+
get players() {
|
|
1425
|
+
return this.copiaGiocatori();
|
|
1426
|
+
}
|
|
1427
|
+
get you() {
|
|
1428
|
+
return this.youCorrente;
|
|
1429
|
+
}
|
|
1430
|
+
get host() {
|
|
1431
|
+
return this.hostCorrente;
|
|
1432
|
+
}
|
|
1433
|
+
get code() {
|
|
1434
|
+
return this.codice;
|
|
1435
|
+
}
|
|
1436
|
+
get result() {
|
|
1437
|
+
return this.resultCorrente;
|
|
1438
|
+
}
|
|
1439
|
+
pronta() {
|
|
1440
|
+
return this.promessaPronta;
|
|
1441
|
+
}
|
|
1442
|
+
invite() {
|
|
1443
|
+
return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };
|
|
1444
|
+
}
|
|
1445
|
+
onState(listener) {
|
|
1446
|
+
this.ascoltatoriStato.add(listener);
|
|
1447
|
+
return () => {
|
|
1448
|
+
this.ascoltatoriStato.delete(listener);
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
onPlayers(listener) {
|
|
1452
|
+
this.ascoltatoriGiocatori.add(listener);
|
|
1453
|
+
return () => {
|
|
1454
|
+
this.ascoltatoriGiocatori.delete(listener);
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
onStatus(listener) {
|
|
1458
|
+
this.ascoltatoriStatus.add(listener);
|
|
1459
|
+
return () => {
|
|
1460
|
+
this.ascoltatoriStatus.delete(listener);
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
onMessage(listener) {
|
|
1464
|
+
this.ascoltatoriMessaggi.add(listener);
|
|
1465
|
+
return () => {
|
|
1466
|
+
this.ascoltatoriMessaggi.delete(listener);
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
send(message) {
|
|
1470
|
+
const prossimo = this.seq + 1;
|
|
1471
|
+
this.invia({ t: "msg", seq: prossimo, m: message });
|
|
1472
|
+
this.seq = prossimo;
|
|
1473
|
+
}
|
|
1474
|
+
ready(ready) {
|
|
1475
|
+
this.invia({ t: "ready", ready });
|
|
1476
|
+
}
|
|
1477
|
+
setRole(role) {
|
|
1478
|
+
this.invia({ t: "role", role });
|
|
1479
|
+
}
|
|
1480
|
+
setTeam(team) {
|
|
1481
|
+
this.invia({ t: "team", team });
|
|
1482
|
+
}
|
|
1483
|
+
start() {
|
|
1484
|
+
this.invia({ t: "start" });
|
|
1485
|
+
}
|
|
1486
|
+
leave() {
|
|
1487
|
+
if (this.lasciata) return;
|
|
1488
|
+
this.voice.leave();
|
|
1489
|
+
this.lasciata = true;
|
|
1490
|
+
this.segnalaStanza(null);
|
|
1491
|
+
if (this.socket?.readyState === APERTO) this.invia({ t: "leave" });
|
|
1492
|
+
this.termina(1e3);
|
|
1493
|
+
}
|
|
1494
|
+
serverTime() {
|
|
1495
|
+
return this.input.ora() + this.scartoOrario;
|
|
1496
|
+
}
|
|
1497
|
+
copiaGiocatori() {
|
|
1498
|
+
return this.giocatoriCorrenti.map((player) => ({ ...player }));
|
|
1499
|
+
}
|
|
1500
|
+
notifica(listeners, ...args) {
|
|
1501
|
+
for (const listener of listeners) {
|
|
1502
|
+
try {
|
|
1503
|
+
listener(...args);
|
|
1504
|
+
} catch {
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
invia(message) {
|
|
1509
|
+
if (this.socket?.readyState !== APERTO) {
|
|
1510
|
+
throw creaErrore("offline", "The room is reconnecting.");
|
|
1511
|
+
}
|
|
1512
|
+
let frame;
|
|
1513
|
+
try {
|
|
1514
|
+
frame = JSON.stringify(message);
|
|
1515
|
+
} catch {
|
|
1516
|
+
throw creaErrore("invalid_request", "Room messages must be valid JSON.");
|
|
1517
|
+
}
|
|
1518
|
+
this.socket.send(frame);
|
|
1519
|
+
}
|
|
1520
|
+
apri(url) {
|
|
1521
|
+
let socket;
|
|
1522
|
+
try {
|
|
1523
|
+
socket = this.input.apriSocket(url);
|
|
1524
|
+
} catch {
|
|
1525
|
+
this.programmaRiconnessione();
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
this.socket = socket;
|
|
1529
|
+
socket.addEventListener("open", () => {
|
|
1530
|
+
if (this.socket === socket) this.avviaPing();
|
|
1531
|
+
});
|
|
1532
|
+
socket.addEventListener("message", (evento) => {
|
|
1533
|
+
if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);
|
|
1534
|
+
});
|
|
1535
|
+
socket.addEventListener("close", (evento) => {
|
|
1536
|
+
if (this.socket === socket) this.chiuso(evento.code);
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
avviaPing() {
|
|
1540
|
+
if (this.timerPing !== null) this.input.clearInterval(this.timerPing);
|
|
1541
|
+
this.timerPing = this.input.setInterval(() => {
|
|
1542
|
+
if (this.socket?.readyState !== APERTO) return;
|
|
1543
|
+
try {
|
|
1544
|
+
this.invia({ t: "ping", c: this.input.ora() });
|
|
1545
|
+
} catch {
|
|
1546
|
+
}
|
|
1547
|
+
}, INTERVALLO_PING);
|
|
1548
|
+
}
|
|
1549
|
+
fermaPing() {
|
|
1550
|
+
if (this.timerPing === null) return;
|
|
1551
|
+
this.input.clearInterval(this.timerPing);
|
|
1552
|
+
this.timerPing = null;
|
|
1553
|
+
}
|
|
1554
|
+
ricevi(frame) {
|
|
1555
|
+
let dati;
|
|
1556
|
+
try {
|
|
1557
|
+
const value = JSON.parse(frame);
|
|
1558
|
+
const oggetto = record2(value);
|
|
1559
|
+
if (oggetto === null || typeof oggetto.t !== "string") return;
|
|
1560
|
+
dati = oggetto;
|
|
1561
|
+
} catch {
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
try {
|
|
1565
|
+
if (dati.t === "welcome") this.riceviWelcome(dati);
|
|
1566
|
+
else if (dati.t === "players") this.riceviGiocatori(dati.players);
|
|
1567
|
+
else if (dati.t === "status") this.riceviStatus(dati);
|
|
1568
|
+
else if (dati.t === "state") this.riceviDiff(dati);
|
|
1569
|
+
else if (dati.t === "snapshot") this.riceviSnapshot(dati);
|
|
1570
|
+
else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));
|
|
1571
|
+
else if (dati.t === "pong") this.riceviPong(dati);
|
|
1572
|
+
else if (dati.t === "flush") this.richiediFlush();
|
|
1573
|
+
else if (dati.t === "voice") this.voice.ricevi(dati);
|
|
1574
|
+
} catch {
|
|
1575
|
+
if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
riceviWelcome(dati) {
|
|
1579
|
+
const room = dati.room;
|
|
1580
|
+
if (room.id !== this.roomId) return;
|
|
1581
|
+
this.youCorrente = dati.you;
|
|
1582
|
+
this.seedCorrente = room.seed;
|
|
1583
|
+
this.hostCorrente = room.host;
|
|
1584
|
+
this.statusCorrente = room.status;
|
|
1585
|
+
this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
|
|
1586
|
+
this.aggiornaStato(dati.state, room.tick, room.serverTime);
|
|
1587
|
+
this.scartoOrario = room.serverTime - this.input.ora();
|
|
1588
|
+
this.resyncRichiesto = false;
|
|
1589
|
+
this.welcomeRicevuto = true;
|
|
1590
|
+
if (!this.rosterRicevuto && this.timerRoster === null) {
|
|
1591
|
+
this.timerRoster = this.input.setTimeout(() => {
|
|
1592
|
+
this.timerRoster = null;
|
|
1593
|
+
this.rosterRicevuto = true;
|
|
1594
|
+
this.risolviProntaSePossibile();
|
|
1595
|
+
}, ATTESA_ROSTER);
|
|
1596
|
+
}
|
|
1597
|
+
this.ritardoIndice = 0;
|
|
1598
|
+
this.tempoRiconnessione = 0;
|
|
1599
|
+
this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
|
|
1600
|
+
this.voice.giocatoriCambiati();
|
|
1601
|
+
this.voice.socketRiconnesso();
|
|
1602
|
+
this.notifica(
|
|
1603
|
+
this.ascoltatoriStatus,
|
|
1604
|
+
this.statusCorrente,
|
|
1605
|
+
this.resultCorrente,
|
|
1606
|
+
room.serverTime
|
|
1607
|
+
);
|
|
1608
|
+
this.risolviProntaSePossibile();
|
|
1609
|
+
}
|
|
1610
|
+
riceviGiocatori(value) {
|
|
1611
|
+
this.giocatoriCorrenti = value.map((player) => ({ ...player }));
|
|
1612
|
+
if (!this.giocatoriCorrenti.some(
|
|
1613
|
+
(player) => player.id === this.hostCorrente && player.connected
|
|
1614
|
+
)) {
|
|
1615
|
+
this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;
|
|
1616
|
+
}
|
|
1617
|
+
this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
|
|
1618
|
+
this.voice.giocatoriCambiati();
|
|
1619
|
+
}
|
|
1620
|
+
riceviStatus(dati) {
|
|
1621
|
+
this.statusCorrente = dati.status;
|
|
1622
|
+
this.resultCorrente = copiaJson(dati.result);
|
|
1623
|
+
if (dati.status === "ended") {
|
|
1624
|
+
this.terminata = true;
|
|
1625
|
+
this.segnalaStanza(null);
|
|
1626
|
+
this.voice.termina();
|
|
1627
|
+
this.fermaPing();
|
|
1628
|
+
this.fermaRiconnessione();
|
|
1629
|
+
}
|
|
1630
|
+
this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
|
|
1631
|
+
}
|
|
1632
|
+
riceviDiff(dati) {
|
|
1633
|
+
if (dati.base !== this.tickCorrente) {
|
|
1634
|
+
this.chiediResync();
|
|
1635
|
+
return;
|
|
1636
|
+
}
|
|
1637
|
+
const risultato = applicaPatch(this.statoSincronizzato, dati.patch);
|
|
1638
|
+
if (!risultato.ok) {
|
|
1639
|
+
this.chiediResync();
|
|
1640
|
+
return;
|
|
1641
|
+
}
|
|
1642
|
+
this.resyncRichiesto = false;
|
|
1643
|
+
this.aggiornaStato(risultato.state, dati.tick, dati.serverTime);
|
|
1644
|
+
}
|
|
1645
|
+
riceviSnapshot(dati) {
|
|
1646
|
+
if (dati.tick < this.tickCorrente) return;
|
|
1647
|
+
this.resyncRichiesto = false;
|
|
1648
|
+
this.aggiornaStato(dati.state, dati.tick, dati.serverTime);
|
|
1649
|
+
}
|
|
1650
|
+
aggiornaStato(state, tick, serverTime) {
|
|
1651
|
+
this.statoSincronizzato = copiaJson(state);
|
|
1652
|
+
this.statoPubblico = copiaJson(state);
|
|
1653
|
+
this.tickCorrente = tick;
|
|
1654
|
+
this.notifica(this.ascoltatoriStato, this.statoPubblico, tick, serverTime);
|
|
1655
|
+
}
|
|
1656
|
+
chiediResync() {
|
|
1657
|
+
if (this.resyncRichiesto || this.socket?.readyState !== APERTO) return;
|
|
1658
|
+
this.resyncRichiesto = true;
|
|
1659
|
+
try {
|
|
1660
|
+
this.invia({ t: "resync" });
|
|
1661
|
+
} catch {
|
|
1662
|
+
this.resyncRichiesto = false;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
riceviPong(dati) {
|
|
1666
|
+
this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;
|
|
1667
|
+
}
|
|
1668
|
+
chiuso(code) {
|
|
1669
|
+
this.socket = null;
|
|
1670
|
+
this.welcomeRicevuto = false;
|
|
1671
|
+
this.fermaPing();
|
|
1672
|
+
if (CHIUSURE_DEFINITIVE.has(code)) {
|
|
1673
|
+
this.termina(code);
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
if (this.lasciata || this.terminata) return;
|
|
1677
|
+
this.voice.socketDisconnesso();
|
|
1678
|
+
this.programmaRiconnessione();
|
|
1679
|
+
}
|
|
1680
|
+
programmaRiconnessione() {
|
|
1681
|
+
if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;
|
|
1682
|
+
const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);
|
|
1683
|
+
const ritardo = RITARDI_RICONNESSIONE2[indice];
|
|
1684
|
+
if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {
|
|
1685
|
+
this.termina("timeout");
|
|
1686
|
+
return;
|
|
1687
|
+
}
|
|
1688
|
+
this.ritardoIndice++;
|
|
1689
|
+
this.tempoRiconnessione += ritardo;
|
|
1690
|
+
this.timerRiconnessione = this.input.setTimeout(() => {
|
|
1691
|
+
this.timerRiconnessione = null;
|
|
1692
|
+
void this.riconnetti();
|
|
1693
|
+
}, ritardo);
|
|
1694
|
+
}
|
|
1695
|
+
async riconnetti() {
|
|
1696
|
+
if (this.terminata || this.lasciata) return;
|
|
1697
|
+
try {
|
|
1698
|
+
const ingresso = await this.api.joinRoom(this.roomId);
|
|
1699
|
+
const codiceCambiato = this.codice !== ingresso.code;
|
|
1700
|
+
this.codice = ingresso.code;
|
|
1701
|
+
if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {
|
|
1702
|
+
this.segnalaStanza({ code: this.codice });
|
|
1703
|
+
}
|
|
1704
|
+
this.apri(ingresso.url);
|
|
1705
|
+
} catch {
|
|
1706
|
+
this.programmaRiconnessione();
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
fermaRiconnessione() {
|
|
1710
|
+
if (this.timerRiconnessione === null) return;
|
|
1711
|
+
this.input.clearTimeout(this.timerRiconnessione);
|
|
1712
|
+
this.timerRiconnessione = null;
|
|
1713
|
+
}
|
|
1714
|
+
termina(code) {
|
|
1715
|
+
const risultato = { closed: code };
|
|
1716
|
+
const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
|
|
1717
|
+
this.terminata = true;
|
|
1718
|
+
this.segnalaStanza(null);
|
|
1719
|
+
this.statusCorrente = "ended";
|
|
1720
|
+
this.resultCorrente = risultato;
|
|
1721
|
+
this.voice.termina();
|
|
1722
|
+
this.fermaPing();
|
|
1723
|
+
this.fermaRiconnessione();
|
|
1724
|
+
if (cambiato) this.notifica(this.ascoltatoriStatus, "ended", risultato, this.serverTime());
|
|
1725
|
+
if (!this.prontaRisolta) {
|
|
1726
|
+
this.prontaRisolta = true;
|
|
1727
|
+
const codici = {
|
|
1728
|
+
4003: "kicked",
|
|
1729
|
+
4004: "room_ended",
|
|
1730
|
+
4005: "version_closed",
|
|
1731
|
+
4006: "replaced"
|
|
1732
|
+
};
|
|
1733
|
+
const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";
|
|
1734
|
+
this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
risolviProntaSePossibile() {
|
|
1738
|
+
if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;
|
|
1739
|
+
if (this.timerRoster !== null) {
|
|
1740
|
+
this.input.clearTimeout(this.timerRoster);
|
|
1741
|
+
this.timerRoster = null;
|
|
1742
|
+
}
|
|
1743
|
+
this.prontaRisolta = true;
|
|
1744
|
+
if (!this.terminata && !this.lasciata) this.segnalaStanza({ code: this.codice });
|
|
1745
|
+
this.risolviPronta();
|
|
1746
|
+
}
|
|
1747
|
+
richiediFlush() {
|
|
1748
|
+
this.flushRichiesto = true;
|
|
1749
|
+
if (this.flushInCorso || this.timerFlush !== null) return;
|
|
1750
|
+
this.timerFlush = this.input.setTimeout(() => {
|
|
1751
|
+
this.timerFlush = null;
|
|
1752
|
+
void this.eseguiFlush();
|
|
1753
|
+
}, RITARDO_FLUSH);
|
|
1754
|
+
}
|
|
1755
|
+
async eseguiFlush() {
|
|
1756
|
+
if (this.flushInCorso || !this.flushRichiesto) return;
|
|
1757
|
+
this.flushInCorso = true;
|
|
1758
|
+
this.flushRichiesto = false;
|
|
1759
|
+
try {
|
|
1760
|
+
await this.api.flush(this.roomId);
|
|
1761
|
+
} catch {
|
|
1762
|
+
} finally {
|
|
1763
|
+
this.flushInCorso = false;
|
|
1764
|
+
if (this.flushRichiesto) this.richiediFlush();
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
function creaStanzeOffline(invited = null) {
|
|
1769
|
+
return {
|
|
1770
|
+
invited,
|
|
1771
|
+
async create() {
|
|
1772
|
+
throw erroreOffline();
|
|
1773
|
+
},
|
|
1774
|
+
async join() {
|
|
1775
|
+
throw erroreOffline();
|
|
1776
|
+
},
|
|
1777
|
+
async match() {
|
|
1778
|
+
throw erroreOffline();
|
|
1779
|
+
}
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
function creaGestoreStanze(input, invited) {
|
|
1783
|
+
const api = creaApiLive(input);
|
|
1784
|
+
let haSegnalato = false;
|
|
1785
|
+
let ultimoCodice = null;
|
|
1786
|
+
const segnalaStanza = (room) => {
|
|
1787
|
+
const codice = room?.code ?? null;
|
|
1788
|
+
if (haSegnalato && codice === ultimoCodice) return;
|
|
1789
|
+
haSegnalato = true;
|
|
1790
|
+
ultimoCodice = codice;
|
|
1791
|
+
input.segnalaStanza?.(room);
|
|
1792
|
+
};
|
|
1793
|
+
const collega = async (ingresso) => {
|
|
1794
|
+
const stanza = new StanzaClient(
|
|
1795
|
+
ingresso.roomId,
|
|
1796
|
+
ingresso.code,
|
|
1797
|
+
ingresso.url,
|
|
1798
|
+
input,
|
|
1799
|
+
api,
|
|
1800
|
+
segnalaStanza
|
|
1801
|
+
);
|
|
1802
|
+
await stanza.pronta();
|
|
1803
|
+
return stanza;
|
|
1804
|
+
};
|
|
1805
|
+
const attendiMatch = (url, options) => new Promise((resolve, reject) => {
|
|
1806
|
+
let socket;
|
|
1807
|
+
let conclusa = false;
|
|
1808
|
+
const pulisci = () => {
|
|
1809
|
+
socket.removeEventListener("message", ricevi);
|
|
1810
|
+
socket.removeEventListener("close", chiuso);
|
|
1811
|
+
socket.removeEventListener("error", caduto);
|
|
1812
|
+
options.signal?.removeEventListener("abort", annulla);
|
|
1813
|
+
};
|
|
1814
|
+
const chiudi = () => {
|
|
1815
|
+
try {
|
|
1816
|
+
socket.close(1e3);
|
|
1817
|
+
} catch {
|
|
1818
|
+
}
|
|
1819
|
+
};
|
|
1820
|
+
const fallisci = (errore, chiudiSocket) => {
|
|
1821
|
+
if (conclusa) return;
|
|
1822
|
+
conclusa = true;
|
|
1823
|
+
pulisci();
|
|
1824
|
+
if (chiudiSocket) chiudi();
|
|
1825
|
+
reject(errore);
|
|
1826
|
+
};
|
|
1827
|
+
function annulla() {
|
|
1828
|
+
fallisci(
|
|
1829
|
+
creaErrore("cancelled", "The matchmaking search was cancelled."),
|
|
1830
|
+
true
|
|
1831
|
+
);
|
|
1832
|
+
}
|
|
1833
|
+
function chiuso() {
|
|
1834
|
+
fallisci(erroreOffline(), false);
|
|
1835
|
+
}
|
|
1836
|
+
function caduto() {
|
|
1837
|
+
fallisci(erroreOffline(), true);
|
|
1838
|
+
}
|
|
1839
|
+
function ricevi(evento) {
|
|
1840
|
+
let dati = null;
|
|
1841
|
+
try {
|
|
1842
|
+
dati = typeof evento.data === "string" ? record2(JSON.parse(evento.data)) : null;
|
|
1843
|
+
} catch {
|
|
1844
|
+
}
|
|
1845
|
+
if (dati === null || typeof dati.t !== "string") {
|
|
1846
|
+
fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
|
|
1847
|
+
return;
|
|
1848
|
+
}
|
|
1849
|
+
if (dati.t === "waiting") {
|
|
1850
|
+
if (!Number.isInteger(dati.players) || !Number.isInteger(dati.min) || !Number.isInteger(dati.max)) {
|
|
1851
|
+
fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
|
|
1852
|
+
return;
|
|
1853
|
+
}
|
|
1854
|
+
try {
|
|
1855
|
+
options.onWaiting?.({
|
|
1856
|
+
players: dati.players,
|
|
1857
|
+
min: dati.min,
|
|
1858
|
+
max: dati.max
|
|
1859
|
+
});
|
|
1860
|
+
} catch {
|
|
1861
|
+
}
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
if (dati.t === "matched") {
|
|
1865
|
+
if (!ingressoValido(dati)) {
|
|
1866
|
+
fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
|
|
1867
|
+
return;
|
|
1868
|
+
}
|
|
1869
|
+
conclusa = true;
|
|
1870
|
+
pulisci();
|
|
1871
|
+
chiudi();
|
|
1872
|
+
resolve(dati);
|
|
1873
|
+
return;
|
|
1874
|
+
}
|
|
1875
|
+
if (dati.t === "no_match") {
|
|
1876
|
+
fallisci(creaErrore("no_match", "No match was found before the timeout."), true);
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
if (dati.t === "error") {
|
|
1880
|
+
fallisci(creaErrore(
|
|
1881
|
+
typeof dati.code === "string" ? dati.code : "internal_error",
|
|
1882
|
+
typeof dati.message === "string" ? dati.message : "The matchmaking service could not complete the search."
|
|
1883
|
+
), true);
|
|
1884
|
+
return;
|
|
1885
|
+
}
|
|
1886
|
+
if (dati.t !== "pong") {
|
|
1887
|
+
fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
try {
|
|
1891
|
+
socket = input.apriSocket(url);
|
|
1892
|
+
} catch {
|
|
1893
|
+
reject(erroreOffline());
|
|
1894
|
+
return;
|
|
1895
|
+
}
|
|
1896
|
+
socket.addEventListener("message", ricevi);
|
|
1897
|
+
socket.addEventListener("close", chiuso);
|
|
1898
|
+
socket.addEventListener("error", caduto);
|
|
1899
|
+
options.signal?.addEventListener("abort", annulla, { once: true });
|
|
1900
|
+
if (options.signal?.aborted === true) annulla();
|
|
1901
|
+
});
|
|
1902
|
+
return {
|
|
1903
|
+
invited,
|
|
1904
|
+
async create(options) {
|
|
1905
|
+
return collega(await api.create(options.mode));
|
|
1906
|
+
},
|
|
1907
|
+
async join(code) {
|
|
1908
|
+
const scelto = code ?? invited;
|
|
1909
|
+
if (scelto === null || scelto === void 0 || scelto.length === 0) {
|
|
1910
|
+
throw creaErrore("invalid_request", "A room invitation code is required.");
|
|
1911
|
+
}
|
|
1912
|
+
return collega(await api.joinCode(scelto));
|
|
1913
|
+
},
|
|
1914
|
+
async match(options) {
|
|
1915
|
+
const annullata = () => options.signal?.aborted === true;
|
|
1916
|
+
if (annullata()) {
|
|
1917
|
+
throw creaErrore("cancelled", "The matchmaking search was cancelled.");
|
|
1918
|
+
}
|
|
1919
|
+
const risposta = await api.match(options);
|
|
1920
|
+
if (annullata()) {
|
|
1921
|
+
throw creaErrore("cancelled", "The matchmaking search was cancelled.");
|
|
1922
|
+
}
|
|
1923
|
+
return collega(await attendiMatch(risposta.url, options));
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
|
|
233
1928
|
// src/standalone.ts
|
|
234
1929
|
var PREFISSO = "caisual:save:";
|
|
235
1930
|
var CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
@@ -292,7 +1987,7 @@ function creaSave(archivio, ora) {
|
|
|
292
1987
|
}
|
|
293
1988
|
};
|
|
294
1989
|
}
|
|
295
|
-
async function creaStandalone(input) {
|
|
1990
|
+
async function creaStandalone(input, invited = null) {
|
|
296
1991
|
const day = giornoUtc(input.ora());
|
|
297
1992
|
const seed = await calcolaSeed(input.hostname, day, input.subtle);
|
|
298
1993
|
return {
|
|
@@ -308,7 +2003,8 @@ async function creaStandalone(input) {
|
|
|
308
2003
|
async top(_board, opzioni = {}) {
|
|
309
2004
|
return { day: opzioni.daily ? day : null, entries: [], me: null };
|
|
310
2005
|
}
|
|
311
|
-
}
|
|
2006
|
+
},
|
|
2007
|
+
room: creaStanzeOffline(invited)
|
|
312
2008
|
};
|
|
313
2009
|
}
|
|
314
2010
|
|
|
@@ -330,7 +2026,7 @@ function archivioReale() {
|
|
|
330
2026
|
return null;
|
|
331
2027
|
}
|
|
332
2028
|
}
|
|
333
|
-
function
|
|
2029
|
+
function dipendenzeReali2() {
|
|
334
2030
|
return {
|
|
335
2031
|
finestra: typeof window === "undefined" ? null : window,
|
|
336
2032
|
documento: typeof document === "undefined" ? null : document,
|
|
@@ -338,7 +2034,8 @@ function dipendenzeReali() {
|
|
|
338
2034
|
archivio: archivioReale(),
|
|
339
2035
|
hostname: typeof location === "undefined" ? "" : location.hostname,
|
|
340
2036
|
subtle: globalThis.crypto.subtle,
|
|
341
|
-
ora: Date.now
|
|
2037
|
+
ora: Date.now,
|
|
2038
|
+
sonda: () => probeDevice()
|
|
342
2039
|
};
|
|
343
2040
|
}
|
|
344
2041
|
async function connetti(input) {
|
|
@@ -358,7 +2055,8 @@ async function connetti(input) {
|
|
|
358
2055
|
handshake.porta,
|
|
359
2056
|
input.finestra,
|
|
360
2057
|
input.ora,
|
|
361
|
-
input.timeoutRinnovo
|
|
2058
|
+
input.timeoutRinnovo,
|
|
2059
|
+
"portal"
|
|
362
2060
|
);
|
|
363
2061
|
const api = creaClienteApi(appOrigin, input.fetcher, biglietto);
|
|
364
2062
|
const prima = input.ora();
|
|
@@ -366,10 +2064,40 @@ async function connetti(input) {
|
|
|
366
2064
|
try {
|
|
367
2065
|
me = await api.me();
|
|
368
2066
|
} catch {
|
|
369
|
-
return creaStandalone(input);
|
|
2067
|
+
return creaStandalone(input, handshake.invite);
|
|
370
2068
|
}
|
|
371
2069
|
const dopo = input.ora();
|
|
372
2070
|
const scartoOrario = me.serverTime - (prima + dopo) / 2;
|
|
2071
|
+
const room = handshake.live === null ? creaStanzeOffline(handshake.invite) : creaGestoreStanze({
|
|
2072
|
+
appOrigin,
|
|
2073
|
+
liveOrigin: handshake.live,
|
|
2074
|
+
fetcher: input.fetcher,
|
|
2075
|
+
biglietto: creaGestoreBiglietto(
|
|
2076
|
+
null,
|
|
2077
|
+
handshake.porta,
|
|
2078
|
+
input.finestra,
|
|
2079
|
+
input.ora,
|
|
2080
|
+
input.timeoutRinnovo,
|
|
2081
|
+
"live"
|
|
2082
|
+
),
|
|
2083
|
+
apriSocket(url) {
|
|
2084
|
+
if (input.apriSocket !== void 0) return input.apriSocket(url);
|
|
2085
|
+
if (typeof WebSocket === "undefined") throw erroreOffline();
|
|
2086
|
+
return new WebSocket(url);
|
|
2087
|
+
},
|
|
2088
|
+
ora: input.ora,
|
|
2089
|
+
setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout),
|
|
2090
|
+
clearTimeout: (id) => globalThis.clearTimeout(id),
|
|
2091
|
+
setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),
|
|
2092
|
+
clearInterval: (id) => globalThis.clearInterval(id),
|
|
2093
|
+
voce: input.voce,
|
|
2094
|
+
segnalaStanza(room2) {
|
|
2095
|
+
try {
|
|
2096
|
+
handshake.porta.postMessage({ type: "caisual:room", room: room2 });
|
|
2097
|
+
} catch {
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
}, handshake.invite);
|
|
373
2101
|
return {
|
|
374
2102
|
connected: true,
|
|
375
2103
|
player: me.player,
|
|
@@ -391,14 +2119,42 @@ async function connetti(input) {
|
|
|
391
2119
|
}
|
|
392
2120
|
},
|
|
393
2121
|
top: (board, opzioni = {}) => api.boardTop(board, opzioni)
|
|
394
|
-
}
|
|
2122
|
+
},
|
|
2123
|
+
room
|
|
395
2124
|
};
|
|
396
2125
|
}
|
|
397
|
-
function
|
|
2126
|
+
function dispositivoSconosciuto() {
|
|
2127
|
+
return {
|
|
2128
|
+
webgl2: false,
|
|
2129
|
+
webgpu: false,
|
|
2130
|
+
wasm: false,
|
|
2131
|
+
threads: false,
|
|
2132
|
+
isolated: false,
|
|
2133
|
+
gpu: "none",
|
|
2134
|
+
memoryMb: null,
|
|
2135
|
+
cores: null,
|
|
2136
|
+
mobile: false,
|
|
2137
|
+
tier: "low"
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
async function attendiSonda(sonda) {
|
|
2141
|
+
let timer;
|
|
2142
|
+
try {
|
|
2143
|
+
return await Promise.race([
|
|
2144
|
+
Promise.resolve().then(sonda).catch(() => dispositivoSconosciuto()),
|
|
2145
|
+
new Promise((resolve) => {
|
|
2146
|
+
timer = globalThis.setTimeout(() => resolve(dispositivoSconosciuto()), 1500);
|
|
2147
|
+
})
|
|
2148
|
+
]);
|
|
2149
|
+
} finally {
|
|
2150
|
+
if (timer !== void 0) globalThis.clearTimeout(timer);
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
function creaKit(input = dipendenzeReali2()) {
|
|
398
2154
|
let promessa = null;
|
|
399
2155
|
return {
|
|
400
2156
|
connect() {
|
|
401
|
-
promessa ?? (promessa = connetti(input));
|
|
2157
|
+
promessa ?? (promessa = Promise.all([connetti(input), attendiSonda(input.sonda)]).then(([connessione, device]) => ({ ...connessione, device })));
|
|
402
2158
|
return promessa;
|
|
403
2159
|
}
|
|
404
2160
|
};
|