@caisual/cli 0.3.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/caisual.mjs +1133 -208
- package/package.json +4 -2
package/dist/caisual.mjs
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
// src/caisual.ts
|
|
4
4
|
import { createHash as createHash3 } from "node:crypto";
|
|
5
|
-
import { createReadStream, promises as
|
|
6
|
-
import {
|
|
5
|
+
import { createReadStream, promises as fs3 } from "node:fs";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { basename, extname as extname2, join as join3, resolve as resolve2 } from "node:path";
|
|
7
8
|
|
|
8
9
|
// ../contracts/src/slug.ts
|
|
9
10
|
var NOMI_RISERVATI = [
|
|
@@ -64,8 +65,10 @@ var CAMPI = /* @__PURE__ */ new Set([
|
|
|
64
65
|
"visibility",
|
|
65
66
|
"network",
|
|
66
67
|
"isolated",
|
|
68
|
+
"requires",
|
|
67
69
|
"players",
|
|
68
70
|
"lobby",
|
|
71
|
+
"persistent",
|
|
69
72
|
"roles",
|
|
70
73
|
"teams",
|
|
71
74
|
"voice",
|
|
@@ -76,8 +79,10 @@ var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
|
|
|
76
79
|
var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
|
|
77
80
|
var VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);
|
|
78
81
|
var VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);
|
|
82
|
+
var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
|
|
79
83
|
var TAG = /^[a-z0-9-]+$/;
|
|
80
84
|
var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
85
|
+
var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
81
86
|
function oggetto(value) {
|
|
82
87
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
83
88
|
return value;
|
|
@@ -213,6 +218,41 @@ function validaManifest(valore) {
|
|
|
213
218
|
if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
|
|
214
219
|
else isolated = dati.isolated;
|
|
215
220
|
}
|
|
221
|
+
const requires = {
|
|
222
|
+
webgl2: false,
|
|
223
|
+
webgpu: false,
|
|
224
|
+
wasm: false,
|
|
225
|
+
threads: false,
|
|
226
|
+
memoryMb: null,
|
|
227
|
+
performance: "light"
|
|
228
|
+
};
|
|
229
|
+
if (dati.requires !== void 0) {
|
|
230
|
+
const value = oggetto(dati.requires);
|
|
231
|
+
if (value === null) errori.push("requires: must be an object.");
|
|
232
|
+
else {
|
|
233
|
+
for (const campo of Object.keys(value)) {
|
|
234
|
+
if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {
|
|
235
|
+
errori.push(`requires.${campo}: unknown field.`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
|
|
239
|
+
if (value[campo] === void 0) continue;
|
|
240
|
+
if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);
|
|
241
|
+
else requires[campo] = value[campo];
|
|
242
|
+
}
|
|
243
|
+
if (value.memoryMb !== void 0) {
|
|
244
|
+
if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {
|
|
245
|
+
errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");
|
|
246
|
+
} else requires.memoryMb = value.memoryMb;
|
|
247
|
+
}
|
|
248
|
+
if (value.performance !== void 0) {
|
|
249
|
+
if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {
|
|
250
|
+
errori.push("requires.performance: must be light, medium, or heavy.");
|
|
251
|
+
} else requires.performance = value.performance;
|
|
252
|
+
}
|
|
253
|
+
if (requires.threads && !isolated) errori.push("requires.threads: needs isolated: true.");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
216
256
|
let players = { min: 1, max: 1 };
|
|
217
257
|
if (dati.players !== void 0) {
|
|
218
258
|
const value = oggetto(dati.players);
|
|
@@ -234,6 +274,11 @@ function validaManifest(valore) {
|
|
|
234
274
|
if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");
|
|
235
275
|
else lobby = dati.lobby;
|
|
236
276
|
}
|
|
277
|
+
let persistent = false;
|
|
278
|
+
if (dati.persistent !== void 0) {
|
|
279
|
+
if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
|
|
280
|
+
else persistent = dati.persistent;
|
|
281
|
+
}
|
|
237
282
|
const roles = [];
|
|
238
283
|
if (dati.roles !== void 0) {
|
|
239
284
|
if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
|
|
@@ -330,33 +375,31 @@ function validaManifest(valore) {
|
|
|
330
375
|
continue;
|
|
331
376
|
}
|
|
332
377
|
for (const campo of Object.keys(matchmaking)) {
|
|
333
|
-
if (
|
|
378
|
+
if (campo !== "key" && campo !== "timeoutMs") {
|
|
334
379
|
errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);
|
|
335
380
|
}
|
|
336
381
|
}
|
|
337
382
|
let valido = true;
|
|
338
383
|
const key = [];
|
|
339
|
-
if (!Array.isArray(matchmaking.key) || matchmaking.key.length
|
|
340
|
-
errori.push(`modes[${indice}].matchmaking.key: must
|
|
384
|
+
if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {
|
|
385
|
+
errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);
|
|
341
386
|
valido = false;
|
|
342
387
|
} else for (const [keyIndice, item] of matchmaking.key.entries()) {
|
|
343
|
-
if (typeof item !== "string" ||
|
|
344
|
-
errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or
|
|
388
|
+
if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {
|
|
389
|
+
errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);
|
|
390
|
+
valido = false;
|
|
391
|
+
} else if (key.includes(item)) {
|
|
392
|
+
errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);
|
|
345
393
|
valido = false;
|
|
346
394
|
} else key.push(item);
|
|
347
395
|
}
|
|
348
|
-
if (!
|
|
349
|
-
errori.push(`modes[${indice}].matchmaking.timeoutMs: must be
|
|
350
|
-
valido = false;
|
|
351
|
-
}
|
|
352
|
-
if (matchmaking.fallback !== "ghost" && matchmaking.fallback !== "bot") {
|
|
353
|
-
errori.push(`modes[${indice}].matchmaking.fallback: must be ghost or bot.`);
|
|
396
|
+
if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {
|
|
397
|
+
errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);
|
|
354
398
|
valido = false;
|
|
355
399
|
}
|
|
356
400
|
if (valido) modes.push({ id: value.id, matchmaking: {
|
|
357
401
|
key,
|
|
358
|
-
timeoutMs: matchmaking.timeoutMs
|
|
359
|
-
fallback: matchmaking.fallback
|
|
402
|
+
timeoutMs: matchmaking.timeoutMs
|
|
360
403
|
} });
|
|
361
404
|
}
|
|
362
405
|
}
|
|
@@ -377,8 +420,10 @@ function validaManifest(valore) {
|
|
|
377
420
|
visibility,
|
|
378
421
|
network,
|
|
379
422
|
isolated,
|
|
423
|
+
requires,
|
|
380
424
|
players,
|
|
381
425
|
lobby,
|
|
426
|
+
persistent,
|
|
382
427
|
roles,
|
|
383
428
|
teams,
|
|
384
429
|
voice,
|
|
@@ -481,16 +526,127 @@ function validaServerJs(sorgente) {
|
|
|
481
526
|
}
|
|
482
527
|
|
|
483
528
|
// ../../docs/publish.md
|
|
484
|
-
var publish_default = '# Publish a game on Caisual\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version and moves the game\'s stable link to that version.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, leaderboards, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\n## Game folder\n\nUse this structure:\n\n```text\nmy-game/\n caisual.json\n server.js # optional, required only for multiplayer rooms\n client/\n index.html\n ...\n```\n\n`caisual.json` and `client/index.html` are required. Put every file used by the game under `client/`.\n\nRun `npx @caisual/cli init my-game` to create a minimal single-player folder. Run `npx @caisual/cli init --multiplayer my-game` to include a four-player lobby, a relay server, and a room client example.\n\n## caisual.json\n\nThe file must contain one JSON object. Unknown fields are rejected. This is a complete single-player example:\n\n```json\n{\n "manifest": 1,\n "id": "my-game",\n "name": "My Game",\n "description": "A short description of the game.",\n "cover": "cover.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "language": "en",\n "platform": "both",\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "isolated": false,\n "players": { "min": 1, "max": 1 },\n "lobby": false,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": []\n}\n```\n\n- `manifest` is required and must be `1`.\n- `id` is required. Use 3 to 32 lowercase ASCII letters or digits, with single hyphens only between groups. The ID becomes the URL slug. Choose it carefully because it cannot be renamed or reused after deletion.\n- `name` is required and must contain 1 to 60 characters.\n- `description` is optional, defaults to an empty string, and can contain at most 500 characters.\n- `cover` is optional. Use a relative path inside `client/`, or `null`. Do not include a query, fragment, empty segment, or parent segment.\n- `screenshots` is optional and defaults to `[]`. It accepts up to 8 relative paths inside `client/`.\n- `tags` is optional and defaults to `[]`. It accepts up to 10 values. Each value uses 1 to 24 lowercase letters, digits, or hyphens.\n- `language` is optional and defaults to `en`. Use a BCP 47 language tag such as `en`, `it`, or `pt-BR`.\n- `platform` is required. Use `desktop` when the game needs a keyboard, mouse, large display, or desktop performance. Use `mobile` when it is designed only for touch and small screens. Use `both` only after checking that layout, performance, and controls work on both.\n- `orientation` is optional and defaults to `landscape`. Use `landscape` or `portrait` to describe the intended mobile layout. The device may not honor an orientation request.\n- `input` is optional and defaults to `[]`. Include every supported input from `keyboard`, `mouse`, `touch`, and `gamepad`. Do not claim an input until the game is usable with it.\n- `visibility` is optional and defaults to `public`. Use `public` for catalog eligibility or `unlisted` for access by direct link only.\n- `network` is optional and defaults to `[]`. List every external host contacted or loaded by the game, without scheme, port, path, query, or fragment, for example `api.example.com`. If an external host is missing, the browser blocks the request. Keep the array empty when the game uses only its own files and Caisual services.\n- `isolated` is optional and defaults to `false`. Use `true` only when the game requires shared memory or threaded WebAssembly. Every external host in `network` must then send headers compatible with cross-origin isolation.\n- `players` is optional and defaults to `{ "min": 1, "max": 1 }`. Both values are integers from 1 to 16 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is optional and defaults to `false`. Use `true` when players must choose roles or teams, mark themselves ready, and wait for the host to start. With `false`, play starts when the first player enters and later players may join in progress.\n- `roles` is optional and defaults to `[]`. Each entry has an `id` of 1 to 32 lowercase letters, digits, or internal hyphens, a `min` integer from 0 to 16, and an optional `max` in the same range. Rooms enforce these capacities in the lobby.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 16, with `max` at least `min`. Rooms balance players who do not choose a team.\n- `voice` is optional and defaults to `none`. Use `room` so everyone in the room can hear each other, `team` to restrict voice to teammates, or `proximity` when `server.js` sets the gain between player pairs. Use `none` to disable voice.\n- `modes` is optional and defaults to `[]`. A mode has a unique `id` using 1 to 32 lowercase letters, digits, or internal hyphens. It may have `matchmaking` with a non-empty `key` array using the same format, a positive integer `timeoutMs`, and `fallback` set to `ghost` or `bot`.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\n## client/index.html\n\n`index.html` must be at the root of `client/`. Use relative URLs such as `./game.js` or `assets/sprite.png`. Do not use root-relative URLs such as `/game.js`, and do not use parent paths that leave the published `client/` tree.\n\nTo use player identity, saves, and leaderboards, import the kit from `/__caisual/kit/v1.js` as shown in [kit.md](./kit.md). The path `/__caisual/` is reserved: do not put game files under it.\n\nDo not register a service worker. The game runs in an iframe on its own origin inside `caisual.com`. Test it without assuming access to the parent page, parent cookies, or files outside `client/`.\n\nWhen `voice` is not `none`, the portal grants microphone access to the game iframe. The browser still asks the player for permission when the game calls `room.voice.join()`. Call it from a button click or another user gesture, not automatically when the page loads.\n\n## Multiplayer server\n\nAdd `server.js` beside `caisual.json` when the game uses rooms. It must be one ESM file with an `export default`. Its only permitted dependency is `@caisual/kit/server`, imported with either single or double quotes. Static imports from any other path, dynamic `import()`, `require()`, and CommonJS exports are rejected.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\nThe file may define the optional room callbacks documented in [kit.md](./kit.md). Server code cannot make outbound network requests. The `network` field in `caisual.json` controls only requests made by the browser client.\n\nThe source file may be at most 1,000,000 bytes. Room state must remain plain JSON and may be at most 256 KB when serialized. Each incoming player message may be at most 16 KB, and each connection may send at most 20 messages per second. Room save values may be at most 128 KB.\n\nPublish a multiplayer game with the same `npx @caisual/cli publish` command. The CLI validates `server.js`, declares its size and SHA-256 digest, and uploads it separately from browser files. The portal validates the stored source again before making the new game version current.\n\nIf the portal finds an invalid `server.js`, the command prints `The multiplayer server could not be published.` followed by diagnostic hints. The failed version is kept for diagnosis but never becomes current. If the game already has a working version, players continue to receive that version. Fix the reported problem and publish again to create a new version.\n\n## Test locally\n\nRun the local preview from the game folder before publishing:\n\n```sh\nnpx @caisual/cli dev\n```\n\nYou can pass a game folder and choose another port:\n\n```sh\nnpx @caisual/cli dev ./my-game --port 8790\n```\n\nThe command prints a portal URL and a game URL. Open the portal URL. It loads the game in an iframe with the same handshake used after publishing, so `c.connected` is `true`. Player identity, saves, leaderboards, daily data, invitations, and rooms all use local data. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Without `server.js`, the game remains single player and attempts to create a room return `no_server`.\n\nPress Ctrl+C in the terminal to stop the preview. No account or publish key is required.\n\n## Limits\n\n- At most 2,000 files per version.\n- At most 50,000,000 bytes per file.\n- At most 200,000,000 bytes for all files in one version.\n- At most 1,000,000 bytes for `server.js`.\n- Dotfiles, dot-directories, and directories named `node_modules` are ignored.\n- Symbolic links and other non-regular files are rejected.\n\nReduce or split files that exceed the per-file limit. Remove generated files that the browser does not need.\n\n## Publish\n\nUse the key supplied by the creator. Set it in the environment so it does not enter shell history as a command-line flag:\n\n```sh\nexport CAISUAL_KEY=\'ck_...\'\nnpx @caisual/cli publish\n```\n\nRun the command from the game folder, or pass the folder path after `publish`. For local portal development only, set `CAISUAL_ORIGIN` to the local HTTP origin.\n\nThe CLI validates the folder, computes every file size and SHA-256 digest, creates a new version, uploads the files, completes the version, and prints the game URL. The stable URL is `https://caisual.com/g/<id>`.\n\nThe first games from a new creator are reviewed before they can appear in the public catalog. Their stable links still work while review is pending.\n\n## Update, unlist, or delete\n\nTo update a game, change its files without changing `id`, then run `npx @caisual/cli publish` again. This creates a new version and keeps the same stable game URL.\n\nTo remove a game from the catalog, set `visibility` to `unlisted` and publish, or change visibility from the dashboard. To delete a game, use the dashboard. Deletion is permanent and its ID cannot be reused.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing.\n- `The publish API key is not valid`: create a new key in the account dashboard if the old key expired or was revoked.\n- `caisual.json is not valid`: read every reported field and rule, fix all of them, then retry.\n- `client/index.html: file not found`: place `index.html` directly under `client/`, not in a nested build folder.\n- `referenced file not found`: make sure `cover` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 50 MB`: compress, reduce, or split the asset and update its references.\n- `upload failed` or a temporary portal error: keep the files unchanged and retry the same publish command. The CLI retries temporary upload failures automatically.\n- `The multiplayer server could not be published`: read every diagnostic hint, fix `server.js`, and publish again. The failed version does not replace the current one.\n- An external browser request works locally but fails after publishing: add its host to `network` and publish a new version. Server code cannot make outbound network requests.\n- A threaded WebAssembly game fails to start: set `isolated` to `true` and verify that every declared external host supports cross-origin isolation.\n';
|
|
529
|
+
var publish_default = '# Publish a game on Caisual\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version and moves the game\'s stable link to that version.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, leaderboards, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\n## Game folder\n\nUse this structure:\n\n```text\nmy-game/\n caisual.json\n server.js # optional, required only for multiplayer rooms\n client/\n index.html\n ...\n```\n\n`caisual.json` and `client/index.html` are required. Put every file used by the game under `client/`.\n\nRun `npx @caisual/cli init my-game` to create a minimal single-player folder. Run `npx @caisual/cli init --multiplayer my-game` to include a four-player lobby, a relay server, and a room client example.\n\n## caisual.json\n\nThe file must contain one JSON object. Unknown fields are rejected. This is a complete single-player example:\n\n```json\n{\n "manifest": 1,\n "id": "my-game",\n "name": "My Game",\n "description": "A short description of the game.",\n "cover": "cover.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "language": "en",\n "platform": "both",\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "isolated": false,\n "requires": { "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" },\n "players": { "min": 1, "max": 1 },\n "lobby": false,\n "persistent": false,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": []\n}\n```\n\n- `manifest` is required and must be `1`.\n- `id` is required. Use 3 to 32 lowercase ASCII letters or digits, with single hyphens only between groups. The ID becomes the URL slug. Choose it carefully because it cannot be renamed or reused after deletion.\n- `name` is required and must contain 1 to 60 characters.\n- `description` is optional, defaults to an empty string, and can contain at most 500 characters.\n- `cover` is optional. Use a relative path inside `client/`, or `null`. Do not include a query, fragment, empty segment, or parent segment.\n- `screenshots` is optional and defaults to `[]`. It accepts up to 8 relative paths inside `client/`.\n- `tags` is optional and defaults to `[]`. It accepts up to 10 values. Each value uses 1 to 24 lowercase letters, digits, or hyphens.\n- `language` is optional and defaults to `en`. Use a BCP 47 language tag such as `en`, `it`, or `pt-BR`.\n- `platform` is required. Use `desktop` when the game needs a keyboard, mouse, large display, or desktop performance. Use `mobile` when it is designed only for touch and small screens. Use `both` only after checking that layout, performance, and controls work on both.\n- `orientation` is optional and defaults to `landscape`. Use `landscape` or `portrait` to describe the intended mobile layout. The device may not honor an orientation request.\n- `input` is optional and defaults to `[]`. Include every supported input from `keyboard`, `mouse`, `touch`, and `gamepad`. Do not claim an input until the game is usable with it.\n- `visibility` is optional and defaults to `public`. Use `public` for catalog eligibility or `unlisted` for access by direct link only.\n- `network` is optional and defaults to `[]`. List every external host contacted or loaded by the game, without scheme, port, path, query, or fragment, for example `api.example.com`. If an external host is missing, the browser blocks the request. Keep the array empty when the game uses only its own files and Caisual services.\n- `isolated` is optional and defaults to `false`. Use `true` only when the game requires shared memory or threaded WebAssembly. Every external host in `network` must then send headers compatible with cross-origin isolation.\n- `requires` is optional and defaults to `{ "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" }`. Declare the minimum capabilities the game truly needs to run. For example, a game with a WebGPU renderer and a WebGL2 fallback declares only `webgl2`. Set `threads` together with `isolated: true`. `memoryMb` accepts `null` or a multiple of 256 from 512 to 32768. Use `light`, `medium`, or `heavy` for the expected performance load.\n- `players` is optional and defaults to `{ "min": 1, "max": 1 }`. Both values are integers from 1 to 16 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is optional and defaults to `false`. Use `true` when players must choose roles or teams, mark themselves ready, and wait for the host to start. With `false`, play starts when the first player enters and later players may join in progress.\n- `persistent` is optional and defaults to `false`. Use `true` when room members must be able to return with the same code after disconnecting, including while the game is already playing. Persistent rooms expire after 30 days without activity.\n- `roles` is optional and defaults to `[]`. Each entry has an `id` of 1 to 32 lowercase letters, digits, or internal hyphens, a `min` integer from 0 to 16, and an optional `max` in the same range. Rooms enforce these capacities in the lobby.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 16, with `max` at least `min`. Rooms balance players who do not choose a team.\n- `voice` is optional and defaults to `none`. Use `room` so everyone in the room can hear each other, `team` to restrict voice to teammates, or `proximity` when `server.js` sets the gain between player pairs. Use `none` to disable voice.\n- `modes` is optional and defaults to `[]`. A mode has a unique `id` using 1 to 32 lowercase letters, digits, or internal hyphens. It may have `matchmaking` with `key`, an array of 1 to 8 unique field names, and `timeoutMs`, an integer from 1,000 to 300,000. Each field name uses 1 to 32 lowercase letters, digits, or hyphens and starts with a letter or digit.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\nWhen `requires` is not at its default, the game page checks the player\'s browser and device. It reports that the game is compatible, may run slowly, or is missing a required capability. The Play button always remains active so the player can still try the game.\n\n## client/index.html\n\n`index.html` must be at the root of `client/`. Use relative URLs such as `./game.js` or `assets/sprite.png`. Do not use root-relative URLs such as `/game.js`, and do not use parent paths that leave the published `client/` tree.\n\nTo use player identity, saves, and leaderboards, import the kit from `/__caisual/kit/v1.js` as shown in [kit.md](./kit.md). The path `/__caisual/` is reserved: do not put game files under it.\n\nDo not register a service worker. The game runs in an iframe on its own origin inside `caisual.com`. Test it without assuming access to the parent page, parent cookies, or files outside `client/`.\n\nWhen `voice` is not `none`, the portal grants microphone access to the game iframe. The browser still asks the player for permission when the game calls `room.voice.join()`. Call it from a button click or another user gesture, not automatically when the page loads.\n\n## Multiplayer server\n\nAdd `server.js` beside `caisual.json` when the game uses rooms. It is the ESM entry point and must have an `export default`. It may import local files such as `./logic/ships.js`, including `.js`, `.ts`, and `.json` files, and npm packages installed in the game folder. The CLI bundles these imports into one file both when publishing and when starting `caisual dev`.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\nThe file may define the optional room callbacks documented in [kit.md](./kit.md). Server code runs without Node.js APIs or network access. Dynamic `import()`, `require()`, and CommonJS exports are not supported. Use only pure JavaScript packages, such as a noise or vector library. A package that needs an HTTP client is not suitable. The `network` field in `caisual.json` controls only requests made by the browser client.\n\nThe bundled `server.js` may be at most 1,000,000 bytes. Room state must remain plain JSON and may be at most 256 KB when serialized. Each incoming player message may be at most 16 KB, and each connection may send at most 20 messages per second. Room save values may be at most 128 KB.\n\nPublish a multiplayer game with the same `npx @caisual/cli publish` command. When imports need bundling, the CLI prints `Bundling server.js (N KB).` The uploaded file is the bundle: the CLI validates it, declares its size and SHA-256 digest, and uploads it separately from browser files. The portal validates the stored bundle again before making the new game version current.\n\nIf the portal finds an invalid `server.js`, the command prints `The multiplayer server could not be published.` followed by diagnostic hints. The failed version is kept for diagnosis but never becomes current. If the game already has a working version, players continue to receive that version. Fix the reported problem and publish again to create a new version.\n\n## Test locally\n\nRun the local preview from the game folder before publishing:\n\n```sh\nnpx @caisual/cli dev\n```\n\nYou can pass a game folder and choose another port:\n\n```sh\nnpx @caisual/cli dev ./my-game --port 8790\n```\n\nThe command prints a portal URL and a game URL. Open the portal URL. It loads the game in an iframe with the same handshake used after publishing, so `c.connected` is `true`. Player identity, saves, leaderboards, daily data, invitations, and rooms all use local data. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Without `server.js`, the game remains single player and attempts to create a room return `no_server`.\n\nPress Ctrl+C in the terminal to stop the preview. No account or publish key is required.\n\n## Limits\n\n- At most 2,000 files per version.\n- At most 50,000,000 bytes per file.\n- At most 200,000,000 bytes for all files in one version.\n- At most 1,000,000 bytes for `server.js`.\n- Dotfiles, dot-directories, and directories named `node_modules` are ignored.\n- Symbolic links and other non-regular files are rejected.\n\nReduce or split files that exceed the per-file limit. Remove generated files that the browser does not need.\n\n## Publish\n\nUse the key supplied by the creator. Set it in the environment so it does not enter shell history as a command-line flag:\n\n```sh\nexport CAISUAL_KEY=\'ck_...\'\nnpx @caisual/cli publish\n```\n\nRun the command from the game folder, or pass the folder path after `publish`. For local portal development only, set `CAISUAL_ORIGIN` to the local HTTP origin.\n\nThe CLI validates the folder, computes every file size and SHA-256 digest, creates a new version, uploads the files, completes the version, and prints the game URL. The stable URL is `https://caisual.com/g/<id>`.\n\nBefore contacting the portal, the CLI scans browser files for common WebGL2, WebGPU, WebAssembly, and shared-memory signatures. A possible mismatch is printed to stderr with a `Warning:` prefix and never blocks publishing. Correct an accurate warning by declaring the minimum matching `requires` field, and set `isolated: true` for shared memory. If the signature belongs to unused code, remove that code from the published client bundle.\n\nThe first games from a new creator are reviewed before they can appear in the public catalog. Their stable links still work while review is pending.\n\n## Update, unlist, or delete\n\nTo update a game, change its files without changing `id`, then run `npx @caisual/cli publish` again. This creates a new version and keeps the same stable game URL.\n\nTo remove a game from the catalog, set `visibility` to `unlisted` and publish, or change visibility from the dashboard. To delete a game, use the dashboard. Deletion is permanent and its ID cannot be reused.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing.\n- `The publish API key is not valid`: create a new key in the account dashboard if the old key expired or was revoked.\n- `caisual.json is not valid`: read every reported field and rule, fix all of them, then retry.\n- `client/index.html: file not found`: place `index.html` directly under `client/`, not in a nested build folder.\n- `referenced file not found`: make sure `cover` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 50 MB`: compress, reduce, or split the asset and update its references.\n- `upload failed` or a temporary portal error: keep the files unchanged and retry the same publish command. The CLI retries temporary upload failures automatically.\n- `The multiplayer server could not be published`: read every diagnostic hint, fix `server.js`, and publish again. The failed version does not replace the current one.\n- An external browser request works locally but fails after publishing: add its host to `network` and publish a new version. Server code cannot make outbound network requests.\n- A threaded WebAssembly game fails to start: set `isolated` to `true` and verify that every declared external host supports cross-origin isolation.\n';
|
|
485
530
|
|
|
486
531
|
// ../../docs/kit.md
|
|
487
|
-
var kit_default = "# Caisual game kit\n\nThe kit gives a published game a stable player identity, cloud saves, leaderboards, a daily challenge seed, and multiplayer rooms with server-owned state.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page: the game keeps its own rendering, input, and UI.\n\n## Load the kit\n\nEvery published game can import the kit from its own origin, without a bundler and without an npm install:\n\n```html\n<script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n\n const c = await caisual.connect();\n console.log(c.player.name);\n</script>\n```\n\nGames built with a bundler can install the same module from npm:\n\n```sh\nnpm install @caisual/kit\n```\n\n```js\nimport { caisual } from '@caisual/kit';\n```\n\nBoth forms expose the same API. The module also sets `globalThis.caisual` for classic scripts that load it first.\n\nThe path `/__caisual/` is reserved on every game origin. Do not put game files under it.\n\n## Connect\n\n```js\nconst c = await caisual.connect();\n```\n\n`connect()` completes when the game is running inside caisual.com and has received its player identity, or after a short timeout when it is not. Calling it again returns the same promise.\n\n- `c.connected` is `true` inside caisual.com and `false` when the game runs on its own, for example from a local folder during development or when its files are copied elsewhere.\n- `c.player` is `{ id, name, guest }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or `\"Guest\"`. `guest` is `true` for players without an account. When a guest later signs in, saves and scores stay attached to the same `id`.\n- When not connected, `c.player` is `{ id: \"local\", name: \"Guest\", guest: true }`.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\n## Daily challenge\n\n```js\nc.daily.day; // \"2026-09-04\", the current UTC day\nc.daily.seed; // unsigned 32-bit integer, identical for every player on that day\nconst r = c.daily.random(); // number in [0, 1), deterministic from the seed\n```\n\n`c.daily.random()` is a deterministic generator initialized from `c.daily.seed`. Every `connect()` starts the sequence from the beginning, so two players who call it the same number of times get the same values. Use it to build the level of the day.\n\n`c.time.now()` returns milliseconds aligned with the portal clock. Prefer it to `Date.now()` for anything that must agree with the current day.\n\nWhen not connected, `day` comes from the local clock and `seed` from the local hostname, so a game copied elsewhere still runs.\n\n## Saves\n\nEach player has up to 32 saves per game. A save is any JSON value up to 256 KB when serialized.\n\n```js\nawait c.save.set('slot1', { level: 3, coins: 120 }); // -> { key, bytes, updatedAt }\nconst data = await c.save.get('slot1'); // -> the value, or null\nawait c.save.remove('slot1');\nconst saves = await c.save.list(); // -> [{ key, bytes, updatedAt }]\n```\n\n- Keys use 1 to 32 characters: lowercase letters, digits, `_` or `-`, starting with a letter or digit.\n- `updatedAt` is a millisecond timestamp.\n- Saves are per player and per game. Another game cannot read them.\n- When not connected, saves go to the browser's local storage on the game origin.\n\nErrors reject the promise with an `Error` whose `code` is one of `invalid_request`, `not_found`, `save_limit`, `payload_too_large`, `rate_limited`, `invalid_ticket`, `internal_error`, or `offline`.\n\n## Leaderboards\n\nA leaderboard is identified by a board id chosen by the game. Scores are non-negative integers and higher is better. Each player keeps one entry per board, and one per board per day for daily boards: the best score is kept.\n\n```js\nconst result = await c.board.submit('main', 1234);\n// -> { accepted: true, best: 1234, rank: 7, day: null }\n\nconst daily = await c.board.submit('main', 1234, { daily: true });\n// -> { accepted: true, best: 1234, rank: 7, day: \"2026-09-04\" }\n\nconst top = await c.board.top('main', { daily: true, limit: 10 });\n// -> { day: \"2026-09-04\", entries: [{ rank, name, score, guest, me }], me: { rank, score } | null }\n```\n\n- Board ids use the same format as save keys.\n- `submit` never rejects because of connectivity. When the game is not connected it resolves `{ accepted: false, reason: \"offline\" }`.\n- `best` is the score kept for this player after the submission, which can be higher than the submitted one.\n- `rank` counts players with a strictly higher score. Ties are ordered by who reached the score first.\n- Accounts and guests are ranked separately. `top()` returns account players by default; pass `guests: true` to list guests instead. `me` always refers to the current player within their own category, even beyond `limit`.\n- `limit` is 1 to 100 and defaults to 10.\n- Scores submitted from the browser are recorded as unverified. A room server can submit verified scores.\n\n## Rooms\n\nA room brings players into the same running game. Creating and joining require a published `server.js`; single-player games can ignore `c.room`.\n\n```js\nconst c = await caisual.connect();\n\nc.room.invited; // invitation code from the game page, or null\n\nconst room = await c.room.create({ mode: null });\n// Or join the invitation that opened the game:\nconst invitedRoom = await c.room.join();\n// Or enter a code supplied by the player:\nconst codedRoom = await c.room.join('ABC234');\n\nroom.code;\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nPass a mode id from the manifest to `create({ mode })`, or `null` when the game has no modes. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. Show the URL returned by `invite()` in a share button or copy action.\n\nRoom status is one of:\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: the lobby has accepted `start()` and play begins at the announced server time.\n- `playing`: the game server is running the match.\n- `ended`: the match or connection has ended. `room.result` contains the result last reported by the room. A definitive connection closure uses `{ closed: 4003 }`, `{ closed: 4004 }`, `{ closed: 4005 }`, or `{ closed: 4006 }`.\n\nThe current lobby data is available directly:\n\n```js\nroom.players; // [{ id, name, guest, role, team, ready, connected }]\nroom.you; // this player's id\nroom.host; // the current host's id, or null\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n\nif (room.you === room.host) room.start();\n```\n\n`ready`, role, team, and `start()` are lobby actions. Starting requires the host, every connected player to be ready, and the player, role, and team minimums from the manifest. Calling `start()` begins a three-second countdown. A role or team change clears that player's ready state. The built-in `spectator` role receives state but cannot send game input.\n\nThe server owns room state. Read it and react to updates, but do not assign to it or mutate nested values from the browser:\n\n```js\ndraw(room.state);\n\nconst stopState = room.onState((state, tick, serverTime) => {\n draw(state);\n});\n\nconst stopPlayers = room.onPlayers((players) => updateLobby(players));\nconst stopStatus = room.onStatus((status, result, at) => showStatus(status, result, at));\n\nstopState();\nstopPlayers();\nstopStatus();\n```\n\n`room.tick` identifies the latest state. The kit applies structural updates in order and requests a full state automatically if an update does not match the current tick. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\nSend JSON input to `onMessage` in the server definition, and receive JSON sent or broadcast by the server:\n\n```js\nroom.send({ type: 'fire', target: 3 });\n\nconst stopMessages = room.onMessage((message) => {\n showEvent(message);\n});\n```\n\nThe kit numbers outgoing inputs in increasing order. It automatically reconnects temporary failures with delays of 1, 2, 4, then 8 seconds, for at most the room's 60-second grace period. Each attempt gets a fresh room token. A successful reconnect replaces local state with a full server state. Inputs sent while reconnecting throw an error with `code: \"offline\"`.\n\nCall `room.leave()` for an intentional departure. The kit does not reconnect after leaving, being kicked, the room ending, the published version closing, or the same player opening the room in another tab.\n\nRoom creation and joining reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `no_server`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, both `create` and `join` reject with `offline`.\n\nEvery `onState`, `onPlayers`, `onStatus`, and `onMessage` call returns a function that removes that listener.\n\n## Voice\n\nEvery room has a `room.voice` object. Voice is disabled by default and is enabled with the manifest's `voice` field. A game should offer an explicit control because `join()` must be called from a click or another user gesture so the browser can request microphone permission and start audio.\n\n```js\nconst micButton = document.querySelector('#mic');\nconst voiceList = document.querySelector('#voice-list');\n\nfunction renderVoice(peers = room.voice.peers) {\n voiceList.replaceChildren(...peers.map((peer) => {\n const item = document.createElement('li');\n const player = room.players.find((entry) => entry.id === peer.id);\n item.textContent = `${player?.name ?? peer.id}: ${\n peer.speaking ? 'speaking' : peer.muted ? 'muted' : 'quiet'\n }`;\n return item;\n }));\n micButton.textContent = room.voice.state === 'off'\n ? 'Join voice'\n : room.voice.muted ? 'Unmute' : 'Mute';\n}\n\nmicButton.addEventListener('click', async () => {\n if (room.voice.state === 'off') await room.voice.join();\n else room.voice.mute(!room.voice.muted);\n renderVoice();\n});\n\nroom.voice.onPeers(renderVoice);\nroom.voice.onState(() => renderVoice());\nrenderVoice();\n```\n\n`room.voice.mode` is `none`, `room`, `team`, or `proximity`. In `room` mode, every participant in voice can hear every other participant. In `team` mode, players hear only their team. In `proximity` mode, the room server controls the gain between each pair. Spectators cannot publish audio, and `join()` rejects for them.\n\n`room.voice.state` is `off`, `joining`, `on`, or `reconnecting`. `room.voice.muted` and `room.voice.speaking` describe the local microphone. `room.voice.peers` contains the other voice participants as `{ id, muted, speaking, volume, gain }`. `volume` is the local setting and `gain` is the proximity value from the room server. Use `room.voice.setVolume(playerId, volume)` with a value from 0 to 1 to change only local playback.\n\n`room.voice.onPeers(listener)` runs when participants, mute state, speaking state, volume, or proximity gain changes. `room.voice.onState(listener)` reports connection state changes. Both return a function that removes the listener.\n\nCall `room.voice.leave()` to stop the microphone and leave voice without leaving the room. `room.leave()` and the end of the room stop voice automatically.\n\n`join()` rejects with an `Error` carrying one of these stable codes: `voice_disabled`, `permission_denied`, `unsupported`, `spectator`, `offline`, or `voice_error`. Voice can reconnect after a temporary room or media connection failure. The state becomes `reconnecting` while the kit retries.\n\n## Server\n\nPut `server.js` next to `caisual.json` and publish it with the game. See [publish.md](./publish.md#multiplayer-server) for the file rules, validation, and publishing flow.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\n\nexport default defineGame({\n tickRate: 20, // 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n});\n```\n\nAll callbacks are optional. A player is `{ id, name, guest, role, team, connected }`. The room object provides:\n\n```js\nroom.id;\nroom.mode;\nroom.status;\nroom.tick;\nroom.state;\nroom.players;\nroom.host;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.end(result);\n\nawait room.save('round', value);\nawait room.load('round');\nroom.schedule(milliseconds, 'methodName', payload);\nroom.board.submit(playerOrId, 'main', score, { daily: true });\n\nroom.daily.day;\nroom.daily.seed;\nroom.time.now();\n\nroom.voice.mode;\nroom.voice.setProximity(playerA, playerB, 0.5);\n```\n\nSet `room.state` in `onCreate`, then mutate it only in server callbacks. It must remain plain JSON and may be at most 256 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and ends the room. Room saves use keys with the same format as player save keys and values up to 128 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes. Scores submitted through `room.board` are verified.\n\nFor a room using `\"voice\": \"proximity\"`, update the symmetric gain between players from server-owned positions. The value is limited to the range from 0 to 1. Calls in other voice modes have no effect.\n\n```js\nexport default defineGame({\n tickRate: 20,\n onTick(room) {\n for (const a of room.players) {\n for (const b of room.players) {\n if (a.id >= b.id) continue;\n const pa = room.state.positions[a.id];\n const pb = room.state.positions[b.id];\n const distance = Math.hypot(pa.x - pb.x, pa.y - pb.y);\n room.voice.setProximity(a, b, Math.max(0, 1 - distance / 20));\n }\n }\n },\n});\n```\n\n### Sleeping and cost\n\nPrefer `tickRate: 0` for turn based and party games. A room with a tick loop sleeps automatically after 30 seconds without player input or state changes and wakes on the next game message or player joining. Automatic ping and resync messages do not count as player input. A match with no player input for 10 minutes ends with `{ error: 'idle' }`. Timers set with `schedule` and the countdown keep working while the room sleeps.\n\n## Limits\n\n- 120 requests per minute per player. Beyond that the kit rejects with `rate_limited`; wait and retry.\n- Saves: 32 keys per player per game, 256 KB per value.\n- Scores: safe integers from 0 upward.\n- Room state: 256 KB of plain JSON.\n- Room messages: 16 KB each and 20 messages per second per connection.\n- Voice supports audio only and one voice channel per room.\n- Voice control messages: 64 KB each and 30 operations per 10 seconds per connection. Voice traffic is not counted against the room's message limits.\n- Room save values: 128 KB each.\n\n## Development\n\nRun `npx @caisual/cli dev` from the game folder, then open the printed portal URL. The preview supplies the normal handshake, so `c.connected` is `true` and the game receives a local guest identity. Saves, leaderboards, daily data, invitations, and rooms work locally. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. If it has no `server.js`, room creation rejects with `no_server` and the single-player APIs still work.\n\nOpening `client/index.html` from a plain static server still uses standalone mode: `c.connected` is `false`, saves use local storage, `submit` returns `accepted: false`, leaderboards are empty, the daily seed is local, and room creation and joining reject with `offline`. The rest of the game logic does not need a different code path.\n\nAfter publishing with `npx @caisual/cli publish`, open the game from its caisual.com page: `c.connected` becomes `true` and every call goes to the portal.\n\n## Manifest\n\nNo manifest field is required for identity, saves, leaderboards, or the daily challenge. For rooms, set `players` to the supported range and use `lobby`, `roles`, `teams`, and `modes` to describe the setup enforced before play starts. Set `voice` to `room`, `team`, or `proximity` to enable the corresponding voice mode, or omit it for `none`. A single-player game can keep `players` at `{ \"min\": 1, \"max\": 1 }`, `lobby` at `false`, and omit `server.js`. See [publish.md](./publish.md#caisualjson) for every field and the publishing steps.\n";
|
|
532
|
+
var kit_default = "# Caisual game kit\n\nThe kit gives a published game a stable player identity, cloud saves, leaderboards, a daily challenge seed, and multiplayer rooms with server-owned state.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page: the game keeps its own rendering, input, and UI.\n\n## Load the kit\n\nEvery published game can import the kit from its own origin, without a bundler and without an npm install:\n\n```html\n<script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n\n const c = await caisual.connect();\n console.log(c.player.name);\n</script>\n```\n\nGames built with a bundler can install the same module from npm:\n\n```sh\nnpm install @caisual/kit\n```\n\n```js\nimport { caisual } from '@caisual/kit';\n```\n\nBoth forms expose the same API. The module also sets `globalThis.caisual` for classic scripts that load it first.\n\nThe path `/__caisual/` is reserved on every game origin. Do not put game files under it.\n\n## Connect\n\n```js\nconst c = await caisual.connect();\n```\n\n`connect()` completes when the game is running inside caisual.com and has received its player identity, or after a short timeout when it is not. Calling it again returns the same promise.\n\n- `c.connected` is `true` inside caisual.com and `false` when the game runs on its own, for example from a local folder during development or when its files are copied elsewhere.\n- `c.player` is `{ id, name, guest }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or `\"Guest\"`. `guest` is `true` for players without an account. When a guest later signs in, saves and scores stay attached to the same `id`.\n- When not connected, `c.player` is `{ id: \"local\", name: \"Guest\", guest: true }`.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\n## Daily challenge\n\n```js\nc.daily.day; // \"2026-09-04\", the current UTC day\nc.daily.seed; // unsigned 32-bit integer, identical for every player on that day\nconst r = c.daily.random(); // number in [0, 1), deterministic from the seed\n```\n\n`c.daily.random()` is a deterministic generator initialized from `c.daily.seed`. Every `connect()` starts the sequence from the beginning, so two players who call it the same number of times get the same values. Use it to build the level of the day.\n\n`c.time.now()` returns milliseconds aligned with the portal clock. Prefer it to `Date.now()` for anything that must agree with the current day.\n\nWhen not connected, `day` comes from the local clock and `seed` from the local hostname, so a game copied elsewhere still runs.\n\n## Saves\n\nEach player has up to 32 saves per game. A save is any JSON value up to 256 KB when serialized.\n\n```js\nawait c.save.set('slot1', { level: 3, coins: 120 }); // -> { key, bytes, updatedAt }\nconst data = await c.save.get('slot1'); // -> the value, or null\nawait c.save.remove('slot1');\nconst saves = await c.save.list(); // -> [{ key, bytes, updatedAt }]\n```\n\n- Keys use 1 to 32 characters: lowercase letters, digits, `_` or `-`, starting with a letter or digit.\n- `updatedAt` is a millisecond timestamp.\n- Saves are per player and per game. Another game cannot read them.\n- When not connected, saves go to the browser's local storage on the game origin.\n\nErrors reject the promise with an `Error` whose `code` is one of `invalid_request`, `not_found`, `save_limit`, `payload_too_large`, `rate_limited`, `invalid_ticket`, `internal_error`, or `offline`.\n\n## Leaderboards\n\nA leaderboard is identified by a board id chosen by the game. Scores are non-negative integers and higher is better. Each player keeps one entry per board, and one per board per day for daily boards: the best score is kept.\n\n```js\nconst result = await c.board.submit('main', 1234);\n// -> { accepted: true, best: 1234, rank: 7, day: null }\n\nconst daily = await c.board.submit('main', 1234, { daily: true });\n// -> { accepted: true, best: 1234, rank: 7, day: \"2026-09-04\" }\n\nconst top = await c.board.top('main', { daily: true, limit: 10 });\n// -> { day: \"2026-09-04\", entries: [{ rank, name, score, guest, me }], me: { rank, score } | null }\n```\n\n- Board ids use the same format as save keys.\n- `submit` never rejects because of connectivity. When the game is not connected it resolves `{ accepted: false, reason: \"offline\" }`.\n- `best` is the score kept for this player after the submission, which can be higher than the submitted one.\n- `rank` counts players with a strictly higher score. Ties are ordered by who reached the score first.\n- Accounts and guests are ranked separately. `top()` returns account players by default; pass `guests: true` to list guests instead. `me` always refers to the current player within their own category, even beyond `limit`.\n- `limit` is 1 to 100 and defaults to 10.\n- Scores submitted from the browser are recorded as unverified. A room server can submit verified scores.\n\n## Device\n\n`c.device` contains the browser and device report collected while `connect()` runs:\n\n```ts\ninterface DeviceReport {\n webgl2: boolean;\n webgpu: boolean;\n wasm: boolean;\n threads: boolean;\n isolated: boolean;\n gpu: 'hardware' | 'software' | 'none';\n memoryMb: number | null;\n cores: number | null;\n mobile: boolean;\n tier: 'low' | 'mid' | 'high';\n}\n```\n\nUse capability fields to choose a renderer, then use `tier` to reduce pixel ratio and quality on smaller devices:\n\n```js\nconst renderer = c.device.webgpu\n ? createWebGpuRenderer()\n : createWebGl2Renderer();\n\nconst pixelRatio = c.device.tier === 'high' ? devicePixelRatio : 1;\nconst quality = c.device.tier === 'low' ? 'low' : 'high';\nrenderer.configure({ pixelRatio, quality });\n```\n\nThe probe takes at most 1.5 seconds. `memoryMb` and `cores` are `null` when the browser does not expose them. The report stays in the browser and is not saved or sent to Caisual.\n\n## Rooms\n\nA room brings players into the same running game. Creating and joining require a published `server.js`; single-player games can ignore `c.room`.\n\n```js\nconst c = await caisual.connect();\n\nc.room.invited; // invitation code from the game page, or null\n\nconst room = await c.room.create({ mode: null });\n// Or join the invitation that opened the game:\nconst invitedRoom = await c.room.join();\n// Or enter a code supplied by the player:\nconst codedRoom = await c.room.join('ABC234');\n\nroom.code;\nroom.seed; // unsigned 32-bit integer fixed for this room\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nPass a mode id from the manifest to `create({ mode })`, or `null` when the game has no modes. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. Show the URL returned by `invite()` in a share button or copy action.\n\n### Crew\n\nThe kit automatically reports the player's current room to the Caisual portal, so the player's friends can join with one click. The game does not need to send or handle anything for this. There is no `c.crew` API in this version.\n\n### Matchmaking\n\nUse `c.room.match()` to find players who requested the same mode and key. The key must contain exactly the fields declared by that mode's `matchmaking.key` in `caisual.json`.\n\n```js\nconst room = await c.room.match({\n mode: 'daily',\n key: { day: c.daily.day, stage: 3 },\n onWaiting({ players, min, max }) {\n showQueue(`${players}/${max} players, ${min} required`);\n },\n});\n```\n\nA room opens as soon as the queue reaches `players.max`. When `matchmaking.timeoutMs` expires, it also opens if at least `players.min` players are waiting. Otherwise the promise rejects with `no_match`, and the game should offer the player another option. A new search first tries to fill a matching room that is already open and can still accept players.\n\nPass an `AbortSignal` as `signal` to let the player cancel a search. Cancellation rejects with `cancelled`. For lobbies with players who may not know each other, have the game start automatically after everyone is ready:\n\n```js\nroom.onPlayers((players) => {\n if (players.every((player) => player.ready) && room.you === room.host) room.start();\n});\n```\n\nRoom status is one of:\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: the lobby has accepted `start()` and play begins at the announced server time.\n- `playing`: the game server is running the match.\n- `ended`: the match or connection has ended. `room.result` contains the result last reported by the room. A definitive connection closure uses `{ closed: 4003 }`, `{ closed: 4004 }`, `{ closed: 4005 }`, or `{ closed: 4006 }`.\n\nThe current lobby data is available directly:\n\n```js\nroom.players; // [{ id, name, guest, role, team, ready, connected }]\nroom.you; // this player's id\nroom.host; // the current host's id, or null\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n\nif (room.you === room.host) room.start();\n```\n\n`ready`, role, team, and `start()` are lobby actions. Starting requires the host, every connected player to be ready, and the player, role, and team minimums from the manifest. Calling `start()` begins a three-second countdown. A role or team change clears that player's ready state. The built-in `spectator` role receives state but cannot send game input.\n\nThe server owns room state. Read it and react to updates, but do not assign to it or mutate nested values from the browser:\n\n```js\ndraw(room.state);\n\nconst stopState = room.onState((state, tick, serverTime) => {\n draw(state);\n});\n\nconst stopPlayers = room.onPlayers((players) => updateLobby(players));\nconst stopStatus = room.onStatus((status, result, at) => showStatus(status, result, at));\n\nstopState();\nstopPlayers();\nstopStatus();\n```\n\n`room.tick` identifies the latest state. The kit applies structural updates in order and requests a full state automatically if an update does not match the current tick. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\nSend JSON input to `onMessage` in the server definition, and receive JSON sent or broadcast by the server:\n\n```js\nroom.send({ type: 'fire', target: 3 });\n\nconst stopMessages = room.onMessage((message) => {\n showEvent(message);\n});\n```\n\nThe kit numbers outgoing inputs in increasing order. It automatically reconnects temporary failures with delays of 1, 2, 4, then 8 seconds, for at most the room's 60-second grace period. Each attempt gets a fresh room token. A successful reconnect replaces local state with a full server state. Inputs sent while reconnecting throw an error with `code: \"offline\"`.\n\nCall `room.leave()` for an intentional departure. The kit does not reconnect after leaving, being kicked, the room ending, the published version closing, or the same player opening the room in another tab.\n\nRoom creation, joining, and matchmaking reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `no_server`, `no_match`, `cancelled`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, `create`, `join`, and `match` reject with `offline`.\n\nEvery `onState`, `onPlayers`, `onStatus`, and `onMessage` call returns a function that removes that listener.\n\n## Voice\n\nEvery room has a `room.voice` object. Voice is disabled by default and is enabled with the manifest's `voice` field. A game should offer an explicit control because `join()` must be called from a click or another user gesture so the browser can start audio and, when publishing, request microphone permission.\n\n```js\nconst micButton = document.querySelector('#mic');\nconst voiceList = document.querySelector('#voice-list');\n\nfunction renderVoice(peers = room.voice.peers) {\n voiceList.replaceChildren(...peers.map((peer) => {\n const item = document.createElement('li');\n const player = room.players.find((entry) => entry.id === peer.id);\n item.textContent = `${player?.name ?? peer.id}: ${\n peer.speaking ? 'speaking' : peer.muted ? 'muted' : 'quiet'\n }`;\n return item;\n }));\n micButton.textContent = room.voice.state === 'off'\n ? 'Join voice'\n : !room.voice.mic ? 'Listening' : room.voice.muted ? 'Unmute' : 'Mute';\n}\n\nmicButton.addEventListener('click', async () => {\n if (room.voice.state === 'off') await room.voice.join();\n else if (room.voice.mic) room.voice.mute(!room.voice.muted);\n renderVoice();\n});\n\nroom.voice.onPeers(renderVoice);\nroom.voice.onState(() => renderVoice());\nrenderVoice();\n```\n\n`room.voice.mode` is `none`, `room`, `team`, or `proximity`. In `room` mode, every participant in voice can hear every other participant. In `team` mode, players hear only their team. In `proximity` mode, the room server controls the gain between participants. Call `room.voice.join({ mic: false })` to listen without opening or publishing a microphone. Spectators join in listening mode when they call `join()` without options. A spectator that calls `join({ mic: true })` receives the `spectator` error.\n\n`room.voice.state` is `off`, `joining`, `on`, or `reconnecting`. `room.voice.mic` is `true` while the local player is publishing. `room.voice.muted` and `room.voice.speaking` describe the local microphone. `room.voice.peers` contains the other voice participants as `{ id, mic, muted, speaking, volume, gain }`. A listening participant has `mic: false`, `muted: true`, and `speaking: false`. `volume` is the local setting and `gain` is the value from the room server. Use `room.voice.setVolume(playerId, volume)` with a value from 0 to 1 to change only local playback.\n\n`room.voice.onPeers(listener)` runs when participants, microphone state, mute state, speaking state, volume, or gain changes. `room.voice.onState(listener)` reports connection state changes. Both return a function that removes the listener.\n\nCall `room.voice.leave()` to stop publishing or listening without leaving the room. `room.voice.mute()` requires an active published microphone and otherwise throws `not_publishing`. `room.leave()` and the end of the room stop voice automatically.\n\n`join()` rejects with an `Error` carrying one of these stable codes: `voice_disabled`, `permission_denied`, `unsupported`, `spectator`, `offline`, or `voice_error`. Voice can reconnect after a temporary room or media connection failure. The state becomes `reconnecting` while the kit retries.\n\n## Server\n\nPut `server.js` next to `caisual.json` and publish it with the game. See [publish.md](./publish.md#multiplayer-server) for the file rules, validation, and publishing flow.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\n\nexport default defineGame({\n tickRate: 20, // 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n});\n```\n\nAll callbacks are optional. A player is `{ id, name, guest, role, team, connected }`. The room object provides:\n\n```js\nroom.id;\nroom.seed;\nroom.mode;\nroom.status;\nroom.tick;\nroom.tickRate;\nroom.result;\nroom.state;\nroom.players;\nroom.host;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.setRole(playerOrId, role);\nroom.setTeam(playerOrId, team);\nroom.end(result);\n\nawait room.save('round', value);\nawait room.load('round');\nawait room.shared.get('ship_abc');\nawait room.shared.set('ship_abc', value);\nawait room.shared.delete('ship_abc');\nawait room.shared.list('ship_');\nawait room.shared.increment('visits', 1);\nroom.schedule(milliseconds, 'methodName', payload);\nroom.board.submit(playerOrId, 'main', score, { daily: true });\n\nroom.daily.day;\nroom.daily.seed;\nroom.time.now();\n\nroom.voice.mode;\nroom.voice.setGain(listener, speaker, 0.25);\nroom.voice.setProximity(playerA, playerB, 0.5);\n```\n\nSet `room.state` in `onCreate`, then mutate it only in server callbacks. It must remain plain JSON and may be at most 256 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and ends the room. Room saves use keys with the same format as player save keys and values up to 128 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes. Scores submitted through `room.board` are verified.\n\nThe browser can change its role or team only while the room is in `lobby`. During a match, the server decides when a player changes role or team with `room.setRole` and `room.setTeam`. Both methods accept a player object or id and immediately update `room.players` for every client.\n\n```js\nonMessage(room, player, message) {\n if (message?.swap === 'captain') {\n room.setRole(player, 'captain');\n }\n},\n```\n\n`room.daily.seed` is shared by every room for the game on the current UTC day. `room.seed` is fixed for one room and is identical on the server and clients, so rooms created on the same day can generate different maps.\n\n### Shared game store\n\n`room.shared` is a server-only JSON key/value store shared by every room of the same game. It is useful when one room must leave data for another room, while `room.save` remains private to one room.\n\nThe following server leaves a ship when a room ends, then loads every previously left ship when another room is created. The room id suffix is used because shared-store keys follow the save-key format.\n\n```js\nexport default defineGame({\n tickRate: 0,\n\n async onCreate(room) {\n const keys = await room.shared.list('ship_');\n room.state = {\n ships: await Promise.all(keys.map((key) => room.shared.get(key))),\n };\n },\n\n async onEnd(room) {\n const roomSuffix = room.id.split('.')[1];\n await room.shared.set('ship_' + roomSuffix, {\n position: room.state.position,\n cargo: room.state.cargo,\n });\n },\n});\n```\n\nThe five methods are asynchronous:\n\n```js\nconst value = await room.shared.get(key); // JSON value, or null\nawait room.shared.set(key, value); // last writer wins\nawait room.shared.delete(key);\nconst keys = await room.shared.list(prefix); // sorted, up to 1024\nconst total = await room.shared.increment(key, 1); // atomic, defaults to 1\n```\n\nKeys contain 1 to 32 lowercase letters, numbers, underscores, or hyphens. Values may be up to 64 KB when serialized, and each game may keep up to 1024 keys. Each room may perform up to 120 shared-store operations per minute. `increment` treats a missing key as zero and rejects unless the existing value, amount, and result are safe integers.\n\nUse the store in `onCreate`, `onStart`, `onEnd`, `onMessage`, or a `schedule` handler. Do not call it on every tick: each call waits for a remote operation, and the CPU budget uses elapsed wall-clock time. Browser clients cannot access this store. Send only the data they need with `room.broadcast` or `room.send`.\n\nFailures reject with an `Error` carrying `store_invalid_key`, `store_too_large`, `store_full`, `store_not_integer`, `store_unavailable`, or `store_rate_limited` in `code`.\n\n`room.voice.setGain(listener, speaker, gain)` controls how much one listener hears one speaker. It is directional, limited to the range from 0 to 1, and rounded to two decimal places. For example, the following setup lets the captain hear everyone while each crew member hears only the captain:\n\n```js\nconst captain = room.players.find((player) => player.role === 'captain');\nconst crew = room.players.filter((player) => player.id !== captain.id);\n\nfor (const speaker of room.players) {\n room.voice.setGain(captain, speaker, 1);\n}\nfor (const listener of crew) {\n for (const speaker of room.players) {\n room.voice.setGain(listener, speaker, speaker.id === captain.id ? 1 : 0);\n }\n}\n```\n\n`room.voice.setProximity(a, b, gain)` is the symmetric shortcut for setting both directions. Both methods work in `room`, `team`, and `proximity` modes, and do nothing in `none`. In `team` mode, gains remain inside the team and cannot make a player hear another team.\n\nFor position-based audio, update the symmetric gain between players from server-owned positions:\n\n```js\nexport default defineGame({\n tickRate: 20,\n onTick(room) {\n for (const a of room.players) {\n for (const b of room.players) {\n if (a.id >= b.id) continue;\n const pa = room.state.positions[a.id];\n const pb = room.state.positions[b.id];\n const distance = Math.hypot(pa.x - pb.x, pa.y - pb.y);\n room.voice.setProximity(a, b, Math.max(0, 1 - distance / 20));\n }\n }\n },\n});\n```\n\n### Sleeping and cost\n\nPrefer `tickRate: 0` for turn based and party games. A room with a tick loop sleeps automatically after 30 seconds without player input or state changes and wakes on the next game message or player joining. Automatic ping and resync messages do not count as player input. A match with no player input for 10 minutes ends with `{ error: 'idle' }`. Timers set with `schedule` and the countdown keep working while the room sleeps.\n\n### CPU budget\n\nEvery `onTick` and `onMessage` call is measured. Twenty consecutive calls above 100 ms end the room with `{ error: 'cpu_budget' }`. If the average over 50 ticks is above 20 ms, the effective `tickRate` is halved, down to a minimum of 5, and clients receive an `error` message with code `tick_rate_reduced`.\n\n`room.tickRate` starts at the definition's `tickRate` and always reports the current effective frequency. `deltaSeconds` follows that frequency, so a fixed-step simulation must accumulate `deltaSeconds` instead of counting ticks. Measurement uses elapsed wall-clock time, so a slow `await` inside a callback also counts. `room.result` is `null` until the room ends, then contains the final game or automatic error result and is available inside `onEnd`.\n\n### Persistent rooms\n\nSet `\"persistent\": true` in `caisual.json` for a room that must survive long breaks. It does not use the normal inactivity ending rule and does not end when every player disconnects. Players remain members until they call `room.leave()` or the server removes them with `room.kick()`. They can use the same room code to return while the game is already playing. The code remains valid while the room lives, and absent members remain in `room.players` with `connected: false`.\n\nA persistent room ends when the server calls `room.end()`, after 30 days without player input, entry, or a state change with `{ error: 'expired' }`, or after five minutes without any members. Consider storing `room.code` with `c.save.set()` and offering a Resume action. A persistent room incurs cost only while it is awake.\n\n## Limits\n\n- 120 requests per minute per player. Beyond that the kit rejects with `rate_limited`; wait and retry.\n- Saves: 32 keys per player per game, 256 KB per value.\n- Scores: safe integers from 0 upward.\n- Room state: 256 KB of plain JSON.\n- Room messages: 16 KB each and 20 messages per second per connection.\n- Voice supports audio only and one voice channel per room.\n- Voice control messages: 64 KB each and 30 operations per 10 seconds per connection. Voice traffic is not counted against the room's message limits.\n- Room save values: 128 KB each.\n- Shared game store: 64 KB per JSON value, 1024 keys per game, and 120 operations per minute per room.\n\n## Development\n\nRun `npx @caisual/cli dev` from the game folder, then open the printed portal URL. The preview supplies the normal handshake, so `c.connected` is `true` and the game receives a local guest identity. Saves, leaderboards, daily data, invitations, and rooms work locally. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nWhen building the client with a bundler, remember that `client/` is served as-is. Configure Vite, esbuild, or another bundler to write into that folder, for example `vite build --outDir client`, and use relative paths such as `base: './'`.\n\nKeep loading the kit from the `<script type=\"module\">` shown at the beginning of this guide, using `/__caisual/kit/v1.js`.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. If it has no `server.js`, room creation rejects with `no_server` and the single-player APIs still work.\n\nOpening `client/index.html` from a plain static server still uses standalone mode: `c.connected` is `false`, saves use local storage, `submit` returns `accepted: false`, leaderboards are empty, the daily seed is local, and room creation and joining reject with `offline`. The rest of the game logic does not need a different code path.\n\nAfter publishing with `npx @caisual/cli publish`, open the game from its caisual.com page: `c.connected` becomes `true` and every call goes to the portal.\n\n## Manifest\n\nNo manifest field is required for identity, saves, leaderboards, or the daily challenge. For rooms, set `players` to the supported range and use `lobby`, `persistent`, `roles`, `teams`, and `modes` to describe the setup and lifetime. Set `voice` to `room`, `team`, or `proximity` to enable the corresponding voice mode, or omit it for `none`. A single-player game can keep `players` at `{ \"min\": 1, \"max\": 1 }`, `lobby` at `false`, and omit `server.js`. See [publish.md](./publish.md#caisualjson) for every field and the publishing steps.\n";
|
|
533
|
+
|
|
534
|
+
// src/bundle.ts
|
|
535
|
+
import { promises as fs } from "node:fs";
|
|
536
|
+
import { builtinModules } from "node:module";
|
|
537
|
+
import { isAbsolute, join, relative } from "node:path";
|
|
538
|
+
import { build } from "esbuild";
|
|
539
|
+
var CliError = class extends Error {
|
|
540
|
+
exitCode;
|
|
541
|
+
constructor(exitCode, message) {
|
|
542
|
+
super(message);
|
|
543
|
+
this.name = "CliError";
|
|
544
|
+
this.exitCode = exitCode;
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
function formatBuildError(root, error) {
|
|
548
|
+
const location = error.location;
|
|
549
|
+
if (location === null) return `- server.js:?: ${error.text}`;
|
|
550
|
+
const rawFile = location.file === "" ? "server.js" : location.file;
|
|
551
|
+
const file = (isAbsolute(rawFile) ? relative(root, rawFile) : rawFile).replaceAll("\\", "/");
|
|
552
|
+
return `- ${file}:${location.line}: ${error.text}`;
|
|
553
|
+
}
|
|
554
|
+
function isSandboxImport(error) {
|
|
555
|
+
const match = /^Could not resolve "([^"]+)"/.exec(error.text);
|
|
556
|
+
if (match === null) return false;
|
|
557
|
+
const specifier = match[1];
|
|
558
|
+
const bareSpecifier = specifier.startsWith("node:") ? specifier.slice("node:".length) : specifier;
|
|
559
|
+
const packageName = bareSpecifier.split("/")[0];
|
|
560
|
+
return specifier.startsWith("node:") || specifier.startsWith("cloudflare:") || builtinModules.includes(bareSpecifier) || builtinModules.includes(packageName);
|
|
561
|
+
}
|
|
562
|
+
function buildErrors(error) {
|
|
563
|
+
if (typeof error !== "object" || error === null || !("errors" in error)) return null;
|
|
564
|
+
const errors = error.errors;
|
|
565
|
+
return Array.isArray(errors) ? errors : null;
|
|
566
|
+
}
|
|
567
|
+
function normalizeDefaultExport(source) {
|
|
568
|
+
const exportBlock = /\nexport \{\n([\s\S]*?)\n\};\s*$/.exec(source);
|
|
569
|
+
if (exportBlock === null) return source;
|
|
570
|
+
const lines = exportBlock[1].split("\n");
|
|
571
|
+
let defaultName = null;
|
|
572
|
+
const remaining = lines.filter((line) => {
|
|
573
|
+
const match = /^\s*([$A-Z_a-z][$\w]*)\s+as\s+default,?\s*$/.exec(line);
|
|
574
|
+
if (match === null) return true;
|
|
575
|
+
defaultName = match[1];
|
|
576
|
+
return false;
|
|
577
|
+
});
|
|
578
|
+
if (defaultName === null) return source;
|
|
579
|
+
const prefix = source.slice(0, exportBlock.index);
|
|
580
|
+
const namedExports = remaining.length === 0 ? "" : `
|
|
581
|
+
export {
|
|
582
|
+
${remaining.join("\n")}
|
|
583
|
+
};`;
|
|
584
|
+
return `${prefix}${namedExports}
|
|
585
|
+
export default ${defaultName};
|
|
586
|
+
`;
|
|
587
|
+
}
|
|
588
|
+
async function bundleServer(root) {
|
|
589
|
+
const serverPath = join(root, "server.js");
|
|
590
|
+
let source;
|
|
591
|
+
try {
|
|
592
|
+
source = await fs.readFile(serverPath, "utf8");
|
|
593
|
+
} catch {
|
|
594
|
+
throw new CliError(2, "server.js: file not readable.");
|
|
595
|
+
}
|
|
596
|
+
const directValidation = validaServerJs(source);
|
|
597
|
+
if (directValidation.ok) return { source, bundled: false };
|
|
598
|
+
let output;
|
|
599
|
+
try {
|
|
600
|
+
const result = await build({
|
|
601
|
+
entryPoints: [serverPath],
|
|
602
|
+
bundle: true,
|
|
603
|
+
format: "esm",
|
|
604
|
+
platform: "neutral",
|
|
605
|
+
target: "es2022",
|
|
606
|
+
external: ["@caisual/kit/server"],
|
|
607
|
+
mainFields: ["module", "main"],
|
|
608
|
+
conditions: ["workerd", "worker", "import", "default"],
|
|
609
|
+
minify: false,
|
|
610
|
+
treeShaking: true,
|
|
611
|
+
sourcemap: false,
|
|
612
|
+
legalComments: "none",
|
|
613
|
+
logLevel: "silent",
|
|
614
|
+
absWorkingDir: root,
|
|
615
|
+
write: false
|
|
616
|
+
});
|
|
617
|
+
const file = result.outputFiles[0];
|
|
618
|
+
if (file === void 0) throw new Error("esbuild did not produce server.js.");
|
|
619
|
+
output = normalizeDefaultExport(file.text);
|
|
620
|
+
} catch (error) {
|
|
621
|
+
const errors = buildErrors(error);
|
|
622
|
+
if (errors === null || errors.length === 0) {
|
|
623
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
624
|
+
throw new CliError(2, `server.js could not be bundled:
|
|
625
|
+
- server.js:?: ${detail}`);
|
|
626
|
+
}
|
|
627
|
+
const lines = errors.map((buildError) => formatBuildError(root, buildError));
|
|
628
|
+
if (errors.some(isSandboxImport)) {
|
|
629
|
+
lines.push("The server runs in a sandbox without Node.js APIs or network access: only pure JavaScript packages can be bundled.");
|
|
630
|
+
}
|
|
631
|
+
throw new CliError(2, `server.js could not be bundled:
|
|
632
|
+
${lines.join("\n")}`);
|
|
633
|
+
}
|
|
634
|
+
const bundledValidation = validaServerJs(output);
|
|
635
|
+
if (!bundledValidation.ok) {
|
|
636
|
+
throw new CliError(
|
|
637
|
+
2,
|
|
638
|
+
`The bundled server.js violates the server rules:
|
|
639
|
+
${bundledValidation.errori.map((error) => `- ${error}`).join("\n")}`
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
return { source: output, bundled: true };
|
|
643
|
+
}
|
|
488
644
|
|
|
489
645
|
// src/dev.ts
|
|
490
646
|
import { createHash as createHash2, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
491
|
-
import { promises as
|
|
647
|
+
import { promises as fs2 } from "node:fs";
|
|
492
648
|
import { createServer } from "node:http";
|
|
493
|
-
import { extname, join, relative, resolve, sep } from "node:path";
|
|
649
|
+
import { extname, join as join2, relative as relative2, resolve, sep } from "node:path";
|
|
494
650
|
|
|
495
651
|
// ../kit/dist/node.js
|
|
496
652
|
import { randomUUID } from "node:crypto";
|
|
@@ -652,9 +808,8 @@ var COSTANTI_SHA256 = [
|
|
|
652
808
|
function ruotaDestra(value, bits) {
|
|
653
809
|
return value >>> bits | value << 32 - bits;
|
|
654
810
|
}
|
|
655
|
-
function
|
|
656
|
-
const
|
|
657
|
-
const bytes = Array.from(testo, (carattere) => carattere.charCodeAt(0));
|
|
811
|
+
function hashSeed(testo) {
|
|
812
|
+
const bytes = Array.from(new TextEncoder().encode(testo));
|
|
658
813
|
const bitLength = bytes.length * 8;
|
|
659
814
|
bytes.push(128);
|
|
660
815
|
while (bytes.length % 64 !== 56) bytes.push(0);
|
|
@@ -717,18 +872,36 @@ function seedGiornata(slug, day) {
|
|
|
717
872
|
}
|
|
718
873
|
return h0 >>> 0;
|
|
719
874
|
}
|
|
875
|
+
function seedGiornata(slug, day) {
|
|
876
|
+
return hashSeed(`caisual:${slug}:${day}`);
|
|
877
|
+
}
|
|
878
|
+
function seedStanza(roomId) {
|
|
879
|
+
return hashSeed(`caisual:room:${roomId}`);
|
|
880
|
+
}
|
|
720
881
|
var CHIAVE_NUCLEO = "nucleo";
|
|
721
882
|
var PREFISSO_SAVE = "save:";
|
|
722
883
|
var LIMITE_FRAME = 16 * 1024;
|
|
723
884
|
var LIMITE_STATO = 256 * 1024;
|
|
724
885
|
var LIMITE_SAVE = 128 * 1024;
|
|
886
|
+
var LIMITE_DEPOSITO = 64 * 1024;
|
|
887
|
+
var LIMITE_OPERAZIONI_DEPOSITO = 120;
|
|
725
888
|
var GRAZIA_MS = 6e4;
|
|
726
889
|
var STANZA_VUOTA_MS = 5 * 6e4;
|
|
727
890
|
var COUNTDOWN_MS = 3e3;
|
|
728
891
|
var RIPOSO_TICK_MS = 3e4;
|
|
729
892
|
var INATTIVITA_MS = 10 * 6e4;
|
|
893
|
+
var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
|
|
730
894
|
var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
895
|
+
var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
|
|
731
896
|
var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
|
|
897
|
+
var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
|
|
898
|
+
"store_invalid_key",
|
|
899
|
+
"store_too_large",
|
|
900
|
+
"store_full",
|
|
901
|
+
"store_not_integer",
|
|
902
|
+
"store_unavailable",
|
|
903
|
+
"store_rate_limited"
|
|
904
|
+
]);
|
|
732
905
|
function record(value) {
|
|
733
906
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
734
907
|
}
|
|
@@ -751,6 +924,9 @@ function copiaGiocatore(player) {
|
|
|
751
924
|
function copiaJson(value) {
|
|
752
925
|
return JSON.parse(JSON.stringify(value));
|
|
753
926
|
}
|
|
927
|
+
function erroreConCodice(code, message) {
|
|
928
|
+
return Object.assign(new Error(message), { code });
|
|
929
|
+
}
|
|
754
930
|
function codiceIngresso(code) {
|
|
755
931
|
if (code === "room_not_found") return 4001;
|
|
756
932
|
if (code === "room_full") return 4e3;
|
|
@@ -763,6 +939,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
763
939
|
this.adattatore = adattatore;
|
|
764
940
|
this.dati = null;
|
|
765
941
|
this.frequenza = /* @__PURE__ */ new Map();
|
|
942
|
+
this.frequenzaDeposito = [];
|
|
766
943
|
this.kickRichiesti = /* @__PURE__ */ new Set();
|
|
767
944
|
this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
|
|
768
945
|
this.fineRichiesta = null;
|
|
@@ -782,6 +959,9 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
782
959
|
get id() {
|
|
783
960
|
return nucleo.richiediDati().id;
|
|
784
961
|
},
|
|
962
|
+
get seed() {
|
|
963
|
+
return seedStanza(nucleo.richiediDati().id);
|
|
964
|
+
},
|
|
785
965
|
get mode() {
|
|
786
966
|
return nucleo.richiediDati().mode;
|
|
787
967
|
},
|
|
@@ -791,6 +971,12 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
791
971
|
get tick() {
|
|
792
972
|
return nucleo.richiediDati().tick;
|
|
793
973
|
},
|
|
974
|
+
get tickRate() {
|
|
975
|
+
return nucleo.richiediDati().tickRate;
|
|
976
|
+
},
|
|
977
|
+
get result() {
|
|
978
|
+
return nucleo.richiediDati().result;
|
|
979
|
+
},
|
|
794
980
|
get state() {
|
|
795
981
|
return nucleo.richiediDati().state;
|
|
796
982
|
},
|
|
@@ -814,6 +1000,12 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
814
1000
|
kick(player) {
|
|
815
1001
|
nucleo.kickRichiesti.add(idGiocatore(player));
|
|
816
1002
|
},
|
|
1003
|
+
setRole(player, role) {
|
|
1004
|
+
nucleo.impostaRuoloDalServer(idGiocatore(player), role);
|
|
1005
|
+
},
|
|
1006
|
+
setTeam(player, team) {
|
|
1007
|
+
nucleo.impostaSquadraDalServer(idGiocatore(player), team);
|
|
1008
|
+
},
|
|
817
1009
|
end(result) {
|
|
818
1010
|
nucleo.richiediFine(result);
|
|
819
1011
|
},
|
|
@@ -823,6 +1015,23 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
823
1015
|
load(key) {
|
|
824
1016
|
return nucleo.caricaSave(key);
|
|
825
1017
|
},
|
|
1018
|
+
shared: {
|
|
1019
|
+
get(key) {
|
|
1020
|
+
return nucleo.leggiDeposito(key);
|
|
1021
|
+
},
|
|
1022
|
+
set(key, value) {
|
|
1023
|
+
return nucleo.scriviDeposito(key, value);
|
|
1024
|
+
},
|
|
1025
|
+
delete(key) {
|
|
1026
|
+
return nucleo.eliminaDeposito(key);
|
|
1027
|
+
},
|
|
1028
|
+
list(prefix) {
|
|
1029
|
+
return nucleo.elencaDeposito(prefix);
|
|
1030
|
+
},
|
|
1031
|
+
increment(key, amount = 1) {
|
|
1032
|
+
return nucleo.incrementaDeposito(key, amount);
|
|
1033
|
+
}
|
|
1034
|
+
},
|
|
826
1035
|
schedule(milliseconds, handler, payload) {
|
|
827
1036
|
nucleo.pianifica(milliseconds, handler, payload);
|
|
828
1037
|
},
|
|
@@ -837,8 +1046,14 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
837
1046
|
get mode() {
|
|
838
1047
|
return nucleo.manifest.voice ?? "none";
|
|
839
1048
|
},
|
|
1049
|
+
setGain(listener, speaker, gain) {
|
|
1050
|
+
nucleo.impostaGuadagno(idGiocatore(listener), idGiocatore(speaker), gain);
|
|
1051
|
+
},
|
|
840
1052
|
setProximity(a, b, gain) {
|
|
841
|
-
|
|
1053
|
+
const primo = idGiocatore(a);
|
|
1054
|
+
const secondo = idGiocatore(b);
|
|
1055
|
+
nucleo.impostaGuadagno(primo, secondo, gain);
|
|
1056
|
+
nucleo.impostaGuadagno(secondo, primo, gain);
|
|
842
1057
|
}
|
|
843
1058
|
}
|
|
844
1059
|
};
|
|
@@ -863,7 +1078,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
863
1078
|
return nucleo;
|
|
864
1079
|
}
|
|
865
1080
|
static verificaManifest(manifest) {
|
|
866
|
-
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)) {
|
|
1081
|
+
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)) {
|
|
867
1082
|
throw new TypeError("The room manifest is invalid.");
|
|
868
1083
|
}
|
|
869
1084
|
}
|
|
@@ -926,16 +1141,17 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
926
1141
|
await this.persistiEProgramma();
|
|
927
1142
|
return true;
|
|
928
1143
|
}
|
|
929
|
-
info() {
|
|
1144
|
+
info(playerId) {
|
|
930
1145
|
if (this.dati === null) return null;
|
|
931
1146
|
return {
|
|
932
1147
|
roomId: this.dati.id,
|
|
933
1148
|
status: this.dati.status,
|
|
934
|
-
players: this.dati.giocatori.filter(
|
|
1149
|
+
players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
|
|
935
1150
|
(player) => player.connected || player.graziaFinoA !== null
|
|
936
1151
|
).length,
|
|
937
1152
|
max: this.manifest.players.max,
|
|
938
|
-
mode: this.dati.mode
|
|
1153
|
+
mode: this.dati.mode,
|
|
1154
|
+
member: playerId === void 0 ? false : this.dati.giocatori.some((player) => player.id === playerId)
|
|
939
1155
|
};
|
|
940
1156
|
}
|
|
941
1157
|
giocatoreConnesso(connessione) {
|
|
@@ -981,7 +1197,6 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
981
1197
|
seq: 0
|
|
982
1198
|
};
|
|
983
1199
|
dati.giocatori.push(player);
|
|
984
|
-
dati.hostId ??= player.id;
|
|
985
1200
|
} else {
|
|
986
1201
|
if (player.connected && player.connessione !== null && player.connessione !== connessione) {
|
|
987
1202
|
this.adattatore.chiudi(player.connessione, 4006, "replaced");
|
|
@@ -993,6 +1208,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
993
1208
|
player.connessione = connessione;
|
|
994
1209
|
player.seq = 0;
|
|
995
1210
|
}
|
|
1211
|
+
dati.hostId ??= player.id;
|
|
996
1212
|
dati.vuotaDa = null;
|
|
997
1213
|
dati.ultimoInputAt = ora;
|
|
998
1214
|
const primaConnessione = !this.manifest.lobby && dati.status === "lobby";
|
|
@@ -1026,6 +1242,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1026
1242
|
player.connected = false;
|
|
1027
1243
|
player.connessione = null;
|
|
1028
1244
|
player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
|
|
1245
|
+
if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
|
|
1029
1246
|
this.frequenza.delete(connessione);
|
|
1030
1247
|
if (this.dati.hostId === player.id) this.assegnaHost();
|
|
1031
1248
|
this.verificaCountdown();
|
|
@@ -1095,7 +1312,8 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1095
1312
|
if (typeof message.role !== "string") return this.messaggioErrato(player);
|
|
1096
1313
|
if (!this.inLobby(player)) return;
|
|
1097
1314
|
this.dati.ultimoInputAt = ora;
|
|
1098
|
-
this.
|
|
1315
|
+
const errore = this.cambiaRuolo(player, message.role);
|
|
1316
|
+
if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
|
|
1099
1317
|
await this.persistiEProgramma();
|
|
1100
1318
|
return;
|
|
1101
1319
|
}
|
|
@@ -1103,7 +1321,8 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1103
1321
|
if (!Number.isInteger(message.team)) return this.messaggioErrato(player);
|
|
1104
1322
|
if (!this.inLobby(player)) return;
|
|
1105
1323
|
this.dati.ultimoInputAt = ora;
|
|
1106
|
-
this.
|
|
1324
|
+
const errore = this.cambiaSquadra(player, message.team);
|
|
1325
|
+
if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
|
|
1107
1326
|
await this.persistiEProgramma();
|
|
1108
1327
|
return;
|
|
1109
1328
|
}
|
|
@@ -1193,7 +1412,10 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1193
1412
|
const scaduti = this.dati.giocatori.filter(
|
|
1194
1413
|
(player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
|
|
1195
1414
|
);
|
|
1196
|
-
for (const player of scaduti)
|
|
1415
|
+
for (const player of scaduti) {
|
|
1416
|
+
if (this.manifest.persistent === true) player.graziaFinoA = null;
|
|
1417
|
+
else await this.rimuoviGiocatore(player, "timeout");
|
|
1418
|
+
}
|
|
1197
1419
|
if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
|
|
1198
1420
|
const errore = this.erroreMinimi();
|
|
1199
1421
|
if (errore !== null) {
|
|
@@ -1253,6 +1475,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1253
1475
|
player.connected = false;
|
|
1254
1476
|
player.connessione = null;
|
|
1255
1477
|
player.graziaFinoA = ora + GRAZIA_MS;
|
|
1478
|
+
if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
|
|
1256
1479
|
cambiato = true;
|
|
1257
1480
|
}
|
|
1258
1481
|
}
|
|
@@ -1296,37 +1519,52 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1296
1519
|
this.inviaErrore(player, "not_in_lobby", "This action is only available in the lobby.");
|
|
1297
1520
|
return false;
|
|
1298
1521
|
}
|
|
1299
|
-
|
|
1522
|
+
cambiaRuolo(player, roleId) {
|
|
1300
1523
|
const ruolo = this.manifest.roles.find((item) => item.id === roleId);
|
|
1301
1524
|
if (ruolo === void 0 && roleId !== "spectator") {
|
|
1302
|
-
|
|
1303
|
-
return;
|
|
1525
|
+
return { code: "invalid_role", message: "This role does not exist." };
|
|
1304
1526
|
}
|
|
1305
1527
|
const occupati = this.richiediDati().giocatori.filter(
|
|
1306
1528
|
(item) => item.id !== player.id && item.role === roleId
|
|
1307
1529
|
).length;
|
|
1308
1530
|
if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
|
|
1309
|
-
|
|
1310
|
-
return;
|
|
1531
|
+
return { code: "role_full", message: "This role is full." };
|
|
1311
1532
|
}
|
|
1312
1533
|
player.role = roleId;
|
|
1313
1534
|
if (roleId === "spectator") player.team = null;
|
|
1314
1535
|
else if (player.team === null) player.team = this.squadraAutomatica();
|
|
1315
|
-
player.ready = false;
|
|
1536
|
+
if (this.richiediDati().status === "lobby") player.ready = false;
|
|
1316
1537
|
this.inviaGiocatori();
|
|
1538
|
+
return null;
|
|
1317
1539
|
}
|
|
1318
|
-
|
|
1319
|
-
if (this.manifest.teams === null || team < 1 || team > this.manifest.teams.max) {
|
|
1320
|
-
|
|
1321
|
-
return;
|
|
1540
|
+
cambiaSquadra(player, team) {
|
|
1541
|
+
if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
|
|
1542
|
+
return { code: "invalid_team", message: "This team does not exist." };
|
|
1322
1543
|
}
|
|
1323
1544
|
if (player.role === "spectator") {
|
|
1324
|
-
|
|
1325
|
-
return;
|
|
1545
|
+
return { code: "spectator", message: "Spectators cannot join a team." };
|
|
1326
1546
|
}
|
|
1327
1547
|
player.team = team;
|
|
1328
|
-
player.ready = false;
|
|
1548
|
+
if (this.richiediDati().status === "lobby") player.ready = false;
|
|
1329
1549
|
this.inviaGiocatori();
|
|
1550
|
+
return null;
|
|
1551
|
+
}
|
|
1552
|
+
impostaRuoloDalServer(playerId, roleId) {
|
|
1553
|
+
const player = this.giocatorePerModificaDalServer(playerId);
|
|
1554
|
+
const errore = this.cambiaRuolo(player, roleId);
|
|
1555
|
+
if (errore !== null) throw erroreConCodice(errore.code, errore.message);
|
|
1556
|
+
}
|
|
1557
|
+
impostaSquadraDalServer(playerId, team) {
|
|
1558
|
+
const player = this.giocatorePerModificaDalServer(playerId);
|
|
1559
|
+
const errore = this.cambiaSquadra(player, team);
|
|
1560
|
+
if (errore !== null) throw erroreConCodice(errore.code, errore.message);
|
|
1561
|
+
}
|
|
1562
|
+
giocatorePerModificaDalServer(playerId) {
|
|
1563
|
+
const dati = this.richiediDati();
|
|
1564
|
+
if (dati.status === "ended") throw new Error("The room has ended.");
|
|
1565
|
+
const player = dati.giocatori.find((item) => item.id === playerId);
|
|
1566
|
+
if (player === void 0) throw erroreConCodice("player_not_found", "Player not found.");
|
|
1567
|
+
return player;
|
|
1330
1568
|
}
|
|
1331
1569
|
erroreMinimi() {
|
|
1332
1570
|
const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
|
|
@@ -1470,6 +1708,91 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1470
1708
|
if (!json.ok) throw new Error("The saved value is invalid.");
|
|
1471
1709
|
return json.valore;
|
|
1472
1710
|
}
|
|
1711
|
+
verificaChiaveDeposito(key) {
|
|
1712
|
+
if (typeof key !== "string" || !CHIAVE.test(key)) {
|
|
1713
|
+
throw erroreConCodice(
|
|
1714
|
+
"store_invalid_key",
|
|
1715
|
+
"Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
|
|
1716
|
+
);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
verificaPrefissoDeposito(prefix) {
|
|
1720
|
+
if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
|
|
1721
|
+
throw erroreConCodice(
|
|
1722
|
+
"store_invalid_key",
|
|
1723
|
+
"Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
|
|
1724
|
+
);
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
contaOperazioneDeposito() {
|
|
1728
|
+
const ora = this.adattatore.ora();
|
|
1729
|
+
this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
|
|
1730
|
+
if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
|
|
1731
|
+
throw erroreConCodice(
|
|
1732
|
+
"store_rate_limited",
|
|
1733
|
+
"The shared store allows at most 120 operations per minute for each room."
|
|
1734
|
+
);
|
|
1735
|
+
}
|
|
1736
|
+
this.frequenzaDeposito.push(ora);
|
|
1737
|
+
}
|
|
1738
|
+
async usaDeposito(operazione) {
|
|
1739
|
+
this.contaOperazioneDeposito();
|
|
1740
|
+
const deposito = this.adattatore.deposito;
|
|
1741
|
+
if (deposito === null) {
|
|
1742
|
+
throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
|
|
1743
|
+
}
|
|
1744
|
+
try {
|
|
1745
|
+
return await operazione(deposito);
|
|
1746
|
+
} catch (cause) {
|
|
1747
|
+
const code = cause instanceof Error ? cause.code : void 0;
|
|
1748
|
+
if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
|
|
1749
|
+
throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
async leggiDeposito(key) {
|
|
1753
|
+
this.verificaChiaveDeposito(key);
|
|
1754
|
+
const value = await this.usaDeposito((deposito) => deposito.get(key));
|
|
1755
|
+
if (value === null) return null;
|
|
1756
|
+
try {
|
|
1757
|
+
return JSON.parse(JSON.stringify(value));
|
|
1758
|
+
} catch {
|
|
1759
|
+
throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
async scriviDeposito(key, value) {
|
|
1763
|
+
this.verificaChiaveDeposito(key);
|
|
1764
|
+
const json = analizzaJson(value);
|
|
1765
|
+
if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
|
|
1766
|
+
throw erroreConCodice(
|
|
1767
|
+
"store_too_large",
|
|
1768
|
+
"Shared store values must be valid JSON of at most 65536 bytes."
|
|
1769
|
+
);
|
|
1770
|
+
}
|
|
1771
|
+
await this.usaDeposito((deposito) => deposito.set(key, json.valore));
|
|
1772
|
+
}
|
|
1773
|
+
async eliminaDeposito(key) {
|
|
1774
|
+
this.verificaChiaveDeposito(key);
|
|
1775
|
+
await this.usaDeposito((deposito) => deposito.delete(key));
|
|
1776
|
+
}
|
|
1777
|
+
async elencaDeposito(prefix) {
|
|
1778
|
+
this.verificaPrefissoDeposito(prefix);
|
|
1779
|
+
const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
|
|
1780
|
+
if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
|
|
1781
|
+
throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
|
|
1782
|
+
}
|
|
1783
|
+
return [...keys].sort().slice(0, 1024);
|
|
1784
|
+
}
|
|
1785
|
+
async incrementaDeposito(key, amount) {
|
|
1786
|
+
this.verificaChiaveDeposito(key);
|
|
1787
|
+
if (!Number.isSafeInteger(amount)) {
|
|
1788
|
+
throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
|
|
1789
|
+
}
|
|
1790
|
+
const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
|
|
1791
|
+
if (!Number.isSafeInteger(value)) {
|
|
1792
|
+
throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
|
|
1793
|
+
}
|
|
1794
|
+
return value;
|
|
1795
|
+
}
|
|
1473
1796
|
broadcastCreatore(message) {
|
|
1474
1797
|
const json = analizzaJson(message);
|
|
1475
1798
|
if (!json.ok) throw new TypeError("Messages must be valid JSON.");
|
|
@@ -1515,6 +1838,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1515
1838
|
you: player.id,
|
|
1516
1839
|
room: {
|
|
1517
1840
|
id: dati.id,
|
|
1841
|
+
seed: seedStanza(dati.id),
|
|
1518
1842
|
status: dati.status,
|
|
1519
1843
|
mode: dati.mode,
|
|
1520
1844
|
tick: dati.tick,
|
|
@@ -1615,16 +1939,15 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1615
1939
|
}
|
|
1616
1940
|
return stato;
|
|
1617
1941
|
}
|
|
1618
|
-
|
|
1619
|
-
if ((this.manifest.voice ?? "none")
|
|
1942
|
+
impostaGuadagno(listener, speaker, gain) {
|
|
1943
|
+
if ((this.manifest.voice ?? "none") === "none") return;
|
|
1620
1944
|
const dati = this.richiediDati();
|
|
1621
|
-
if (!dati.giocatori.some((player) => player.id ===
|
|
1945
|
+
if (!dati.giocatori.some((player) => player.id === listener) || !dati.giocatori.some((player) => player.id === speaker)) throw new Error("Player not found.");
|
|
1622
1946
|
if (Number.isNaN(gain)) throw new TypeError("Voice gain must be a number.");
|
|
1623
|
-
if (
|
|
1947
|
+
if (listener === speaker) return;
|
|
1624
1948
|
const valore = Math.round(Math.min(1, Math.max(0, gain)) * 100) / 100;
|
|
1625
1949
|
dati.voceGuadagni ??= {};
|
|
1626
|
-
this.salvaGuadagno(
|
|
1627
|
-
this.salvaGuadagno(b, a, valore);
|
|
1950
|
+
this.salvaGuadagno(listener, speaker, valore);
|
|
1628
1951
|
}
|
|
1629
1952
|
salvaGuadagno(playerId, altroId, valore) {
|
|
1630
1953
|
const dati = this.richiediDati();
|
|
@@ -1748,6 +2071,11 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1748
2071
|
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;
|
|
1749
2072
|
}
|
|
1750
2073
|
async terminaSeInattiva() {
|
|
2074
|
+
if (this.manifest.persistent === true) {
|
|
2075
|
+
if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
|
|
2076
|
+
await this.terminaInterna({ error: "expired" });
|
|
2077
|
+
return true;
|
|
2078
|
+
}
|
|
1751
2079
|
if (this.dati?.status !== "playing" || this.adattatore.ora() < this.dati.ultimoInputAt + INATTIVITA_MS) return false;
|
|
1752
2080
|
await this.terminaInterna({ error: "idle" });
|
|
1753
2081
|
return true;
|
|
@@ -1762,7 +2090,13 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1762
2090
|
this.serveTick() ? 1e3 / this.dati.tickRate : null
|
|
1763
2091
|
);
|
|
1764
2092
|
const prossime = [];
|
|
1765
|
-
if (this.
|
|
2093
|
+
if (this.manifest.persistent === true) {
|
|
2094
|
+
prossime.push(
|
|
2095
|
+
Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
|
|
2096
|
+
);
|
|
2097
|
+
} else if (this.dati.status === "playing") {
|
|
2098
|
+
prossime.push(this.dati.ultimoInputAt + INATTIVITA_MS);
|
|
2099
|
+
}
|
|
1766
2100
|
if (this.dati.countdownAt !== null) prossime.push(this.dati.countdownAt);
|
|
1767
2101
|
for (const player of this.dati.giocatori) {
|
|
1768
2102
|
if (!player.connected && player.graziaFinoA !== null) prossime.push(player.graziaFinoA);
|
|
@@ -2037,8 +2371,9 @@ var ArchivioNode = class _ArchivioNode {
|
|
|
2037
2371
|
}
|
|
2038
2372
|
};
|
|
2039
2373
|
var AdattatoreNode = class {
|
|
2040
|
-
constructor(storage) {
|
|
2374
|
+
constructor(storage, deposito) {
|
|
2041
2375
|
this.storage = storage;
|
|
2376
|
+
this.deposito = deposito;
|
|
2042
2377
|
this.connessioni = /* @__PURE__ */ new Map();
|
|
2043
2378
|
this.tickTimer = null;
|
|
2044
2379
|
this.tickIntervallo = null;
|
|
@@ -2134,6 +2469,7 @@ var StanzaNode = class {
|
|
|
2134
2469
|
this.manifest = manifest;
|
|
2135
2470
|
this.coda = Promise.resolve();
|
|
2136
2471
|
this.voceRoster = /* @__PURE__ */ new Map();
|
|
2472
|
+
this.voceListeners = /* @__PURE__ */ new Map();
|
|
2137
2473
|
this.voceFrequenza = /* @__PURE__ */ new Map();
|
|
2138
2474
|
this.voceUltimaRichiesta = /* @__PURE__ */ new Map();
|
|
2139
2475
|
this.frameFrequenza = /* @__PURE__ */ new Map();
|
|
@@ -2284,17 +2620,24 @@ var StanzaNode = class {
|
|
|
2284
2620
|
return;
|
|
2285
2621
|
}
|
|
2286
2622
|
if (richiesta.op === "publish") {
|
|
2287
|
-
|
|
2623
|
+
const mic = richiesta.mic !== false;
|
|
2624
|
+
if (role === "spectator" && mic) {
|
|
2288
2625
|
this.inviaErroreVoce(connessione, richiesta, "spectator", "Spectators cannot join voice.");
|
|
2289
2626
|
return;
|
|
2290
2627
|
}
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2628
|
+
if (mic) {
|
|
2629
|
+
this.voceListeners.delete(playerId);
|
|
2630
|
+
this.voceRoster.set(playerId, {
|
|
2631
|
+
id: playerId,
|
|
2632
|
+
session: "mesh",
|
|
2633
|
+
track: "mic",
|
|
2634
|
+
muted: false,
|
|
2635
|
+
connessione
|
|
2636
|
+
});
|
|
2637
|
+
} else {
|
|
2638
|
+
this.voceRoster.delete(playerId);
|
|
2639
|
+
this.voceListeners.set(playerId, connessione);
|
|
2640
|
+
}
|
|
2298
2641
|
this.adattatore.invia(connessione, { t: "voice", op: "publish", r: richiesta.r });
|
|
2299
2642
|
this.broadcastRoster();
|
|
2300
2643
|
return;
|
|
@@ -2330,9 +2673,11 @@ var StanzaNode = class {
|
|
|
2330
2673
|
}
|
|
2331
2674
|
if (richiesta.op === "stop") {
|
|
2332
2675
|
const peer = this.voceRoster.get(playerId);
|
|
2333
|
-
const
|
|
2676
|
+
const listener = this.voceListeners.get(playerId);
|
|
2677
|
+
const rimossaPeer = peer?.connessione === connessione && this.voceRoster.delete(playerId);
|
|
2678
|
+
const rimossoListener = listener === connessione && this.voceListeners.delete(playerId);
|
|
2334
2679
|
this.adattatore.invia(connessione, { t: "voice", op: "stop", r: richiesta.r });
|
|
2335
|
-
if (
|
|
2680
|
+
if (rimossaPeer || rimossoListener) this.broadcastRoster();
|
|
2336
2681
|
return;
|
|
2337
2682
|
}
|
|
2338
2683
|
this.inviaErroreVoce(connessione, richiesta, "invalid_request", "The voice request is invalid.");
|
|
@@ -2342,9 +2687,12 @@ var StanzaNode = class {
|
|
|
2342
2687
|
return null;
|
|
2343
2688
|
}
|
|
2344
2689
|
const base = { t: "voice", r: value.r };
|
|
2345
|
-
if (value.op === "ice" || value.op === "
|
|
2690
|
+
if (value.op === "ice" || value.op === "stop") {
|
|
2346
2691
|
return { ...base, op: value.op };
|
|
2347
2692
|
}
|
|
2693
|
+
if (value.op === "publish" && (value.mic === void 0 || typeof value.mic === "boolean")) {
|
|
2694
|
+
return { ...base, op: "publish", ...value.mic === void 0 ? {} : { mic: value.mic } };
|
|
2695
|
+
}
|
|
2348
2696
|
if (value.op === "mute" && typeof value.muted === "boolean") {
|
|
2349
2697
|
return { ...base, op: "mute", muted: value.muted };
|
|
2350
2698
|
}
|
|
@@ -2367,7 +2715,8 @@ var StanzaNode = class {
|
|
|
2367
2715
|
t: "voice",
|
|
2368
2716
|
op: "roster",
|
|
2369
2717
|
mode: this.modoVoce(),
|
|
2370
|
-
peers: this.rosterPubblico()
|
|
2718
|
+
peers: this.rosterPubblico(),
|
|
2719
|
+
listeners: [...this.voceListeners.keys()].sort((a, b) => a.localeCompare(b))
|
|
2371
2720
|
});
|
|
2372
2721
|
}
|
|
2373
2722
|
broadcastRoster() {
|
|
@@ -2381,6 +2730,11 @@ var StanzaNode = class {
|
|
|
2381
2730
|
this.voceRoster.delete(playerId);
|
|
2382
2731
|
cambiato = true;
|
|
2383
2732
|
}
|
|
2733
|
+
for (const [playerId, connessione] of this.voceListeners) {
|
|
2734
|
+
if (this.nucleo.giocatoreConnesso(connessione)?.id === playerId) continue;
|
|
2735
|
+
this.voceListeners.delete(playerId);
|
|
2736
|
+
cambiato = true;
|
|
2737
|
+
}
|
|
2384
2738
|
if (cambiato) this.broadcastRoster();
|
|
2385
2739
|
}
|
|
2386
2740
|
rimuoviConnessione(connessione) {
|
|
@@ -2396,6 +2750,9 @@ var StanzaNode = class {
|
|
|
2396
2750
|
if (this.voceRoster.get(playerId)?.connessione === connessione) {
|
|
2397
2751
|
this.voceRoster.delete(playerId);
|
|
2398
2752
|
this.broadcastRoster();
|
|
2753
|
+
} else if (this.voceListeners.get(playerId) === connessione) {
|
|
2754
|
+
this.voceListeners.delete(playerId);
|
|
2755
|
+
this.broadcastRoster();
|
|
2399
2756
|
}
|
|
2400
2757
|
}
|
|
2401
2758
|
inviaErroreVoce(connessione, richiesta, code, message) {
|
|
@@ -2406,7 +2763,7 @@ var StanzaNode = class {
|
|
|
2406
2763
|
};
|
|
2407
2764
|
async function createNodeRoom(definition, manifest, options = {}) {
|
|
2408
2765
|
const storage = await ArchivioNode.apri(options.storageFile ?? null);
|
|
2409
|
-
const adattatore = new AdattatoreNode(storage);
|
|
2766
|
+
const adattatore = new AdattatoreNode(storage, options.deposito ?? null);
|
|
2410
2767
|
const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
|
|
2411
2768
|
return new StanzaNode(nucleo, adattatore, manifest);
|
|
2412
2769
|
}
|
|
@@ -2420,6 +2777,70 @@ var FORMA_SESSIONE = /^[A-Za-z0-9_-]{8,128}$/;
|
|
|
2420
2777
|
var FORMA_CODICE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/;
|
|
2421
2778
|
var ALFABETO_CODICE = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
2422
2779
|
var MASSIMO_CORPO = 262144;
|
|
2780
|
+
var MASSIMO_FRAME_MATCH = 4096;
|
|
2781
|
+
var DURATA_STANZA_APERTA = 24 * 60 * 60 * 1e3;
|
|
2782
|
+
var VALORE_CHIAVE_MATCH = /^[A-Za-z0-9_.:-]+$/;
|
|
2783
|
+
var PREFISSO_DEPOSITO = /^[a-z0-9_-]{0,32}$/;
|
|
2784
|
+
var LIMITE_DEPOSITO2 = 64 * 1024;
|
|
2785
|
+
var MASSIMO_CHIAVI_DEPOSITO = 1024;
|
|
2786
|
+
function erroreDeposito(code, message) {
|
|
2787
|
+
return Object.assign(new Error(message), { code });
|
|
2788
|
+
}
|
|
2789
|
+
var DepositoDev = class {
|
|
2790
|
+
valori = /* @__PURE__ */ new Map();
|
|
2791
|
+
verificaChiave(key) {
|
|
2792
|
+
if (typeof key !== "string" || !CHIAVE_SAVE.test(key)) {
|
|
2793
|
+
throw erroreDeposito("store_invalid_key", "The shared store key is invalid.");
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
async get(key) {
|
|
2797
|
+
this.verificaChiave(key);
|
|
2798
|
+
const value = this.valori.get(key);
|
|
2799
|
+
return value === void 0 ? null : structuredClone(value);
|
|
2800
|
+
}
|
|
2801
|
+
async set(key, value) {
|
|
2802
|
+
this.verificaChiave(key);
|
|
2803
|
+
let testo;
|
|
2804
|
+
try {
|
|
2805
|
+
testo = JSON.stringify(value);
|
|
2806
|
+
} catch {
|
|
2807
|
+
throw erroreDeposito("store_too_large", "The shared store value is not valid JSON.");
|
|
2808
|
+
}
|
|
2809
|
+
if (testo === void 0 || Buffer.byteLength(testo, "utf8") > LIMITE_DEPOSITO2) {
|
|
2810
|
+
throw erroreDeposito("store_too_large", "The shared store value is too large.");
|
|
2811
|
+
}
|
|
2812
|
+
if (!this.valori.has(key) && this.valori.size >= MASSIMO_CHIAVI_DEPOSITO) {
|
|
2813
|
+
throw erroreDeposito("store_full", "The shared store is full.");
|
|
2814
|
+
}
|
|
2815
|
+
this.valori.set(key, JSON.parse(testo));
|
|
2816
|
+
}
|
|
2817
|
+
async delete(key) {
|
|
2818
|
+
this.verificaChiave(key);
|
|
2819
|
+
this.valori.delete(key);
|
|
2820
|
+
}
|
|
2821
|
+
async list(prefix = "") {
|
|
2822
|
+
if (typeof prefix !== "string" || !PREFISSO_DEPOSITO.test(prefix)) {
|
|
2823
|
+
throw erroreDeposito("store_invalid_key", "The shared store prefix is invalid.");
|
|
2824
|
+
}
|
|
2825
|
+
return [...this.valori.keys()].filter((key) => key.startsWith(prefix)).sort().slice(0, MASSIMO_CHIAVI_DEPOSITO);
|
|
2826
|
+
}
|
|
2827
|
+
async increment(key, amount = 1) {
|
|
2828
|
+
this.verificaChiave(key);
|
|
2829
|
+
const current = this.valori.get(key) ?? 0;
|
|
2830
|
+
if (!Number.isSafeInteger(current) || !Number.isSafeInteger(amount)) {
|
|
2831
|
+
throw erroreDeposito("store_not_integer", "The shared store value is not a safe integer.");
|
|
2832
|
+
}
|
|
2833
|
+
const result = Number(current) + amount;
|
|
2834
|
+
if (!Number.isSafeInteger(result)) {
|
|
2835
|
+
throw erroreDeposito("store_not_integer", "The shared store value is not a safe integer.");
|
|
2836
|
+
}
|
|
2837
|
+
if (!this.valori.has(key) && this.valori.size >= MASSIMO_CHIAVI_DEPOSITO) {
|
|
2838
|
+
throw erroreDeposito("store_full", "The shared store is full.");
|
|
2839
|
+
}
|
|
2840
|
+
this.valori.set(key, result);
|
|
2841
|
+
return result;
|
|
2842
|
+
}
|
|
2843
|
+
};
|
|
2423
2844
|
var DevHttpError = class extends Error {
|
|
2424
2845
|
constructor(status, code, message, hints = []) {
|
|
2425
2846
|
super(message);
|
|
@@ -2493,6 +2914,24 @@ function joinTicket(player, room, secret) {
|
|
|
2493
2914
|
exp: iat + DURATA_INGRESSO
|
|
2494
2915
|
}, secret);
|
|
2495
2916
|
}
|
|
2917
|
+
function matchTicket(player, game, mode, key, matchmaking, players, lobby, secret) {
|
|
2918
|
+
const iat = currentSeconds();
|
|
2919
|
+
return signJwt({
|
|
2920
|
+
sub: player.id,
|
|
2921
|
+
game,
|
|
2922
|
+
name: player.name,
|
|
2923
|
+
guest: player.guest,
|
|
2924
|
+
mode,
|
|
2925
|
+
key,
|
|
2926
|
+
timeoutMs: matchmaking.timeoutMs,
|
|
2927
|
+
min: players.min,
|
|
2928
|
+
max: players.max,
|
|
2929
|
+
lobby,
|
|
2930
|
+
aud: "match",
|
|
2931
|
+
iat,
|
|
2932
|
+
exp: iat + DURATA_INGRESSO
|
|
2933
|
+
}, secret);
|
|
2934
|
+
}
|
|
2496
2935
|
function validTimes(payload, duration) {
|
|
2497
2936
|
const now = currentSeconds();
|
|
2498
2937
|
return typeof payload.iat === "number" && Number.isInteger(payload.iat) && typeof payload.exp === "number" && Number.isInteger(payload.exp) && payload.exp === payload.iat + duration && payload.iat <= now + 5 && payload.exp > now;
|
|
@@ -2512,6 +2951,11 @@ function readJoinTicket(token, room, secret) {
|
|
|
2512
2951
|
if (payload === null || payload.aud !== "room" || payload.room !== room || typeof payload.sub !== "string" || payload.sub === "" || typeof payload.name !== "string" || payload.name === "" || typeof payload.guest !== "boolean" || !validTimes(payload, DURATA_INGRESSO)) return null;
|
|
2513
2952
|
return payload;
|
|
2514
2953
|
}
|
|
2954
|
+
function readMatchTicket(token, game, secret) {
|
|
2955
|
+
const payload = verifyJwt(token, secret);
|
|
2956
|
+
if (payload === null || payload.aud !== "match" || payload.game !== game || typeof payload.sub !== "string" || payload.sub === "" || typeof payload.name !== "string" || payload.name === "" || typeof payload.guest !== "boolean" || typeof payload.mode !== "string" || payload.mode === "" || typeof payload.key !== "string" || payload.key === "" || !Number.isInteger(payload.timeoutMs) || payload.timeoutMs < 1e3 || payload.timeoutMs > 3e5 || !Number.isInteger(payload.min) || payload.min < 1 || !Number.isInteger(payload.max) || payload.max < payload.min || typeof payload.lobby !== "boolean" || !validTimes(payload, DURATA_INGRESSO)) return null;
|
|
2957
|
+
return payload;
|
|
2958
|
+
}
|
|
2515
2959
|
function playerFromTicket(ticket) {
|
|
2516
2960
|
return { id: ticket.sub, name: ticket.name, guest: ticket.guest };
|
|
2517
2961
|
}
|
|
@@ -2627,6 +3071,34 @@ async function readBody(request, maximum = MASSIMO_CORPO) {
|
|
|
2627
3071
|
throw new DevHttpError(400, "invalid_request", "The request body must be valid JSON.");
|
|
2628
3072
|
}
|
|
2629
3073
|
}
|
|
3074
|
+
function canonicalMatchKey(value, fields) {
|
|
3075
|
+
const key = object(value);
|
|
3076
|
+
if (key === null) {
|
|
3077
|
+
throw new DevHttpError(400, "invalid_request", "key must be an object.");
|
|
3078
|
+
}
|
|
3079
|
+
for (const field of fields) {
|
|
3080
|
+
if (!Object.hasOwn(key, field)) {
|
|
3081
|
+
throw new DevHttpError(400, "invalid_request", `Matchmaking key field ${field} is missing.`);
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
for (const field of Object.keys(key)) {
|
|
3085
|
+
if (!fields.includes(field)) {
|
|
3086
|
+
throw new DevHttpError(400, "invalid_request", `Matchmaking key field ${field} is not allowed.`);
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
return fields.map((field) => {
|
|
3090
|
+
const item = key[field];
|
|
3091
|
+
if (typeof item === "string" && item.length >= 1 && item.length <= 64 && VALORE_CHIAVE_MATCH.test(item)) {
|
|
3092
|
+
return encodeURIComponent(item);
|
|
3093
|
+
}
|
|
3094
|
+
if (typeof item === "number" && Number.isSafeInteger(item)) return encodeURIComponent(String(item));
|
|
3095
|
+
throw new DevHttpError(
|
|
3096
|
+
400,
|
|
3097
|
+
"invalid_request",
|
|
3098
|
+
`Matchmaking key field ${field} must be a valid string or safe integer.`
|
|
3099
|
+
);
|
|
3100
|
+
}).join("/");
|
|
3101
|
+
}
|
|
2630
3102
|
function parentPage(input) {
|
|
2631
3103
|
return `<!doctype html>
|
|
2632
3104
|
<html lang="en">
|
|
@@ -2697,10 +3169,10 @@ function parentPage(input) {
|
|
|
2697
3169
|
`;
|
|
2698
3170
|
}
|
|
2699
3171
|
async function readGame(root) {
|
|
2700
|
-
const manifestPath =
|
|
3172
|
+
const manifestPath = join2(root, "caisual.json");
|
|
2701
3173
|
let parsed;
|
|
2702
3174
|
try {
|
|
2703
|
-
parsed = JSON.parse(await
|
|
3175
|
+
parsed = JSON.parse(await fs2.readFile(manifestPath, "utf8"));
|
|
2704
3176
|
} catch {
|
|
2705
3177
|
throw new Error("caisual.json: file not found, unreadable, or invalid JSON.");
|
|
2706
3178
|
}
|
|
@@ -2709,28 +3181,25 @@ async function readGame(root) {
|
|
|
2709
3181
|
throw new Error(`caisual.json is not valid:
|
|
2710
3182
|
${result.errori.map((error) => `- ${error}`).join("\n")}`);
|
|
2711
3183
|
}
|
|
2712
|
-
const clientRoot = await
|
|
3184
|
+
const clientRoot = await fs2.realpath(join2(root, "client")).catch(() => null);
|
|
2713
3185
|
if (clientRoot === null) throw new Error("client/: folder not found.");
|
|
2714
|
-
const stat = await
|
|
3186
|
+
const stat = await fs2.stat(clientRoot);
|
|
2715
3187
|
if (!stat.isDirectory()) throw new Error("client/: must be a folder.");
|
|
2716
|
-
const index = await
|
|
3188
|
+
const index = await fs2.stat(join2(clientRoot, "index.html")).catch(() => null);
|
|
2717
3189
|
if (index === null || !index.isFile()) throw new Error("client/index.html: file not found.");
|
|
2718
3190
|
return { manifest: result.manifest, clientRoot };
|
|
2719
3191
|
}
|
|
2720
3192
|
async function loadDefinition(root) {
|
|
2721
|
-
const path =
|
|
2722
|
-
let
|
|
3193
|
+
const path = join2(root, "server.js");
|
|
3194
|
+
let stat;
|
|
2723
3195
|
try {
|
|
2724
|
-
|
|
3196
|
+
stat = await fs2.lstat(path);
|
|
2725
3197
|
} catch (cause) {
|
|
2726
3198
|
if (cause.code === "ENOENT") return null;
|
|
2727
3199
|
throw new Error("server.js: file not readable.");
|
|
2728
3200
|
}
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
throw new Error(`server.js is not valid:
|
|
2732
|
-
${result.errori.map((error) => `- ${error}`).join("\n")}`);
|
|
2733
|
-
}
|
|
3201
|
+
if (!stat.isFile()) throw new Error("server.js: file not readable.");
|
|
3202
|
+
const { source } = await bundleServer(root);
|
|
2734
3203
|
const kitUrl = `data:text/javascript;base64,${Buffer.from('// src/server/index.ts\nvar GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");\nvar CALLBACKS = [\n "onCreate",\n "onStart",\n "onJoin",\n "onLeave",\n "onMessage",\n "onTick",\n "onEnd"\n];\nfunction isRecord(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction defineGame(definition) {\n if (!isRecord(definition)) {\n throw new TypeError("Game definition must be an object.");\n }\n if (typeof definition.tickRate !== "number" || !Number.isInteger(definition.tickRate) || definition.tickRate < 0 || definition.tickRate > 60) {\n throw new TypeError("Game definition tickRate must be an integer from 0 to 60.");\n }\n for (const callback of CALLBACKS) {\n const value = definition[callback];\n if (value !== void 0 && typeof value !== "function") {\n throw new TypeError(`Game definition ${callback} must be a function.`);\n }\n }\n Object.defineProperty(definition, GAME_DEFINITION, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false\n });\n return definition;\n}\nexport {\n defineGame\n};\n').toString("base64")}`;
|
|
2735
3204
|
const rewritten = source.replace(
|
|
2736
3205
|
/(\bfrom\s*)(['"])@caisual\/kit\/server\2/g,
|
|
@@ -2760,9 +3229,12 @@ var DevService = class {
|
|
|
2760
3229
|
saves = /* @__PURE__ */ new Map();
|
|
2761
3230
|
scores = /* @__PURE__ */ new Map();
|
|
2762
3231
|
rooms = /* @__PURE__ */ new Map();
|
|
3232
|
+
deposito = new DepositoDev();
|
|
2763
3233
|
roomByCode = /* @__PURE__ */ new Map();
|
|
3234
|
+
matchQueues = /* @__PURE__ */ new Map();
|
|
2764
3235
|
kitRequests = /* @__PURE__ */ new Map();
|
|
2765
3236
|
liveRequests = /* @__PURE__ */ new Map();
|
|
3237
|
+
matchOperations = Promise.resolve();
|
|
2766
3238
|
playerNumber = 0;
|
|
2767
3239
|
get portalOrigin() {
|
|
2768
3240
|
return `http://localhost:${this.port}`;
|
|
@@ -2785,6 +3257,10 @@ var DevService = class {
|
|
|
2785
3257
|
}
|
|
2786
3258
|
async handleUpgrade(request, socket, head) {
|
|
2787
3259
|
const url = new URL(request.url ?? "/", this.portalOrigin);
|
|
3260
|
+
if (url.pathname === "/match") {
|
|
3261
|
+
await this.handleMatchUpgrade(request, socket, head, url);
|
|
3262
|
+
return;
|
|
3263
|
+
}
|
|
2788
3264
|
const match = /^\/rooms\/(g1-1\.[a-z0-9]{16})$/.exec(url.pathname);
|
|
2789
3265
|
if (match === null || match[1] === void 0) {
|
|
2790
3266
|
this.rejectUpgrade(socket, 404, "room_not_found", "The room was not found.");
|
|
@@ -2812,12 +3288,234 @@ var DevService = class {
|
|
|
2812
3288
|
}
|
|
2813
3289
|
try {
|
|
2814
3290
|
const websocket = acceptNodeWebSocket2(request, socket, head);
|
|
2815
|
-
await localRoom.room.connect(websocket, identity);
|
|
3291
|
+
const result = await localRoom.room.connect(websocket, identity);
|
|
3292
|
+
if (result.ok) localRoom.pendingMatch.delete(identity.id);
|
|
2816
3293
|
} catch {
|
|
2817
3294
|
if (!socket.destroyed) this.rejectUpgrade(socket, 400, "invalid_request", "The WebSocket request is invalid.");
|
|
2818
3295
|
}
|
|
2819
3296
|
}
|
|
3297
|
+
async handleMatchUpgrade(request, socket, head, url) {
|
|
3298
|
+
const token = url.searchParams.get("j");
|
|
3299
|
+
const ticket = token === null ? null : readMatchTicket(token, this.manifest.id, this.secret);
|
|
3300
|
+
const origin = request.headers.origin;
|
|
3301
|
+
const nodeClient = origin === void 0 && request.headers["user-agent"] === "node";
|
|
3302
|
+
if (ticket === null || origin !== this.gameOrigin && !nodeClient) {
|
|
3303
|
+
this.rejectUpgrade(socket, 401, "unauthorized", "The matchmaking connection is not authorized.");
|
|
3304
|
+
return;
|
|
3305
|
+
}
|
|
3306
|
+
try {
|
|
3307
|
+
this.checkRate(this.liveRequests, ticket.sub);
|
|
3308
|
+
} catch (cause) {
|
|
3309
|
+
const error = cause instanceof DevHttpError ? cause : new DevHttpError(429, "rate_limited", "Too many game API requests were sent.");
|
|
3310
|
+
this.rejectUpgrade(socket, error.status, error.code, error.message);
|
|
3311
|
+
return;
|
|
3312
|
+
}
|
|
3313
|
+
let websocket;
|
|
3314
|
+
try {
|
|
3315
|
+
websocket = acceptNodeWebSocket2(request, socket, head);
|
|
3316
|
+
} catch {
|
|
3317
|
+
if (!socket.destroyed) {
|
|
3318
|
+
this.rejectUpgrade(socket, 400, "invalid_request", "The WebSocket request is invalid.");
|
|
3319
|
+
}
|
|
3320
|
+
return;
|
|
3321
|
+
}
|
|
3322
|
+
const queueId = this.matchQueueId(ticket);
|
|
3323
|
+
websocket.on("message", (message) => this.handleMatchMessage(websocket, message));
|
|
3324
|
+
websocket.on("close", () => {
|
|
3325
|
+
void this.serializeMatch(() => this.removeMatchWaiter(queueId, websocket));
|
|
3326
|
+
});
|
|
3327
|
+
try {
|
|
3328
|
+
await this.serializeMatch(() => this.enterMatchQueue(queueId, ticket, websocket));
|
|
3329
|
+
} catch {
|
|
3330
|
+
this.sendMatchError(websocket, "internal_error", "The local matchmaking search failed.");
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
matchQueueId(ticket) {
|
|
3334
|
+
return `${ticket.game}\0${ticket.mode}\0${ticket.key}`;
|
|
3335
|
+
}
|
|
3336
|
+
serializeMatch(operation) {
|
|
3337
|
+
const result = this.matchOperations.then(operation);
|
|
3338
|
+
this.matchOperations = result.then(() => void 0, () => void 0);
|
|
3339
|
+
return result;
|
|
3340
|
+
}
|
|
3341
|
+
matchQueue(queueId) {
|
|
3342
|
+
let queue = this.matchQueues.get(queueId);
|
|
3343
|
+
if (queue === void 0) {
|
|
3344
|
+
queue = { waiting: [], open: [], timer: null };
|
|
3345
|
+
this.matchQueues.set(queueId, queue);
|
|
3346
|
+
}
|
|
3347
|
+
return queue;
|
|
3348
|
+
}
|
|
3349
|
+
handleMatchMessage(socket, frame) {
|
|
3350
|
+
if (Buffer.byteLength(frame, "utf8") > MASSIMO_FRAME_MATCH) {
|
|
3351
|
+
socket.close(4009, "bad_message");
|
|
3352
|
+
return;
|
|
3353
|
+
}
|
|
3354
|
+
let message = null;
|
|
3355
|
+
try {
|
|
3356
|
+
message = object(JSON.parse(frame));
|
|
3357
|
+
} catch {
|
|
3358
|
+
}
|
|
3359
|
+
if (message === null || message.t !== "ping" || typeof message.c !== "number" || !Number.isFinite(message.c) || Object.keys(message).some((key) => key !== "t" && key !== "c")) {
|
|
3360
|
+
socket.close(4009, "bad_message");
|
|
3361
|
+
return;
|
|
3362
|
+
}
|
|
3363
|
+
socket.send(JSON.stringify({ t: "pong", c: message.c }));
|
|
3364
|
+
}
|
|
3365
|
+
async enterMatchQueue(queueId, ticket, socket) {
|
|
3366
|
+
const queue = this.matchQueue(queueId);
|
|
3367
|
+
const previous = queue.waiting.findIndex((waiting) => waiting.ticket.sub === ticket.sub);
|
|
3368
|
+
if (previous >= 0) {
|
|
3369
|
+
const [replaced] = queue.waiting.splice(previous, 1);
|
|
3370
|
+
replaced?.socket.close(4006, "replaced");
|
|
3371
|
+
}
|
|
3372
|
+
if (await this.fillOpenMatchRoom(queue, ticket, socket)) {
|
|
3373
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3374
|
+
return;
|
|
3375
|
+
}
|
|
3376
|
+
queue.waiting.push({ ticket, socket, at: Date.now() });
|
|
3377
|
+
this.notifyMatchQueue(queue);
|
|
3378
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3379
|
+
if (queue.waiting.length >= ticket.max) {
|
|
3380
|
+
await this.openMatchRoom(queueId, queue, ticket.max);
|
|
3381
|
+
}
|
|
3382
|
+
}
|
|
3383
|
+
async fillOpenMatchRoom(queue, ticket, socket) {
|
|
3384
|
+
const now = Date.now();
|
|
3385
|
+
const remove = /* @__PURE__ */ new Set();
|
|
3386
|
+
for (const opened of [...queue.open].sort((left, right) => right.at - left.at)) {
|
|
3387
|
+
if (now - opened.at >= DURATA_STANZA_APERTA) {
|
|
3388
|
+
remove.add(opened.roomId);
|
|
3389
|
+
continue;
|
|
3390
|
+
}
|
|
3391
|
+
const localRoom = this.rooms.get(opened.roomId);
|
|
3392
|
+
const info = localRoom === void 0 ? null : await localRoom.room.info();
|
|
3393
|
+
if (localRoom === void 0 || info === null || info.status === "ended") {
|
|
3394
|
+
remove.add(opened.roomId);
|
|
3395
|
+
continue;
|
|
3396
|
+
}
|
|
3397
|
+
for (const [playerId, expiresAt] of localRoom.pendingMatch) {
|
|
3398
|
+
if (expiresAt <= now) localRoom.pendingMatch.delete(playerId);
|
|
3399
|
+
}
|
|
3400
|
+
const canEnter = info.status === "lobby" || !ticket.lobby;
|
|
3401
|
+
if (!canEnter || info.players + localRoom.pendingMatch.size >= info.max) continue;
|
|
3402
|
+
const permission = await localRoom.room.canJoin(playerFromTicket(ticket));
|
|
3403
|
+
if (!permission.ok) {
|
|
3404
|
+
if (permission.code === "room_not_found" || permission.code === "room_ended") {
|
|
3405
|
+
remove.add(opened.roomId);
|
|
3406
|
+
}
|
|
3407
|
+
continue;
|
|
3408
|
+
}
|
|
3409
|
+
localRoom.pendingMatch.set(ticket.sub, now + DURATA_INGRESSO * 1e3);
|
|
3410
|
+
queue.open = queue.open.filter((entry) => !remove.has(entry.roomId));
|
|
3411
|
+
this.sendMatched(socket, opened.roomId, localRoom, playerFromTicket(ticket));
|
|
3412
|
+
return true;
|
|
3413
|
+
}
|
|
3414
|
+
queue.open = queue.open.filter((entry) => !remove.has(entry.roomId));
|
|
3415
|
+
return false;
|
|
3416
|
+
}
|
|
3417
|
+
async openMatchRoom(queueId, queue, count) {
|
|
3418
|
+
const selected = queue.waiting.splice(0, Math.min(count, queue.waiting.length));
|
|
3419
|
+
const first = selected[0];
|
|
3420
|
+
if (first === void 0) return;
|
|
3421
|
+
try {
|
|
3422
|
+
const { roomId, localRoom } = await this.openLocalRoom(
|
|
3423
|
+
first.ticket.mode,
|
|
3424
|
+
playerFromTicket(first.ticket)
|
|
3425
|
+
);
|
|
3426
|
+
const expiresAt = Date.now() + DURATA_INGRESSO * 1e3;
|
|
3427
|
+
for (const waiting of selected) {
|
|
3428
|
+
localRoom.pendingMatch.set(waiting.ticket.sub, expiresAt);
|
|
3429
|
+
}
|
|
3430
|
+
queue.open = queue.open.filter((entry) => Date.now() - entry.at < DURATA_STANZA_APERTA);
|
|
3431
|
+
queue.open.push({ roomId, at: Date.now() });
|
|
3432
|
+
if (queue.open.length > 20) queue.open.splice(0, queue.open.length - 20);
|
|
3433
|
+
for (const waiting of selected) {
|
|
3434
|
+
this.sendMatched(waiting.socket, roomId, localRoom, playerFromTicket(waiting.ticket));
|
|
3435
|
+
}
|
|
3436
|
+
} catch (cause) {
|
|
3437
|
+
const code = cause instanceof DevHttpError ? cause.code : "internal_error";
|
|
3438
|
+
const message = cause instanceof DevHttpError ? cause.message : "The local room could not be created.";
|
|
3439
|
+
for (const waiting of selected) this.sendMatchError(waiting.socket, code, message);
|
|
3440
|
+
}
|
|
3441
|
+
this.notifyMatchQueue(queue);
|
|
3442
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3443
|
+
}
|
|
3444
|
+
removeMatchWaiter(queueId, socket) {
|
|
3445
|
+
const queue = this.matchQueues.get(queueId);
|
|
3446
|
+
if (queue === void 0) return;
|
|
3447
|
+
const index = queue.waiting.findIndex((waiting) => waiting.socket === socket);
|
|
3448
|
+
if (index < 0) return;
|
|
3449
|
+
queue.waiting.splice(index, 1);
|
|
3450
|
+
this.notifyMatchQueue(queue);
|
|
3451
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3452
|
+
}
|
|
3453
|
+
notifyMatchQueue(queue) {
|
|
3454
|
+
for (const waiting of queue.waiting) {
|
|
3455
|
+
waiting.socket.send(JSON.stringify({
|
|
3456
|
+
t: "waiting",
|
|
3457
|
+
players: queue.waiting.length,
|
|
3458
|
+
min: waiting.ticket.min,
|
|
3459
|
+
max: waiting.ticket.max
|
|
3460
|
+
}));
|
|
3461
|
+
}
|
|
3462
|
+
}
|
|
3463
|
+
scheduleMatchQueue(queueId, queue) {
|
|
3464
|
+
if (queue.timer !== null) clearTimeout(queue.timer);
|
|
3465
|
+
queue.timer = null;
|
|
3466
|
+
const next = queue.waiting.reduce(
|
|
3467
|
+
(nearest, waiting) => Math.min(nearest, waiting.at + waiting.ticket.timeoutMs),
|
|
3468
|
+
Number.POSITIVE_INFINITY
|
|
3469
|
+
);
|
|
3470
|
+
if (!Number.isFinite(next)) return;
|
|
3471
|
+
queue.timer = setTimeout(() => {
|
|
3472
|
+
queue.timer = null;
|
|
3473
|
+
void this.serializeMatch(() => this.expireMatchQueue(queueId));
|
|
3474
|
+
}, Math.max(0, next - Date.now()));
|
|
3475
|
+
queue.timer.unref();
|
|
3476
|
+
}
|
|
3477
|
+
async expireMatchQueue(queueId) {
|
|
3478
|
+
const queue = this.matchQueues.get(queueId);
|
|
3479
|
+
if (queue === void 0 || queue.waiting.length === 0) return;
|
|
3480
|
+
const now = Date.now();
|
|
3481
|
+
const expired = queue.waiting.filter(
|
|
3482
|
+
(waiting) => waiting.at + waiting.ticket.timeoutMs <= now
|
|
3483
|
+
);
|
|
3484
|
+
if (expired.length === 0) {
|
|
3485
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3486
|
+
return;
|
|
3487
|
+
}
|
|
3488
|
+
const first = queue.waiting[0];
|
|
3489
|
+
if (first !== void 0 && queue.waiting.length >= first.ticket.min) {
|
|
3490
|
+
await this.openMatchRoom(queueId, queue, Math.min(first.ticket.max, queue.waiting.length));
|
|
3491
|
+
return;
|
|
3492
|
+
}
|
|
3493
|
+
const expiredSockets = new Set(expired.map((waiting) => waiting.socket));
|
|
3494
|
+
queue.waiting = queue.waiting.filter((waiting) => !expiredSockets.has(waiting.socket));
|
|
3495
|
+
for (const waiting of expired) {
|
|
3496
|
+
waiting.socket.send(JSON.stringify({ t: "no_match" }));
|
|
3497
|
+
waiting.socket.close(1e3);
|
|
3498
|
+
}
|
|
3499
|
+
this.notifyMatchQueue(queue);
|
|
3500
|
+
this.scheduleMatchQueue(queueId, queue);
|
|
3501
|
+
}
|
|
3502
|
+
sendMatched(socket, roomId, localRoom, player) {
|
|
3503
|
+
socket.send(JSON.stringify({
|
|
3504
|
+
t: "matched",
|
|
3505
|
+
...this.joinResponse(roomId, localRoom.code, player)
|
|
3506
|
+
}));
|
|
3507
|
+
socket.close(1e3);
|
|
3508
|
+
}
|
|
3509
|
+
sendMatchError(socket, code, message) {
|
|
3510
|
+
socket.send(JSON.stringify({ t: "error", code, message }));
|
|
3511
|
+
socket.close(1e3);
|
|
3512
|
+
}
|
|
2820
3513
|
async close() {
|
|
3514
|
+
for (const queue of this.matchQueues.values()) {
|
|
3515
|
+
if (queue.timer !== null) clearTimeout(queue.timer);
|
|
3516
|
+
for (const waiting of queue.waiting) waiting.socket.close(1001, "server_shutdown");
|
|
3517
|
+
}
|
|
3518
|
+
this.matchQueues.clear();
|
|
2821
3519
|
await Promise.all([...this.rooms.values()].map((entry) => entry.room.close()));
|
|
2822
3520
|
}
|
|
2823
3521
|
async handleGame(request, response, url) {
|
|
@@ -2830,7 +3528,7 @@ var DevService = class {
|
|
|
2830
3528
|
response.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
2831
3529
|
response.setHeader("Cache-Control", "no-store");
|
|
2832
3530
|
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
2833
|
-
response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.3.0\n\n// src/errors.ts\nfunction creaErrore(code, message) {\n return Object.assign(new Error(message), { name: "CaisualError", code });\n}\nfunction erroreOffline() {\n return creaErrore("offline", "Caisual services are unavailable.");\n}\nfunction codiceErrore(valore) {\n return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;\n}\n\n// src/http.ts\nasync function leggiErrore(response) {\n let corpo = {};\n try {\n corpo = await response.json();\n } catch {\n }\n return creaErrore(\n typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error",\n typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`\n );\n}\nfunction creaRichiedente(origin, prefix, fetcher, biglietto) {\n async function manda(path, metodo, ticket, corpo) {\n const headers = new Headers({ Authorization: `Bearer ${ticket}` });\n let body;\n if (corpo !== void 0) {\n headers.set("Content-Type", "application/json");\n try {\n body = JSON.stringify(corpo);\n } catch {\n throw creaErrore("invalid_request", "The value must be valid JSON.");\n }\n }\n try {\n return await fetcher(new URL(prefix + path, origin), {\n method: metodo,\n headers,\n body,\n credentials: "omit"\n });\n } catch {\n throw erroreOffline();\n }\n }\n return async function richiesta(path, metodo, corpo, forzaRinnovo = false) {\n let ticket;\n try {\n ticket = forzaRinnovo ? await biglietto.rinnova() : await biglietto.ottieni();\n } catch {\n throw erroreOffline();\n }\n let response = await manda(path, metodo, ticket, corpo);\n if (response.status === 401) {\n try {\n ticket = await biglietto.rinnova();\n } catch {\n throw erroreOffline();\n }\n response = await manda(path, metodo, ticket, corpo);\n }\n if (!response.ok) throw await leggiErrore(response);\n try {\n return await response.json();\n } catch {\n throw creaErrore("internal_error", "The service returned an invalid response.");\n }\n };\n}\n\n// src/api.ts\nfunction creaClienteApi(appOrigin, fetcher, biglietto) {\n const richiesta = creaRichiedente(appOrigin, "/api/kit", fetcher, biglietto);\n return {\n me: () => richiesta("/me", "GET"),\n saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),\n async saveGet(key) {\n try {\n return (await richiesta(`/saves/${encodeURIComponent(key)}`, "GET")).value;\n } catch (errore) {\n if (codiceErrore(errore) === "not_found") return null;\n throw errore;\n }\n },\n async saveRemove(key) {\n await richiesta(`/saves/${encodeURIComponent(key)}`, "DELETE");\n },\n async saveList() {\n return (await richiesta("/saves", "GET")).saves;\n },\n async boardSubmit(board, score, daily) {\n const risultato = await richiesta("/scores", "POST", { board, score, daily });\n return { accepted: true, best: risultato.best, rank: risultato.rank, day: risultato.day };\n },\n async boardTop(board, opzioni) {\n const query = new URLSearchParams();\n if (opzioni.daily) query.set("daily", "1");\n if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));\n if (opzioni.guests) query.set("guests", "1");\n const suffisso = query.size === 0 ? "" : `?${query.toString()}`;\n const { day, entries, me } = await richiesta(\n `/scores/${encodeURIComponent(board)}${suffisso}`,\n "GET"\n );\n return { day, entries, me };\n }\n };\n}\n\n// src/daily.ts\nvar DIVISORE_UINT32 = 4294967296;\nfunction giornoUtc(ora) {\n return new Date(ora).toISOString().slice(0, 10);\n}\nasync function calcolaSeed(gioco, giorno, subtle) {\n const dati = new TextEncoder().encode(`caisual:${gioco}:${giorno}`);\n const digest = new Uint8Array(await subtle.digest("SHA-256", dati));\n return (digest[0] ?? 0) * 16777216 + ((digest[1] ?? 0) << 16) + ((digest[2] ?? 0) << 8) + (digest[3] ?? 0) >>> 0;\n}\nfunction creaMulberry32(seed) {\n let stato = seed >>> 0;\n return () => {\n stato = stato + 1831565813 >>> 0;\n let valore = stato;\n valore = Math.imul(valore ^ valore >>> 15, valore | 1);\n valore ^= valore + Math.imul(valore ^ valore >>> 7, valore | 61);\n return ((valore ^ valore >>> 14) >>> 0) / DIVISORE_UINT32;\n };\n}\n\n// src/handshake.ts\nfunction record(valore) {\n return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;\n}\nfunction eTipo(valore, tipo) {\n return record(valore)?.type === tipo;\n}\nfunction leggiOrigine(valore) {\n if (typeof valore !== "string") return null;\n try {\n const url = new URL(valore);\n return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;\n } catch {\n return null;\n }\n}\nfunction attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {\n return new Promise((resolve) => {\n let concluso = false;\n const termina = (esito) => {\n if (concluso) return;\n concluso = true;\n finestra.removeEventListener("message", ascolta);\n finestra.clearTimeout(scadenza);\n resolve(esito);\n };\n const segnalaPronto = () => {\n finestra.parent.postMessage({ type: "caisual:ready" }, appOrigin);\n };\n const ascolta = (evento) => {\n if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;\n if (eTipo(evento.data, "caisual:ready?")) {\n segnalaPronto();\n return;\n }\n if (!eTipo(evento.data, "caisual:hello")) return;\n const dati = record(evento.data);\n const porta = evento.ports[0];\n if (typeof dati?.ticket !== "string" || porta === void 0) return;\n porta.start();\n termina({\n ticket: dati.ticket,\n live: leggiOrigine(dati.live),\n invite: typeof dati.invite === "string" ? dati.invite : null,\n porta\n });\n };\n finestra.addEventListener("message", ascolta);\n const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);\n segnalaPronto();\n });\n}\nfunction scadenzaJwt(ticket) {\n const parte = ticket.split(".")[1];\n if (parte === void 0) return null;\n const base64 = parte.replace(/-/g, "+").replace(/_/g, "/").padEnd(\n Math.ceil(parte.length / 4) * 4,\n "="\n );\n try {\n const payload = record(JSON.parse(globalThis.atob(base64)));\n return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;\n } catch {\n return null;\n }\n}\nfunction chiediBiglietto(porta, finestra, timeoutMs, aud) {\n return new Promise((resolve, reject) => {\n let concluso = false;\n const termina = (ticket) => {\n if (concluso) return;\n concluso = true;\n porta.removeEventListener("message", ascolta);\n finestra.clearTimeout(scadenza);\n if (ticket === null) reject(new Error("Ticket refresh timed out."));\n else resolve(ticket);\n };\n const ascolta = (evento) => {\n const dati = record(evento.data);\n const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;\n if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {\n termina(dati.ticket);\n }\n };\n porta.addEventListener("message", ascolta);\n const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);\n try {\n porta.postMessage(aud === "live" ? { type: "caisual:ticket", aud: "live" } : { type: "caisual:ticket" });\n } catch {\n termina(null);\n }\n });\n}\nfunction creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3, aud = "portal") {\n let ticket = ticketIniziale;\n let rinnovo = null;\n const rinnova = () => {\n if (rinnovo !== null) return rinnovo;\n const richiesta = chiediBiglietto(porta, finestra, timeoutMs, aud).then((nuovo) => {\n ticket = nuovo;\n return nuovo;\n });\n const completa = richiesta.finally(() => {\n if (rinnovo === completa) rinnovo = null;\n });\n rinnovo = completa;\n return completa;\n };\n return {\n async ottieni() {\n if (ticket === null) return rinnova();\n const scadenza = scadenzaJwt(ticket);\n return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;\n },\n rinnova\n };\n}\n\n// src/voce/index.ts\nvar SOGLIA_AUDIO = 0.02;\nvar DURATA_PARLANTE = 300;\nvar INTERVALLO_AUDIO = 200;\nvar DURATA_ZERO = 3e3;\nvar TIMEOUT_CONNESSIONE = 1e4;\nvar RITARDI_RICONNESSIONE = [1e3, 2e3, 4e3];\nfunction limita(value) {\n return Number.isNaN(value) ? 1 : Math.min(1, Math.max(0, value));\n}\nfunction dipendenzeReali(input) {\n const globali = globalThis;\n const AudioContextClass = globali.AudioContext ?? globali.webkitAudioContext;\n if (typeof RTCPeerConnection === "undefined" || typeof MediaStream === "undefined" || AudioContextClass === void 0 || typeof navigator === "undefined" || navigator.mediaDevices?.getUserMedia === void 0 || typeof document === "undefined") return null;\n return {\n ...input,\n creaPeerConnection: (configuration) => new RTCPeerConnection(configuration),\n getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),\n creaAudioContext: () => new AudioContextClass(),\n creaAudioElement: () => document.createElement("audio"),\n creaMediaStream: (tracks) => new MediaStream(tracks)\n };\n}\nvar VoceClient = class {\n constructor(contesto, timer, dipendenze) {\n this.contesto = contesto;\n this.modeCorrente = "none";\n this.stateCorrente = "off";\n this.mutedCorrente = false;\n this.speakingCorrente = false;\n this.roster = [];\n this.gains = /* @__PURE__ */ new Map();\n this.volumi = /* @__PURE__ */ new Map();\n this.speakingPeers = /* @__PURE__ */ new Map();\n this.ultimoAudio = /* @__PURE__ */ new Map();\n this.zeroDa = /* @__PURE__ */ new Map();\n this.timerZero = /* @__PURE__ */ new Map();\n this.ascoltatoriPeers = /* @__PURE__ */ new Set();\n this.ascoltatoriState = /* @__PURE__ */ new Set();\n this.richieste = /* @__PURE__ */ new Map();\n this.riproduzioni = /* @__PURE__ */ new Map();\n this.sfuAttive = /* @__PURE__ */ new Map();\n this.midGiocatori = /* @__PURE__ */ new Map();\n this.mesh = /* @__PURE__ */ new Map();\n this.stream = null;\n this.mic = null;\n this.audioContext = null;\n this.analyser = null;\n this.peerSfu = null;\n this.sessioneSfu = null;\n this.trasporto = null;\n this.intervalloAudio = null;\n this.timerConnessione = null;\n this.cancellaAttesaConnessione = null;\n this.timerRiconnessione = null;\n this.ultimoAudioMic = Number.NEGATIVE_INFINITY;\n this.sequenzaRichieste = 0;\n this.generazione = 0;\n this.tentativoRiconnessione = 0;\n this.desiderata = false;\n this.promessaIngresso = null;\n this.negoziazione = Promise.resolve();\n this.dipendenze = dipendenze ?? dipendenzeReali(timer);\n }\n get mode() {\n return this.modeCorrente;\n }\n get state() {\n return this.stateCorrente;\n }\n get muted() {\n return this.mutedCorrente;\n }\n get speaking() {\n return this.speakingCorrente;\n }\n get peers() {\n return this.copiaPeers();\n }\n async join() {\n if (this.stateCorrente === "on") return;\n if (this.stateCorrente === "joining") {\n if (this.promessaIngresso !== null) await this.promessaIngresso;\n return;\n }\n if (this.stateCorrente === "reconnecting" && this.desiderata) return;\n this.verificaIngresso();\n this.desiderata = true;\n this.tentativoRiconnessione = 0;\n this.aggiornaState("joining");\n const generazione = ++this.generazione;\n const promessa = this.completaIngresso(generazione);\n this.promessaIngresso = promessa;\n try {\n await promessa;\n } finally {\n if (this.promessaIngresso === promessa) this.promessaIngresso = null;\n }\n }\n async completaIngresso(generazione) {\n try {\n await this.entra(generazione);\n } catch (cause) {\n if (generazione !== this.generazione) return;\n this.desiderata = false;\n this.chiudiRisorse();\n this.aggiornaState("off");\n throw this.mappaErrore(cause);\n }\n }\n leave() {\n const deveFermare = this.desiderata || this.stateCorrente !== "off";\n this.desiderata = false;\n this.generazione++;\n this.fermaRiconnessione();\n if (deveFermare && this.contesto.connessa()) {\n void this.richiedi({ t: "voice", op: "stop" }).catch(() => void 0);\n }\n this.rifiutaRichieste(creaErrore("offline", "Voice has stopped."));\n this.chiudiRisorse();\n this.aggiornaState("off");\n }\n mute(muted = true) {\n if (this.stateCorrente !== "on" || this.mic === null) {\n throw creaErrore("not_publishing", "Join voice before changing mute.");\n }\n this.mutedCorrente = muted;\n this.mic.enabled = !muted;\n void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);\n }\n setVolume(playerId, volume) {\n const valore = limita(volume);\n this.volumi.set(playerId, valore);\n this.aggiornaGuadagno(playerId);\n this.notificaPeers();\n }\n onPeers(listener) {\n this.ascoltatoriPeers.add(listener);\n return () => {\n this.ascoltatoriPeers.delete(listener);\n };\n }\n onState(listener) {\n this.ascoltatoriState.add(listener);\n return () => {\n this.ascoltatoriState.delete(listener);\n };\n }\n ricevi(message) {\n if ("r" in message) {\n const pending = this.richieste.get(message.r);\n if (pending !== void 0) {\n this.richieste.delete(message.r);\n if ("error" in message) {\n pending.reject(creaErrore(message.error.code, message.error.message));\n } else pending.resolve(message);\n }\n return;\n }\n if (message.op === "roster") {\n this.modeCorrente = message.mode;\n this.roster = message.peers.map((peer) => ({ ...peer }));\n for (const peer of this.roster) {\n if (peer.muted) this.speakingPeers.set(peer.id, false);\n }\n this.pulisciPeerAssenti();\n this.contesto.rosterPronto();\n this.notificaPeers();\n this.accodaRiconciliazione();\n return;\n }\n if (message.op === "gain") {\n for (const [playerId, gain] of Object.entries(message.gains)) {\n this.gains.set(playerId, limita(gain));\n this.aggiornaZero(playerId);\n this.aggiornaGuadagno(playerId);\n }\n this.notificaPeers();\n this.accodaRiconciliazione();\n return;\n }\n if (message.op === "signal") void this.riceviSegnale(message.from, message.data);\n }\n giocatoriCambiati() {\n const presenti = new Set(this.contesto.giocatori().map((player) => player.id));\n for (const playerId of this.gains.keys()) {\n if (presenti.has(playerId)) continue;\n this.gains.delete(playerId);\n this.zeroDa.delete(playerId);\n const timer = this.timerZero.get(playerId);\n if (timer !== void 0) this.dipendenze?.clearTimeout(timer);\n this.timerZero.delete(playerId);\n this.aggiornaGuadagno(playerId);\n }\n this.notificaPeers();\n this.accodaRiconciliazione();\n }\n socketDisconnesso() {\n this.sequenzaRichieste = 0;\n this.rifiutaRichieste(creaErrore("offline", "The room is reconnecting."));\n if (!this.desiderata) return;\n this.generazione++;\n this.chiudiRisorse();\n this.tentativoRiconnessione = 0;\n this.aggiornaState("reconnecting");\n }\n socketRiconnesso() {\n this.sequenzaRichieste = 0;\n if (this.desiderata && this.stateCorrente === "reconnecting") this.programmaRiconnessione();\n }\n termina() {\n this.desiderata = false;\n this.generazione++;\n this.fermaRiconnessione();\n this.rifiutaRichieste(creaErrore("offline", "The room connection ended."));\n this.chiudiRisorse();\n this.aggiornaState("off");\n }\n verificaIngresso() {\n if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");\n if (this.modeCorrente === "none") {\n throw creaErrore("voice_disabled", "Voice is disabled for this room.");\n }\n const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());\n if (you?.role === "spectator") {\n throw creaErrore("spectator", "Spectators cannot join voice.");\n }\n if (this.dipendenze === null) {\n throw creaErrore("unsupported", "Voice is not supported in this browser.");\n }\n }\n async entra(generazione) {\n this.verificaIngresso();\n const dipendenze = this.richiediDipendenze();\n const audioContext = dipendenze.creaAudioContext();\n this.audioContext = audioContext;\n try {\n await audioContext.resume();\n } catch {\n }\n let stream;\n try {\n stream = await dipendenze.getUserMedia({ audio: true });\n } catch (cause) {\n if (this.permessoNegato(cause)) {\n throw creaErrore("permission_denied", "Microphone permission was denied.");\n }\n throw creaErrore("voice_error", "The microphone could not be opened.");\n }\n try {\n this.controllaGenerazione(generazione);\n } catch (cause) {\n for (const track of stream.getTracks()) track.stop();\n throw cause;\n }\n const mic = stream.getAudioTracks()[0];\n if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");\n this.stream = stream;\n this.mic = mic;\n mic.enabled = !this.mutedCorrente;\n this.preparaAnalizzatore(stream);\n const risposta = await this.richiedi({ t: "voice", op: "ice" });\n this.controllaGenerazione(generazione);\n if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");\n this.modeCorrente = risposta.mode;\n if (risposta.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");\n this.trasporto = risposta.transport;\n if (risposta.transport === "sfu") {\n await this.entraSfu(risposta.iceServers, generazione);\n } else {\n await this.richiedi({ t: "voice", op: "publish" });\n }\n if (this.mutedCorrente) await this.richiedi({ t: "voice", op: "mute", muted: true });\n this.controllaGenerazione(generazione);\n this.tentativoRiconnessione = 0;\n this.aggiornaState("on");\n this.avviaMisuraAudio();\n for (const playerId of this.gains.keys()) this.aggiornaZero(playerId);\n this.accodaRiconciliazione();\n }\n async entraSfu(iceServers, generazione) {\n const pc = this.richiediDipendenze().creaPeerConnection({\n iceServers,\n bundlePolicy: "max-bundle"\n });\n this.peerSfu = pc;\n pc.ontrack = (event) => {\n const mid2 = event.transceiver.mid;\n const playerId = mid2 === null ? void 0 : this.midGiocatori.get(mid2);\n if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);\n };\n this.osservaCaduta(pc);\n const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n this.controllaGenerazione(generazione);\n const mid = transceiver.mid;\n const sdp = pc.localDescription?.sdp;\n if (mid === null || sdp === void 0) {\n throw creaErrore("voice_error", "The voice connection could not create an offer.");\n }\n const risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });\n if (risposta.op !== "session") {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n this.sessioneSfu = risposta.session;\n await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });\n await this.attendiConnessione(pc, generazione);\n }\n attendiConnessione(pc, generazione) {\n if (pc.connectionState === "connected") return Promise.resolve();\n const dipendenze = this.richiediDipendenze();\n return new Promise((resolve, reject) => {\n const pulisci = () => {\n pc.removeEventListener("connectionstatechange", cambiata);\n if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);\n this.timerConnessione = null;\n this.cancellaAttesaConnessione = null;\n };\n const cambiata = () => {\n if (generazione !== this.generazione) {\n pulisci();\n reject(creaErrore("offline", "Voice was stopped."));\n } else if (pc.connectionState === "connected") {\n pulisci();\n resolve();\n } else if (pc.connectionState === "failed" || pc.connectionState === "closed") {\n pulisci();\n reject(creaErrore("voice_error", "The voice connection failed."));\n }\n };\n pc.addEventListener("connectionstatechange", cambiata);\n this.cancellaAttesaConnessione = () => {\n pulisci();\n reject(creaErrore("offline", "Voice was stopped."));\n };\n this.timerConnessione = dipendenze.setTimeout(() => {\n pulisci();\n reject(creaErrore("voice_error", "The voice connection timed out."));\n }, TIMEOUT_CONNESSIONE);\n });\n }\n accodaRiconciliazione() {\n if (this.stateCorrente !== "on") return;\n this.negoziazione = this.negoziazione.then(async () => {\n if (this.stateCorrente !== "on") return;\n if (this.trasporto === "sfu") await this.riconciliaSfu();\n else if (this.trasporto === "mesh") this.riconciliaMesh();\n }).catch(() => this.avviaRiconnessione());\n }\n async riconciliaSfu() {\n const sessione = this.sessioneSfu;\n const pc = this.peerSfu;\n if (sessione === null || pc === null) return;\n const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));\n const daChiudere = [];\n for (const [playerId, attiva] of this.sfuAttive) {\n const peer = desiderati.get(playerId);\n if (peer !== void 0 && peer.session === attiva.session && peer.track === attiva.track) continue;\n daChiudere.push(attiva);\n if (!this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();\n this.sfuAttive.delete(playerId);\n this.midGiocatori.delete(attiva.mid);\n this.scollegaTraccia(playerId);\n }\n if (daChiudere.length > 0) {\n await this.richiedi({\n t: "voice",\n op: "close",\n session: sessione,\n mids: daChiudere.map((item) => item.mid)\n });\n }\n const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));\n if (nuove.length === 0) return;\n const risposta = await this.richiedi({\n t: "voice",\n op: "subscribe",\n session: sessione,\n tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))\n });\n if (risposta.op !== "subscribe") {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n for (const risultato of risposta.tracks) {\n const peer = nuove.find(\n (item) => item.session === risultato.session && item.track === risultato.track\n );\n if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;\n this.midGiocatori.set(risultato.mid, peer.id);\n this.sfuAttive.set(peer.id, {\n session: peer.session,\n track: peer.track,\n mid: risultato.mid,\n receiver: null\n });\n }\n await pc.setRemoteDescription({ type: "offer", sdp: risposta.sdp });\n const answer = await pc.createAnswer();\n await pc.setLocalDescription(answer);\n const sdp = pc.localDescription?.sdp;\n if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");\n await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });\n }\n riconciliaMesh() {\n const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));\n for (const [playerId, item] of this.mesh) {\n if (desiderati.has(playerId)) continue;\n item.pc.close();\n this.mesh.delete(playerId);\n this.scollegaTraccia(playerId);\n }\n for (const peer of desiderati.values()) {\n if (!this.mesh.has(peer.id)) this.creaMesh(peer.id);\n }\n }\n creaMesh(playerId) {\n const pc = this.richiediDipendenze().creaPeerConnection();\n const item = {\n pc,\n makingOffer: false,\n ignoreOffer: false,\n settingRemoteAnswer: false,\n polite: this.contesto.you() > playerId,\n receiver: null\n };\n this.mesh.set(playerId, item);\n pc.onicecandidate = (event) => {\n if (event.candidate === null) return;\n void this.inviaSegnale(playerId, { kind: "candidate", candidate: event.candidate.toJSON() });\n };\n if (!item.polite) pc.onnegotiationneeded = () => {\n void this.offriMesh(playerId, item);\n };\n pc.ontrack = (event) => {\n item.receiver = event.receiver;\n this.collegaTraccia(playerId, event.track, event.receiver);\n };\n this.osservaCaduta(pc);\n pc.addTrack(this.richiediMic(), this.richiediStream());\n }\n async offriMesh(playerId, item) {\n try {\n item.makingOffer = true;\n const offer = await item.pc.createOffer();\n await item.pc.setLocalDescription(offer);\n const sdp = item.pc.localDescription?.sdp;\n if (sdp !== void 0) await this.inviaSegnale(playerId, { kind: "offer", sdp });\n } finally {\n item.makingOffer = false;\n }\n }\n async riceviSegnale(from, data) {\n if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;\n if (!this.peerDesiderati().some((peer) => peer.id === from)) return;\n if (!this.mesh.has(from)) this.creaMesh(from);\n const item = this.mesh.get(from);\n if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;\n const segnale = data;\n try {\n if (segnale.kind === "candidate") {\n if (!item.ignoreOffer) await item.pc.addIceCandidate(segnale.candidate);\n return;\n }\n if (segnale.kind !== "offer" && segnale.kind !== "answer" || typeof segnale.sdp !== "string") return;\n const pronta = !item.makingOffer && (item.pc.signalingState === "stable" || item.settingRemoteAnswer);\n const collisione = segnale.kind === "offer" && !pronta;\n item.ignoreOffer = !item.polite && collisione;\n if (item.ignoreOffer) return;\n item.settingRemoteAnswer = segnale.kind === "answer";\n await item.pc.setRemoteDescription({ type: segnale.kind, sdp: segnale.sdp });\n item.settingRemoteAnswer = false;\n if (segnale.kind === "offer") {\n const answer = await item.pc.createAnswer();\n await item.pc.setLocalDescription(answer);\n const sdp = item.pc.localDescription?.sdp;\n if (sdp !== void 0) await this.inviaSegnale(from, { kind: "answer", sdp });\n }\n } catch {\n this.avviaRiconnessione();\n }\n }\n inviaSegnale(to, data) {\n return this.richiedi({ t: "voice", op: "signal", to, data });\n }\n peerDesiderati() {\n const you = this.contesto.you();\n const giocatori = this.contesto.giocatori();\n const player = giocatori.find((item) => item.id === you);\n return this.roster.filter((peer) => {\n if (peer.id === you) return false;\n if (this.modeCorrente === "team") {\n const altro = giocatori.find((item) => item.id === peer.id);\n if (player?.role !== "spectator" && altro?.team !== player?.team) return false;\n }\n const zeroAt = this.zeroDa.get(peer.id);\n return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;\n });\n }\n aggiornaZero(playerId) {\n const dipendenze = this.dipendenze;\n if (dipendenze === null) return;\n const precedente = this.timerZero.get(playerId);\n if (precedente !== void 0) dipendenze.clearTimeout(precedente);\n this.timerZero.delete(playerId);\n if ((this.gains.get(playerId) ?? 1) > 0) {\n this.zeroDa.delete(playerId);\n return;\n }\n if (!this.zeroDa.has(playerId)) this.zeroDa.set(playerId, dipendenze.ora());\n const trascorso = dipendenze.ora() - (this.zeroDa.get(playerId) ?? dipendenze.ora());\n const timer = dipendenze.setTimeout(() => {\n this.timerZero.delete(playerId);\n this.accodaRiconciliazione();\n }, Math.max(0, DURATA_ZERO - trascorso));\n this.timerZero.set(playerId, timer);\n }\n collegaTraccia(playerId, track, receiver) {\n this.scollegaTraccia(playerId);\n const dipendenze = this.richiediDipendenze();\n const media = dipendenze.creaMediaStream([track]);\n const source = this.richiediAudioContext().createMediaStreamSource(media);\n const gain = this.richiediAudioContext().createGain();\n source.connect(gain);\n gain.connect(this.richiediAudioContext().destination);\n let analyser = null;\n try {\n analyser = this.richiediAudioContext().createAnalyser();\n analyser.fftSize = 256;\n source.connect(analyser);\n } catch {\n analyser = null;\n }\n const audio = dipendenze.creaAudioElement();\n audio.srcObject = media;\n audio.muted = true;\n audio.playsInline = true;\n void audio.play().catch(() => void 0);\n this.riproduzioni.set(playerId, { source, gain, analyser, audio, track, receiver });\n const attiva = this.sfuAttive.get(playerId);\n if (attiva !== void 0) attiva.receiver = receiver;\n this.aggiornaGuadagno(playerId);\n }\n scollegaTraccia(playerId) {\n const riproduzione = this.riproduzioni.get(playerId);\n if (riproduzione === void 0) return;\n riproduzione.source.disconnect();\n riproduzione.gain.disconnect();\n riproduzione.analyser?.disconnect();\n riproduzione.track.stop();\n riproduzione.audio.pause();\n riproduzione.audio.srcObject = null;\n this.riproduzioni.delete(playerId);\n this.speakingPeers.delete(playerId);\n this.ultimoAudio.delete(playerId);\n }\n aggiornaGuadagno(playerId) {\n const riproduzione = this.riproduzioni.get(playerId);\n if (riproduzione !== void 0) {\n riproduzione.gain.gain.value = (this.volumi.get(playerId) ?? 1) * (this.gains.get(playerId) ?? 1);\n }\n }\n preparaAnalizzatore(stream) {\n const context = this.richiediAudioContext();\n const analyser = context.createAnalyser();\n analyser.fftSize = 256;\n context.createMediaStreamSource(stream).connect(analyser);\n this.analyser = analyser;\n }\n avviaMisuraAudio() {\n const dipendenze = this.richiediDipendenze();\n if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);\n this.intervalloAudio = dipendenze.setInterval(() => this.misuraAudio(), INTERVALLO_AUDIO);\n }\n misuraAudio() {\n const dipendenze = this.dipendenze;\n if (dipendenze === null) return;\n let sopraSoglia = false;\n if (this.analyser !== null) sopraSoglia = this.livelloAnalizzatore(this.analyser) > SOGLIA_AUDIO;\n if (sopraSoglia) this.ultimoAudioMic = dipendenze.ora();\n const parlando = !this.mutedCorrente && dipendenze.ora() - this.ultimoAudioMic <= DURATA_PARLANTE;\n if (parlando !== this.speakingCorrente) {\n this.speakingCorrente = parlando;\n this.notificaPeers();\n }\n let cambiato = false;\n for (const peer of this.copiaPeers()) {\n const riproduzione = this.riproduzioni.get(peer.id);\n if (this.livelloAnalizzatore(riproduzione?.analyser ?? null) > SOGLIA_AUDIO) {\n this.ultimoAudio.set(peer.id, dipendenze.ora());\n } else if (riproduzione?.analyser === null || riproduzione?.analyser === void 0) {\n const sources = riproduzione?.receiver?.getSynchronizationSources?.() ?? [];\n if (sources.some((source) => (source.audioLevel ?? 0) > SOGLIA_AUDIO)) {\n this.ultimoAudio.set(peer.id, dipendenze.ora());\n }\n }\n const speaking = !peer.muted && dipendenze.ora() - (this.ultimoAudio.get(peer.id) ?? 0) <= DURATA_PARLANTE;\n if ((this.speakingPeers.get(peer.id) ?? false) !== speaking) {\n this.speakingPeers.set(peer.id, speaking);\n cambiato = true;\n }\n }\n if (cambiato) this.notificaPeers();\n }\n livelloAnalizzatore(analyser) {\n const nodo = analyser;\n if (nodo?.getFloatTimeDomainData === void 0) return 0;\n const campioni = new Float32Array(nodo.fftSize);\n nodo.getFloatTimeDomainData(campioni);\n return Math.sqrt(campioni.reduce((somma, valore) => somma + valore * valore, 0) / Math.max(1, campioni.length));\n }\n copiaPeers() {\n const you = this.contesto.you();\n const giocatori = this.contesto.giocatori();\n const player = giocatori.find((item) => item.id === you);\n return this.roster.flatMap((peer) => {\n if (peer.id === you) return [];\n if (this.modeCorrente === "team") {\n const altro = giocatori.find((item) => item.id === peer.id);\n if (player?.role !== "spectator" && altro?.team !== player?.team) return [];\n }\n return [{\n id: peer.id,\n muted: peer.muted,\n speaking: !peer.muted && (this.speakingPeers.get(peer.id) ?? false),\n volume: this.volumi.get(peer.id) ?? 1,\n gain: this.gains.get(peer.id) ?? 1\n }];\n });\n }\n pulisciPeerAssenti() {\n const presenti = new Set(this.roster.map((peer) => peer.id));\n for (const playerId of this.speakingPeers.keys()) {\n if (!presenti.has(playerId)) this.speakingPeers.delete(playerId);\n }\n for (const playerId of this.zeroDa.keys()) {\n if (presenti.has(playerId)) continue;\n this.zeroDa.delete(playerId);\n const timer = this.timerZero.get(playerId);\n if (timer !== void 0) this.dipendenze?.clearTimeout(timer);\n this.timerZero.delete(playerId);\n }\n }\n osservaCaduta(pc) {\n pc.addEventListener("connectionstatechange", () => {\n if (this.stateCorrente === "on" && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) this.avviaRiconnessione();\n });\n }\n avviaRiconnessione() {\n if (!this.desiderata || this.stateCorrente === "reconnecting") return;\n this.generazione++;\n this.rifiutaRichieste(creaErrore("voice_error", "The voice connection was restarted."));\n this.chiudiRisorse();\n this.tentativoRiconnessione = 0;\n this.aggiornaState("reconnecting");\n this.programmaRiconnessione();\n }\n programmaRiconnessione() {\n if (!this.desiderata || !this.contesto.connessa() || this.timerRiconnessione !== null || this.stateCorrente !== "reconnecting") return;\n const ritardo = RITARDI_RICONNESSIONE[this.tentativoRiconnessione];\n if (ritardo === void 0) {\n this.desiderata = false;\n this.aggiornaState("off");\n return;\n }\n this.tentativoRiconnessione++;\n this.timerRiconnessione = this.richiediDipendenze().setTimeout(() => {\n this.timerRiconnessione = null;\n const generazione = ++this.generazione;\n void this.entra(generazione).catch(() => {\n if (generazione !== this.generazione || !this.desiderata) return;\n this.chiudiRisorse();\n this.aggiornaState("reconnecting");\n this.programmaRiconnessione();\n });\n }, ritardo);\n }\n fermaRiconnessione() {\n if (this.timerRiconnessione === null || this.dipendenze === null) return;\n this.dipendenze.clearTimeout(this.timerRiconnessione);\n this.timerRiconnessione = null;\n }\n chiudiRisorse() {\n const dipendenze = this.dipendenze;\n this.cancellaAttesaConnessione?.();\n this.cancellaAttesaConnessione = null;\n if (dipendenze !== null) {\n if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);\n if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);\n for (const timer of this.timerZero.values()) dipendenze.clearTimeout(timer);\n }\n this.intervalloAudio = null;\n this.timerConnessione = null;\n this.timerZero.clear();\n for (const playerId of [...this.riproduzioni.keys()]) this.scollegaTraccia(playerId);\n this.peerSfu?.close();\n this.peerSfu = null;\n for (const item of this.mesh.values()) item.pc.close();\n this.mesh.clear();\n this.sfuAttive.clear();\n this.midGiocatori.clear();\n for (const track of this.stream?.getTracks() ?? []) track.stop();\n this.stream = null;\n this.mic = null;\n this.analyser = null;\n void this.audioContext?.close().catch(() => void 0);\n this.audioContext = null;\n this.sessioneSfu = null;\n this.trasporto = null;\n this.speakingCorrente = false;\n this.ultimoAudioMic = Number.NEGATIVE_INFINITY;\n this.speakingPeers.clear();\n this.ultimoAudio.clear();\n this.negoziazione = Promise.resolve();\n }\n richiedi(message) {\n if (!this.contesto.connessa()) return Promise.reject(creaErrore("offline", "The room is reconnecting."));\n const r = ++this.sequenzaRichieste;\n return new Promise((resolve, reject) => {\n this.richieste.set(r, { resolve, reject });\n try {\n this.contesto.invia({ ...message, r });\n } catch (cause) {\n this.richieste.delete(r);\n reject(cause);\n }\n });\n }\n rifiutaRichieste(reason) {\n for (const richiesta of this.richieste.values()) richiesta.reject(reason);\n this.richieste.clear();\n }\n aggiornaState(state) {\n if (state === this.stateCorrente) return;\n this.stateCorrente = state;\n for (const listener of this.ascoltatoriState) {\n try {\n listener(state);\n } catch {\n }\n }\n }\n notificaPeers() {\n const peers = this.copiaPeers();\n for (const listener of this.ascoltatoriPeers) {\n try {\n listener(peers);\n } catch {\n }\n }\n }\n controllaGenerazione(generazione) {\n if (generazione !== this.generazione || !this.desiderata) {\n throw creaErrore("offline", "Voice was stopped.");\n }\n }\n richiediDipendenze() {\n if (this.dipendenze === null) throw creaErrore("unsupported", "Voice is not supported.");\n return this.dipendenze;\n }\n richiediMic() {\n if (this.mic === null) throw creaErrore("voice_error", "The microphone is not ready.");\n return this.mic;\n }\n richiediStream() {\n if (this.stream === null) throw creaErrore("voice_error", "The microphone is not ready.");\n return this.stream;\n }\n richiediAudioContext() {\n if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");\n return this.audioContext;\n }\n permessoNegato(cause) {\n return typeof cause === "object" && cause !== null && "name" in cause && (cause.name === "NotAllowedError" || cause.name === "SecurityError");\n }\n mappaErrore(cause) {\n if (typeof cause === "object" && cause !== null && "code" in cause) {\n const code = cause.code;\n if (code === "voice_disabled" || code === "permission_denied" || code === "unsupported" || code === "spectator" || code === "offline" || code === "voice_error") return cause;\n return creaErrore("voice_error", "Voice could not be started.");\n }\n return creaErrore("voice_error", "Voice could not be started.");\n }\n};\n\n// src/stanza-client/index.ts\nvar APERTO = 1;\nvar RITARDI_RICONNESSIONE2 = [1e3, 2e3, 4e3, 8e3];\nvar GRAZIA_RICONNESSIONE = 6e4;\nvar INTERVALLO_PING = 5e3;\nvar RITARDO_FLUSH = 500;\nvar ATTESA_ROSTER = 2e3;\nvar CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);\nfunction record2(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;\n}\nfunction copiaJson(value) {\n return JSON.parse(JSON.stringify(value));\n}\nfunction applicaPatch(state, value) {\n let risultato = copiaJson(state);\n for (const operazione of value) {\n if (operazione.path.length === 0) {\n if (operazione.op !== "set") return { ok: false };\n risultato = copiaJson(operazione.value);\n continue;\n }\n let contenitore = risultato;\n const percorso = operazione.path;\n for (let indice = 0; indice < percorso.length - 1; indice++) {\n const parte = percorso[indice];\n if (Array.isArray(contenitore)) {\n if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };\n contenitore = contenitore[parte];\n } else {\n const oggetto = record2(contenitore);\n if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {\n return { ok: false };\n }\n contenitore = oggetto[parte];\n }\n }\n const ultima = percorso.at(-1);\n if (Array.isArray(contenitore)) {\n if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };\n contenitore[ultima] = copiaJson(operazione.value);\n } else {\n const oggetto = record2(contenitore);\n if (oggetto === null || typeof ultima !== "string") return { ok: false };\n if (operazione.op === "del") {\n if (!Object.hasOwn(oggetto, ultima)) return { ok: false };\n delete oggetto[ultima];\n } else {\n Object.defineProperty(oggetto, ultima, {\n configurable: true,\n enumerable: true,\n value: copiaJson(operazione.value),\n writable: true\n });\n }\n }\n }\n return { ok: true, state: risultato };\n}\nfunction creaApiLive(input) {\n const richiesta = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);\n function ingressoValido(value) {\n const dati = record2(value);\n return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";\n }\n async function ingresso(path, body, rinnova = false) {\n const value = await richiesta(path, "POST", body, rinnova);\n if (!ingressoValido(value)) {\n throw creaErrore("internal_error", "The room service returned an invalid response.");\n }\n return value;\n }\n return {\n create: (mode) => ingresso("/rooms", { mode }),\n joinCode: (code) => ingresso("/rooms/join", { code }),\n joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),\n flush: (roomId) => richiesta(\n `/rooms/${encodeURIComponent(roomId)}/flush`,\n "POST"\n )\n };\n}\nvar StanzaClient = class {\n constructor(roomId, codice, url, input, api) {\n this.roomId = roomId;\n this.codice = codice;\n this.input = input;\n this.api = api;\n this.statoPubblico = null;\n this.statoSincronizzato = null;\n this.tickCorrente = 0;\n this.statusCorrente = "lobby";\n this.giocatoriCorrenti = [];\n this.youCorrente = "";\n this.hostCorrente = null;\n this.resultCorrente = null;\n this.socket = null;\n this.seq = 0;\n this.scartoOrario = 0;\n this.timerPing = null;\n this.timerRiconnessione = null;\n this.timerFlush = null;\n this.flushInCorso = false;\n this.flushRichiesto = false;\n this.ritardoIndice = 0;\n this.tempoRiconnessione = 0;\n this.resyncRichiesto = false;\n this.terminata = false;\n this.lasciata = false;\n this.prontaRisolta = false;\n this.welcomeRicevuto = false;\n this.rosterRicevuto = false;\n this.timerRoster = null;\n this.risolviPronta = () => void 0;\n this.rifiutaPronta = () => void 0;\n this.ascoltatoriStato = /* @__PURE__ */ new Set();\n this.ascoltatoriGiocatori = /* @__PURE__ */ new Set();\n this.ascoltatoriStatus = /* @__PURE__ */ new Set();\n this.ascoltatoriMessaggi = /* @__PURE__ */ new Set();\n this.promessaPronta = new Promise((resolve, reject) => {\n this.risolviPronta = resolve;\n this.rifiutaPronta = reject;\n });\n this.voice = new VoceClient({\n invia: (message) => this.invia(message),\n connessa: () => this.socket?.readyState === APERTO && this.welcomeRicevuto && !this.terminata && !this.lasciata,\n you: () => this.youCorrente,\n giocatori: () => this.copiaGiocatori(),\n rosterPronto: () => {\n this.rosterRicevuto = true;\n this.risolviProntaSePossibile();\n }\n }, input, input.voce);\n this.apri(url);\n }\n get state() {\n return this.statoPubblico;\n }\n get tick() {\n return this.tickCorrente;\n }\n get status() {\n return this.statusCorrente;\n }\n get players() {\n return this.copiaGiocatori();\n }\n get you() {\n return this.youCorrente;\n }\n get host() {\n return this.hostCorrente;\n }\n get code() {\n return this.codice;\n }\n get result() {\n return this.resultCorrente;\n }\n pronta() {\n return this.promessaPronta;\n }\n invite() {\n return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };\n }\n onState(listener) {\n this.ascoltatoriStato.add(listener);\n return () => {\n this.ascoltatoriStato.delete(listener);\n };\n }\n onPlayers(listener) {\n this.ascoltatoriGiocatori.add(listener);\n return () => {\n this.ascoltatoriGiocatori.delete(listener);\n };\n }\n onStatus(listener) {\n this.ascoltatoriStatus.add(listener);\n return () => {\n this.ascoltatoriStatus.delete(listener);\n };\n }\n onMessage(listener) {\n this.ascoltatoriMessaggi.add(listener);\n return () => {\n this.ascoltatoriMessaggi.delete(listener);\n };\n }\n send(message) {\n const prossimo = this.seq + 1;\n this.invia({ t: "msg", seq: prossimo, m: message });\n this.seq = prossimo;\n }\n ready(ready) {\n this.invia({ t: "ready", ready });\n }\n setRole(role) {\n this.invia({ t: "role", role });\n }\n setTeam(team) {\n this.invia({ t: "team", team });\n }\n start() {\n this.invia({ t: "start" });\n }\n leave() {\n if (this.lasciata) return;\n this.voice.leave();\n this.lasciata = true;\n if (this.socket?.readyState === APERTO) this.invia({ t: "leave" });\n this.termina(1e3);\n }\n serverTime() {\n return this.input.ora() + this.scartoOrario;\n }\n copiaGiocatori() {\n return this.giocatoriCorrenti.map((player) => ({ ...player }));\n }\n notifica(listeners, ...args) {\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch {\n }\n }\n }\n invia(message) {\n if (this.socket?.readyState !== APERTO) {\n throw creaErrore("offline", "The room is reconnecting.");\n }\n let frame;\n try {\n frame = JSON.stringify(message);\n } catch {\n throw creaErrore("invalid_request", "Room messages must be valid JSON.");\n }\n this.socket.send(frame);\n }\n apri(url) {\n let socket;\n try {\n socket = this.input.apriSocket(url);\n } catch {\n this.programmaRiconnessione();\n return;\n }\n this.socket = socket;\n socket.addEventListener("open", () => {\n if (this.socket === socket) this.avviaPing();\n });\n socket.addEventListener("message", (evento) => {\n if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);\n });\n socket.addEventListener("close", (evento) => {\n if (this.socket === socket) this.chiuso(evento.code);\n });\n }\n avviaPing() {\n if (this.timerPing !== null) this.input.clearInterval(this.timerPing);\n this.timerPing = this.input.setInterval(() => {\n if (this.socket?.readyState !== APERTO) return;\n try {\n this.invia({ t: "ping", c: this.input.ora() });\n } catch {\n }\n }, INTERVALLO_PING);\n }\n fermaPing() {\n if (this.timerPing === null) return;\n this.input.clearInterval(this.timerPing);\n this.timerPing = null;\n }\n ricevi(frame) {\n let dati;\n try {\n const value = JSON.parse(frame);\n const oggetto = record2(value);\n if (oggetto === null || typeof oggetto.t !== "string") return;\n dati = oggetto;\n } catch {\n return;\n }\n try {\n if (dati.t === "welcome") this.riceviWelcome(dati);\n else if (dati.t === "players") this.riceviGiocatori(dati.players);\n else if (dati.t === "status") this.riceviStatus(dati);\n else if (dati.t === "state") this.riceviDiff(dati);\n else if (dati.t === "snapshot") this.riceviSnapshot(dati);\n else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));\n else if (dati.t === "pong") this.riceviPong(dati);\n else if (dati.t === "flush") this.richiediFlush();\n else if (dati.t === "voice") this.voice.ricevi(dati);\n } catch {\n if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();\n }\n }\n riceviWelcome(dati) {\n const room = dati.room;\n if (room.id !== this.roomId) return;\n this.youCorrente = dati.you;\n this.hostCorrente = room.host;\n this.statusCorrente = room.status;\n this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));\n this.aggiornaStato(dati.state, room.tick, room.serverTime);\n this.scartoOrario = room.serverTime - this.input.ora();\n this.resyncRichiesto = false;\n this.welcomeRicevuto = true;\n if (!this.rosterRicevuto && this.timerRoster === null) {\n this.timerRoster = this.input.setTimeout(() => {\n this.timerRoster = null;\n this.rosterRicevuto = true;\n this.risolviProntaSePossibile();\n }, ATTESA_ROSTER);\n }\n this.ritardoIndice = 0;\n this.tempoRiconnessione = 0;\n this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());\n this.voice.giocatoriCambiati();\n this.voice.socketRiconnesso();\n this.notifica(\n this.ascoltatoriStatus,\n this.statusCorrente,\n this.resultCorrente,\n room.serverTime\n );\n this.risolviProntaSePossibile();\n }\n riceviGiocatori(value) {\n this.giocatoriCorrenti = value.map((player) => ({ ...player }));\n if (!this.giocatoriCorrenti.some(\n (player) => player.id === this.hostCorrente && player.connected\n )) {\n this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;\n }\n this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());\n this.voice.giocatoriCambiati();\n }\n riceviStatus(dati) {\n this.statusCorrente = dati.status;\n this.resultCorrente = copiaJson(dati.result);\n if (dati.status === "ended") {\n this.terminata = true;\n this.voice.termina();\n this.fermaPing();\n this.fermaRiconnessione();\n }\n this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);\n }\n riceviDiff(dati) {\n if (dati.base !== this.tickCorrente) {\n this.chiediResync();\n return;\n }\n const risultato = applicaPatch(this.statoSincronizzato, dati.patch);\n if (!risultato.ok) {\n this.chiediResync();\n return;\n }\n this.resyncRichiesto = false;\n this.aggiornaStato(risultato.state, dati.tick, dati.serverTime);\n }\n riceviSnapshot(dati) {\n if (dati.tick < this.tickCorrente) return;\n this.resyncRichiesto = false;\n this.aggiornaStato(dati.state, dati.tick, dati.serverTime);\n }\n aggiornaStato(state, tick, serverTime) {\n this.statoSincronizzato = copiaJson(state);\n this.statoPubblico = copiaJson(state);\n this.tickCorrente = tick;\n this.notifica(this.ascoltatoriStato, this.statoPubblico, tick, serverTime);\n }\n chiediResync() {\n if (this.resyncRichiesto || this.socket?.readyState !== APERTO) return;\n this.resyncRichiesto = true;\n try {\n this.invia({ t: "resync" });\n } catch {\n this.resyncRichiesto = false;\n }\n }\n riceviPong(dati) {\n this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;\n }\n chiuso(code) {\n this.socket = null;\n this.welcomeRicevuto = false;\n this.fermaPing();\n if (CHIUSURE_DEFINITIVE.has(code)) {\n this.termina(code);\n return;\n }\n if (this.lasciata || this.terminata) return;\n this.voice.socketDisconnesso();\n this.programmaRiconnessione();\n }\n programmaRiconnessione() {\n if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;\n const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);\n const ritardo = RITARDI_RICONNESSIONE2[indice];\n if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {\n this.termina("timeout");\n return;\n }\n this.ritardoIndice++;\n this.tempoRiconnessione += ritardo;\n this.timerRiconnessione = this.input.setTimeout(() => {\n this.timerRiconnessione = null;\n void this.riconnetti();\n }, ritardo);\n }\n async riconnetti() {\n if (this.terminata || this.lasciata) return;\n try {\n const ingresso = await this.api.joinRoom(this.roomId);\n this.codice = ingresso.code;\n this.apri(ingresso.url);\n } catch {\n this.programmaRiconnessione();\n }\n }\n fermaRiconnessione() {\n if (this.timerRiconnessione === null) return;\n this.input.clearTimeout(this.timerRiconnessione);\n this.timerRiconnessione = null;\n }\n termina(code) {\n const risultato = { closed: code };\n const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);\n this.terminata = true;\n this.statusCorrente = "ended";\n this.resultCorrente = risultato;\n this.voice.termina();\n this.fermaPing();\n this.fermaRiconnessione();\n if (cambiato) this.notifica(this.ascoltatoriStatus, "ended", risultato, this.serverTime());\n if (!this.prontaRisolta) {\n this.prontaRisolta = true;\n const codici = {\n 4003: "kicked",\n 4004: "room_ended",\n 4005: "version_closed",\n 4006: "replaced"\n };\n const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";\n this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));\n }\n }\n risolviProntaSePossibile() {\n if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;\n if (this.timerRoster !== null) {\n this.input.clearTimeout(this.timerRoster);\n this.timerRoster = null;\n }\n this.prontaRisolta = true;\n this.risolviPronta();\n }\n richiediFlush() {\n this.flushRichiesto = true;\n if (this.flushInCorso || this.timerFlush !== null) return;\n this.timerFlush = this.input.setTimeout(() => {\n this.timerFlush = null;\n void this.eseguiFlush();\n }, RITARDO_FLUSH);\n }\n async eseguiFlush() {\n if (this.flushInCorso || !this.flushRichiesto) return;\n this.flushInCorso = true;\n this.flushRichiesto = false;\n try {\n await this.api.flush(this.roomId);\n } catch {\n } finally {\n this.flushInCorso = false;\n if (this.flushRichiesto) this.richiediFlush();\n }\n }\n};\nfunction creaStanzeOffline(invited = null) {\n return {\n invited,\n async create() {\n throw erroreOffline();\n },\n async join() {\n throw erroreOffline();\n }\n };\n}\nfunction creaGestoreStanze(input, invited) {\n const api = creaApiLive(input);\n const collega = async (ingresso) => {\n const stanza = new StanzaClient(ingresso.roomId, ingresso.code, ingresso.url, input, api);\n await stanza.pronta();\n return stanza;\n };\n return {\n invited,\n async create(options) {\n return collega(await api.create(options.mode));\n },\n async join(code) {\n const scelto = code ?? invited;\n if (scelto === null || scelto === void 0 || scelto.length === 0) {\n throw creaErrore("invalid_request", "A room invitation code is required.");\n }\n return collega(await api.joinCode(scelto));\n }\n };\n}\n\n// src/standalone.ts\nvar PREFISSO = "caisual:save:";\nvar CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;\nfunction verificaChiave(key) {\n if (!CHIAVE_VALIDA.test(key)) {\n throw creaErrore("invalid_request", "Save keys must use lowercase letters, numbers, underscores, or hyphens.");\n }\n}\nfunction leggiSalvataggio(testo) {\n if (testo === null) return null;\n try {\n return JSON.parse(testo);\n } catch {\n return null;\n }\n}\nfunction chiavi(archivio) {\n const risultato = [];\n for (let indice = 0; indice < archivio.length; indice++) {\n const key = archivio.key(indice);\n if (key?.startsWith(PREFISSO)) risultato.push(key.slice(PREFISSO.length));\n }\n return risultato;\n}\nfunction creaSave(archivio, ora) {\n const disponibile = () => {\n if (archivio === null) throw erroreOffline();\n return archivio;\n };\n return {\n async set(key, value) {\n verificaChiave(key);\n const locale = disponibile();\n const corpo = JSON.stringify({ value });\n const bytes = new TextEncoder().encode(corpo).byteLength;\n if (bytes > 262144) {\n throw creaErrore("payload_too_large", "The save is larger than 262144 bytes.");\n }\n if (locale.getItem(PREFISSO + key) === null && chiavi(locale).length >= 32) {\n throw creaErrore("save_limit", "A game can store at most 32 save keys.");\n }\n const voce = { value, bytes, updatedAt: ora() };\n locale.setItem(PREFISSO + key, JSON.stringify(voce));\n return { key, bytes, updatedAt: voce.updatedAt };\n },\n async get(key) {\n verificaChiave(key);\n return leggiSalvataggio(disponibile().getItem(PREFISSO + key))?.value ?? null;\n },\n async remove(key) {\n verificaChiave(key);\n disponibile().removeItem(PREFISSO + key);\n },\n async list() {\n const locale = disponibile();\n return chiavi(locale).flatMap((key) => {\n const voce = leggiSalvataggio(locale.getItem(PREFISSO + key));\n return voce === null ? [] : [{ key, bytes: voce.bytes, updatedAt: voce.updatedAt }];\n }).sort((a, b) => a.key.localeCompare(b.key));\n }\n };\n}\nasync function creaStandalone(input, invited = null) {\n const day = giornoUtc(input.ora());\n const seed = await calcolaSeed(input.hostname, day, input.subtle);\n return {\n connected: false,\n player: { id: "local", name: "Guest", guest: true },\n daily: { day, seed, random: creaMulberry32(seed) },\n time: { now: input.ora },\n save: creaSave(input.archivio, input.ora),\n board: {\n async submit() {\n return { accepted: false, reason: "offline" };\n },\n async top(_board, opzioni = {}) {\n return { day: opzioni.daily ? day : null, entries: [], me: null };\n }\n },\n room: creaStanzeOffline(invited)\n };\n}\n\n// src/kit.ts\nfunction leggiAppOrigin(documento) {\n const valore = documento?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");\n if (valore === null || valore === void 0) return null;\n try {\n const url = new URL(valore);\n return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;\n } catch {\n return null;\n }\n}\nfunction archivioReale() {\n try {\n return typeof localStorage === "undefined" ? null : localStorage;\n } catch {\n return null;\n }\n}\nfunction dipendenzeReali2() {\n return {\n finestra: typeof window === "undefined" ? null : window,\n documento: typeof document === "undefined" ? null : document,\n fetcher: (input, init) => globalThis.fetch(input, init),\n archivio: archivioReale(),\n hostname: typeof location === "undefined" ? "" : location.hostname,\n subtle: globalThis.crypto.subtle,\n ora: Date.now\n };\n}\nasync function connetti(input) {\n const appOrigin = leggiAppOrigin(input.documento);\n const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;\n if (appOrigin === null || senzaPadre) {\n return creaStandalone(input);\n }\n const handshake = await attendiHandshake(\n input.finestra,\n appOrigin,\n input.timeoutHandshake\n );\n if (handshake === null) return creaStandalone(input);\n const biglietto = creaGestoreBiglietto(\n handshake.ticket,\n handshake.porta,\n input.finestra,\n input.ora,\n input.timeoutRinnovo,\n "portal"\n );\n const api = creaClienteApi(appOrigin, input.fetcher, biglietto);\n const prima = input.ora();\n let me;\n try {\n me = await api.me();\n } catch {\n return creaStandalone(input, handshake.invite);\n }\n const dopo = input.ora();\n const scartoOrario = me.serverTime - (prima + dopo) / 2;\n const room = handshake.live === null ? creaStanzeOffline(handshake.invite) : creaGestoreStanze({\n appOrigin,\n liveOrigin: handshake.live,\n fetcher: input.fetcher,\n biglietto: creaGestoreBiglietto(\n null,\n handshake.porta,\n input.finestra,\n input.ora,\n input.timeoutRinnovo,\n "live"\n ),\n apriSocket(url) {\n if (input.apriSocket !== void 0) return input.apriSocket(url);\n if (typeof WebSocket === "undefined") throw erroreOffline();\n return new WebSocket(url);\n },\n ora: input.ora,\n setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout),\n clearTimeout: (id) => globalThis.clearTimeout(id),\n setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),\n clearInterval: (id) => globalThis.clearInterval(id),\n voce: input.voce\n }, handshake.invite);\n return {\n connected: true,\n player: me.player,\n daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },\n time: { now: () => input.ora() + scartoOrario },\n save: {\n set: (key, value) => api.saveSet(key, value),\n get: (key) => api.saveGet(key),\n remove: (key) => api.saveRemove(key),\n list: () => api.saveList()\n },\n board: {\n async submit(board, score, opzioni = {}) {\n try {\n return await api.boardSubmit(board, score, opzioni.daily === true);\n } catch (errore) {\n if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline" };\n throw errore;\n }\n },\n top: (board, opzioni = {}) => api.boardTop(board, opzioni)\n },\n room\n };\n}\nfunction creaKit(input = dipendenzeReali2()) {\n let promessa = null;\n return {\n connect() {\n promessa ?? (promessa = connetti(input));\n return promessa;\n }\n };\n}\n\n// src/index.ts\nvar caisual = creaKit();\nglobalThis.caisual = caisual;\nvar index_default = caisual;\nexport {\n caisual,\n index_default as default\n};\n');
|
|
3531
|
+
response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.4.0\n\n// ../contracts/src/slug.ts\nvar NOMI_RISERVATI = [\n "www",\n "api",\n "app",\n "play",\n "live",\n "multi",\n "cdn",\n "assets",\n "static",\n "mail",\n "mx",\n "ns1",\n "ns2",\n "autodiscover",\n "_dmarc",\n "admin",\n "login",\n "account",\n "auth",\n "pay",\n "secure",\n "support",\n "help",\n "blog",\n "status",\n "dev",\n "staging",\n "test",\n "caisual",\n "shipz"\n];\nvar RISERVATI = new Set(NOMI_RISERVATI);\n\n// ../contracts/src/device.ts\nfunction deviceTier(report) {\n if (report.gpu !== "hardware" || report.memoryMb !== null && report.memoryMb <= 2048) return "low";\n if (report.mobile || report.memoryMb !== null && report.memoryMb <= 4096 || report.cores !== null && report.cores <= 4) return "mid";\n return "high";\n}\nfunction perdiContesto(context) {\n try {\n context?.getExtension("WEBGL_lose_context")?.loseContext();\n } catch {\n }\n}\nfunction valoriSincroni(ambiente) {\n let navigator2;\n try {\n navigator2 = ambiente.navigator;\n } catch {\n navigator2 = void 0;\n }\n let memoryMb = null;\n try {\n const memory = navigator2?.deviceMemory;\n const converted = typeof memory === "number" ? memory * 1024 : NaN;\n if (Number.isFinite(converted)) memoryMb = converted;\n } catch {\n memoryMb = null;\n }\n let cores = null;\n try {\n const value = navigator2?.hardwareConcurrency;\n if (typeof value === "number" && Number.isFinite(value)) cores = value;\n } catch {\n cores = null;\n }\n let mobile = false;\n try {\n mobile = typeof navigator2?.userAgentData?.mobile === "boolean" ? navigator2.userAgentData.mobile : /Android|iPhone|iPad|iPod|Mobile/i.test(navigator2?.userAgent ?? "");\n } catch {\n mobile = false;\n }\n let isolated = false;\n try {\n isolated = ambiente.crossOriginIsolated === true;\n } catch {\n isolated = false;\n }\n return {\n webgl2: false,\n webgpu: false,\n wasm: false,\n threads: false,\n isolated,\n gpu: "none",\n memoryMb,\n cores,\n mobile\n };\n}\nasync function probeDevice(globals, timeoutMs = 1500) {\n const ambiente = globals ?? globalThis;\n const report = valoriSincroni(ambiente);\n const webgl = Promise.resolve().then(() => {\n try {\n const canvas = ambiente.document?.createElement("canvas");\n if (canvas === void 0) return;\n const hardware = canvas.getContext("webgl2", { failIfMajorPerformanceCaveat: true });\n if (hardware !== null) {\n report.webgl2 = true;\n report.gpu = "hardware";\n perdiContesto(hardware);\n return;\n }\n const software = canvas.getContext("webgl2");\n if (software !== null) {\n report.webgl2 = true;\n report.gpu = "software";\n perdiContesto(software);\n }\n } catch {\n report.webgl2 = false;\n report.gpu = "none";\n }\n });\n const webgpu = Promise.resolve().then(async () => {\n let device;\n try {\n const gpu = ambiente.navigator?.gpu;\n if (gpu === void 0) return;\n const adapter = await gpu.requestAdapter();\n if (adapter === null) return;\n device = await adapter.requestDevice();\n report.webgpu = true;\n } catch {\n report.webgpu = false;\n } finally {\n try {\n device?.destroy?.();\n } catch {\n }\n }\n });\n const wasm = Promise.resolve().then(() => {\n try {\n report.wasm = ambiente.WebAssembly?.validate(\n new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])\n ) === true;\n } catch {\n report.wasm = false;\n }\n });\n const threads = Promise.resolve().then(() => {\n try {\n if (ambiente.WebAssembly === void 0) return;\n new ambiente.WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });\n report.threads = true;\n } catch {\n report.threads = false;\n }\n });\n let timer;\n await Promise.race([\n Promise.all([webgl, webgpu, wasm, threads]),\n new Promise((resolve) => {\n timer = setTimeout(resolve, Math.max(0, timeoutMs));\n })\n ]);\n if (timer !== void 0) clearTimeout(timer);\n return { ...report, tier: deviceTier(report) };\n}\n\n// src/errors.ts\nfunction creaErrore(code, message) {\n return Object.assign(new Error(message), { name: "CaisualError", code });\n}\nfunction erroreOffline() {\n return creaErrore("offline", "Caisual services are unavailable.");\n}\nfunction codiceErrore(valore) {\n return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;\n}\n\n// src/http.ts\nasync function leggiErrore(response) {\n let corpo = {};\n try {\n corpo = await response.json();\n } catch {\n }\n return creaErrore(\n typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error",\n typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`\n );\n}\nfunction creaRichiedente(origin, prefix, fetcher, biglietto) {\n async function manda(path, metodo, ticket, corpo) {\n const headers = new Headers({ Authorization: `Bearer ${ticket}` });\n let body;\n if (corpo !== void 0) {\n headers.set("Content-Type", "application/json");\n try {\n body = JSON.stringify(corpo);\n } catch {\n throw creaErrore("invalid_request", "The value must be valid JSON.");\n }\n }\n try {\n return await fetcher(new URL(prefix + path, origin), {\n method: metodo,\n headers,\n body,\n credentials: "omit"\n });\n } catch {\n throw erroreOffline();\n }\n }\n return async function richiesta(path, metodo, corpo, forzaRinnovo = false) {\n let ticket;\n try {\n ticket = forzaRinnovo ? await biglietto.rinnova() : await biglietto.ottieni();\n } catch {\n throw erroreOffline();\n }\n let response = await manda(path, metodo, ticket, corpo);\n if (response.status === 401) {\n try {\n ticket = await biglietto.rinnova();\n } catch {\n throw erroreOffline();\n }\n response = await manda(path, metodo, ticket, corpo);\n }\n if (!response.ok) throw await leggiErrore(response);\n try {\n return await response.json();\n } catch {\n throw creaErrore("internal_error", "The service returned an invalid response.");\n }\n };\n}\n\n// src/api.ts\nfunction creaClienteApi(appOrigin, fetcher, biglietto) {\n const richiesta = creaRichiedente(appOrigin, "/api/kit", fetcher, biglietto);\n return {\n me: () => richiesta("/me", "GET"),\n saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),\n async saveGet(key) {\n try {\n return (await richiesta(`/saves/${encodeURIComponent(key)}`, "GET")).value;\n } catch (errore) {\n if (codiceErrore(errore) === "not_found") return null;\n throw errore;\n }\n },\n async saveRemove(key) {\n await richiesta(`/saves/${encodeURIComponent(key)}`, "DELETE");\n },\n async saveList() {\n return (await richiesta("/saves", "GET")).saves;\n },\n async boardSubmit(board, score, daily) {\n const risultato = await richiesta("/scores", "POST", { board, score, daily });\n return { accepted: true, best: risultato.best, rank: risultato.rank, day: risultato.day };\n },\n async boardTop(board, opzioni) {\n const query = new URLSearchParams();\n if (opzioni.daily) query.set("daily", "1");\n if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));\n if (opzioni.guests) query.set("guests", "1");\n const suffisso = query.size === 0 ? "" : `?${query.toString()}`;\n const { day, entries, me } = await richiesta(\n `/scores/${encodeURIComponent(board)}${suffisso}`,\n "GET"\n );\n return { day, entries, me };\n }\n };\n}\n\n// src/daily.ts\nvar DIVISORE_UINT32 = 4294967296;\nfunction giornoUtc(ora) {\n return new Date(ora).toISOString().slice(0, 10);\n}\nasync function calcolaSeed(gioco, giorno, subtle) {\n const dati = new TextEncoder().encode(`caisual:${gioco}:${giorno}`);\n const digest = new Uint8Array(await subtle.digest("SHA-256", dati));\n return (digest[0] ?? 0) * 16777216 + ((digest[1] ?? 0) << 16) + ((digest[2] ?? 0) << 8) + (digest[3] ?? 0) >>> 0;\n}\nfunction creaMulberry32(seed) {\n let stato = seed >>> 0;\n return () => {\n stato = stato + 1831565813 >>> 0;\n let valore = stato;\n valore = Math.imul(valore ^ valore >>> 15, valore | 1);\n valore ^= valore + Math.imul(valore ^ valore >>> 7, valore | 61);\n return ((valore ^ valore >>> 14) >>> 0) / DIVISORE_UINT32;\n };\n}\n\n// src/handshake.ts\nfunction record(valore) {\n return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;\n}\nfunction eTipo(valore, tipo) {\n return record(valore)?.type === tipo;\n}\nfunction leggiOrigine(valore) {\n if (typeof valore !== "string") return null;\n try {\n const url = new URL(valore);\n return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;\n } catch {\n return null;\n }\n}\nfunction attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {\n return new Promise((resolve) => {\n let concluso = false;\n const termina = (esito) => {\n if (concluso) return;\n concluso = true;\n finestra.removeEventListener("message", ascolta);\n finestra.clearTimeout(scadenza);\n resolve(esito);\n };\n const segnalaPronto = () => {\n finestra.parent.postMessage({ type: "caisual:ready" }, appOrigin);\n };\n const ascolta = (evento) => {\n if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;\n if (eTipo(evento.data, "caisual:ready?")) {\n segnalaPronto();\n return;\n }\n if (!eTipo(evento.data, "caisual:hello")) return;\n const dati = record(evento.data);\n const porta = evento.ports[0];\n if (typeof dati?.ticket !== "string" || porta === void 0) return;\n porta.start();\n termina({\n ticket: dati.ticket,\n live: leggiOrigine(dati.live),\n invite: typeof dati.invite === "string" ? dati.invite : null,\n porta\n });\n };\n finestra.addEventListener("message", ascolta);\n const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);\n segnalaPronto();\n });\n}\nfunction scadenzaJwt(ticket) {\n const parte = ticket.split(".")[1];\n if (parte === void 0) return null;\n const base64 = parte.replace(/-/g, "+").replace(/_/g, "/").padEnd(\n Math.ceil(parte.length / 4) * 4,\n "="\n );\n try {\n const payload = record(JSON.parse(globalThis.atob(base64)));\n return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;\n } catch {\n return null;\n }\n}\nfunction chiediBiglietto(porta, finestra, timeoutMs, aud) {\n return new Promise((resolve, reject) => {\n let concluso = false;\n const termina = (ticket) => {\n if (concluso) return;\n concluso = true;\n porta.removeEventListener("message", ascolta);\n finestra.clearTimeout(scadenza);\n if (ticket === null) reject(new Error("Ticket refresh timed out."));\n else resolve(ticket);\n };\n const ascolta = (evento) => {\n const dati = record(evento.data);\n const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;\n if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {\n termina(dati.ticket);\n }\n };\n porta.addEventListener("message", ascolta);\n const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);\n try {\n porta.postMessage(aud === "live" ? { type: "caisual:ticket", aud: "live" } : { type: "caisual:ticket" });\n } catch {\n termina(null);\n }\n });\n}\nfunction creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3, aud = "portal") {\n let ticket = ticketIniziale;\n let rinnovo = null;\n const rinnova = () => {\n if (rinnovo !== null) return rinnovo;\n const richiesta = chiediBiglietto(porta, finestra, timeoutMs, aud).then((nuovo) => {\n ticket = nuovo;\n return nuovo;\n });\n const completa = richiesta.finally(() => {\n if (rinnovo === completa) rinnovo = null;\n });\n rinnovo = completa;\n return completa;\n };\n return {\n async ottieni() {\n if (ticket === null) return rinnova();\n const scadenza = scadenzaJwt(ticket);\n return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;\n },\n rinnova\n };\n}\n\n// src/voce/index.ts\nvar SOGLIA_AUDIO = 0.02;\nvar DURATA_PARLANTE = 300;\nvar INTERVALLO_AUDIO = 200;\nvar DURATA_ZERO = 3e3;\nvar TIMEOUT_CONNESSIONE = 1e4;\nvar RITARDI_RICONNESSIONE = [1e3, 2e3, 4e3];\nfunction limita(value) {\n return Number.isNaN(value) ? 1 : Math.min(1, Math.max(0, value));\n}\nfunction dipendenzeReali(input) {\n const globali = globalThis;\n const AudioContextClass = globali.AudioContext ?? globali.webkitAudioContext;\n if (typeof RTCPeerConnection === "undefined" || typeof MediaStream === "undefined" || AudioContextClass === void 0 || typeof navigator === "undefined" || navigator.mediaDevices?.getUserMedia === void 0 || typeof document === "undefined") return null;\n return {\n ...input,\n creaPeerConnection: (configuration) => new RTCPeerConnection(configuration),\n getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),\n creaAudioContext: () => new AudioContextClass(),\n creaAudioElement: () => document.createElement("audio"),\n creaMediaStream: (tracks) => new MediaStream(tracks)\n };\n}\nvar VoceClient = class {\n constructor(contesto, timer, dipendenze) {\n this.contesto = contesto;\n this.modeCorrente = "none";\n this.stateCorrente = "off";\n this.mutedCorrente = false;\n this.speakingCorrente = false;\n this.roster = [];\n this.gains = /* @__PURE__ */ new Map();\n this.volumi = /* @__PURE__ */ new Map();\n this.speakingPeers = /* @__PURE__ */ new Map();\n this.ultimoAudio = /* @__PURE__ */ new Map();\n this.zeroDa = /* @__PURE__ */ new Map();\n this.timerZero = /* @__PURE__ */ new Map();\n this.ascoltatoriPeers = /* @__PURE__ */ new Set();\n this.ascoltatoriState = /* @__PURE__ */ new Set();\n this.richieste = /* @__PURE__ */ new Map();\n this.riproduzioni = /* @__PURE__ */ new Map();\n this.sfuAttive = /* @__PURE__ */ new Map();\n this.midGiocatori = /* @__PURE__ */ new Map();\n this.mesh = /* @__PURE__ */ new Map();\n this.stream = null;\n this.tracciaMic = null;\n this.audioContext = null;\n this.analyser = null;\n this.peerSfu = null;\n this.sessioneSfu = null;\n this.connessioneSfuAttesa = false;\n this.trasporto = null;\n this.intervalloAudio = null;\n this.timerConnessione = null;\n this.cancellaAttesaConnessione = null;\n this.timerRiconnessione = null;\n this.ultimoAudioMic = Number.NEGATIVE_INFINITY;\n this.sequenzaRichieste = 0;\n this.generazione = 0;\n this.tentativoRiconnessione = 0;\n this.desiderata = false;\n this.micDesiderato = true;\n this.promessaIngresso = null;\n this.negoziazione = Promise.resolve();\n this.dipendenze = dipendenze ?? dipendenzeReali(timer);\n }\n get mode() {\n return this.modeCorrente;\n }\n get state() {\n return this.stateCorrente;\n }\n get mic() {\n return this.stateCorrente === "on" && this.tracciaMic !== null;\n }\n get muted() {\n return this.mutedCorrente;\n }\n get speaking() {\n return this.speakingCorrente;\n }\n get peers() {\n return this.copiaPeers();\n }\n async join(options = {}) {\n if (this.stateCorrente === "on") return;\n if (this.stateCorrente === "joining") {\n if (this.promessaIngresso !== null) await this.promessaIngresso;\n return;\n }\n if (this.stateCorrente === "reconnecting" && this.desiderata) return;\n const mic = this.scegliMic(options);\n this.verificaIngresso(mic);\n this.micDesiderato = mic;\n this.desiderata = true;\n this.tentativoRiconnessione = 0;\n this.aggiornaState("joining");\n const generazione = ++this.generazione;\n const promessa = this.completaIngresso(generazione);\n this.promessaIngresso = promessa;\n try {\n await promessa;\n } finally {\n if (this.promessaIngresso === promessa) this.promessaIngresso = null;\n }\n }\n async completaIngresso(generazione) {\n try {\n await this.entra(generazione);\n } catch (cause) {\n if (generazione !== this.generazione) return;\n this.desiderata = false;\n this.chiudiRisorse();\n this.aggiornaState("off");\n throw this.mappaErrore(cause);\n }\n }\n leave() {\n const deveFermare = this.desiderata || this.stateCorrente !== "off";\n this.desiderata = false;\n this.generazione++;\n this.fermaRiconnessione();\n if (deveFermare && this.contesto.connessa()) {\n void this.richiedi({ t: "voice", op: "stop" }).catch(() => void 0);\n }\n this.rifiutaRichieste(creaErrore("offline", "Voice has stopped."));\n this.chiudiRisorse();\n this.aggiornaState("off");\n }\n mute(muted = true) {\n if (this.stateCorrente !== "on" || this.tracciaMic === null) {\n throw creaErrore("not_publishing", "Join voice before changing mute.");\n }\n this.mutedCorrente = muted;\n this.tracciaMic.enabled = !muted;\n void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);\n }\n setVolume(playerId, volume) {\n const valore = limita(volume);\n this.volumi.set(playerId, valore);\n this.aggiornaGuadagno(playerId);\n this.notificaPeers();\n }\n onPeers(listener) {\n this.ascoltatoriPeers.add(listener);\n return () => {\n this.ascoltatoriPeers.delete(listener);\n };\n }\n onState(listener) {\n this.ascoltatoriState.add(listener);\n return () => {\n this.ascoltatoriState.delete(listener);\n };\n }\n ricevi(message) {\n if ("r" in message) {\n const pending = this.richieste.get(message.r);\n if (pending !== void 0) {\n this.richieste.delete(message.r);\n if ("error" in message) {\n pending.reject(creaErrore(message.error.code, message.error.message));\n } else pending.resolve(message);\n }\n return;\n }\n if (message.op === "roster") {\n this.modeCorrente = message.mode;\n const publisher = new Set(message.peers.map((peer) => peer.id));\n this.roster = [\n ...message.peers.map((peer) => ({ ...peer, mic: true })),\n ...message.listeners.flatMap((id) => publisher.has(id) ? [] : [{ id, mic: false, muted: true }])\n ];\n for (const peer of this.roster) {\n if (peer.muted) this.speakingPeers.set(peer.id, false);\n }\n this.pulisciPeerAssenti();\n this.contesto.rosterPronto();\n this.notificaPeers();\n this.accodaRiconciliazione();\n return;\n }\n if (message.op === "gain") {\n for (const [playerId, gain] of Object.entries(message.gains)) {\n this.gains.set(playerId, limita(gain));\n this.aggiornaZero(playerId);\n this.aggiornaGuadagno(playerId);\n }\n this.notificaPeers();\n this.accodaRiconciliazione();\n return;\n }\n if (message.op === "signal") void this.riceviSegnale(message.from, message.data);\n }\n giocatoriCambiati() {\n const presenti = new Set(this.contesto.giocatori().map((player) => player.id));\n for (const playerId of this.gains.keys()) {\n if (presenti.has(playerId)) continue;\n this.gains.delete(playerId);\n this.zeroDa.delete(playerId);\n const timer = this.timerZero.get(playerId);\n if (timer !== void 0) this.dipendenze?.clearTimeout(timer);\n this.timerZero.delete(playerId);\n this.aggiornaGuadagno(playerId);\n }\n this.notificaPeers();\n this.accodaRiconciliazione();\n }\n socketDisconnesso() {\n this.sequenzaRichieste = 0;\n this.rifiutaRichieste(creaErrore("offline", "The room is reconnecting."));\n if (!this.desiderata) return;\n this.generazione++;\n this.chiudiRisorse();\n this.tentativoRiconnessione = 0;\n this.aggiornaState("reconnecting");\n }\n socketRiconnesso() {\n this.sequenzaRichieste = 0;\n if (this.desiderata && this.stateCorrente === "reconnecting") this.programmaRiconnessione();\n }\n termina() {\n this.desiderata = false;\n this.generazione++;\n this.fermaRiconnessione();\n this.rifiutaRichieste(creaErrore("offline", "The room connection ended."));\n this.chiudiRisorse();\n this.aggiornaState("off");\n }\n scegliMic(options) {\n if (options.mic !== void 0) return options.mic;\n const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());\n return you?.role !== "spectator";\n }\n verificaIngresso(mic = this.micDesiderato) {\n if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");\n if (this.modeCorrente === "none") {\n throw creaErrore("voice_disabled", "Voice is disabled for this room.");\n }\n const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());\n if (you?.role === "spectator" && mic) {\n throw creaErrore("spectator", "Spectators cannot publish voice.");\n }\n if (this.dipendenze === null) {\n throw creaErrore("unsupported", "Voice is not supported in this browser.");\n }\n }\n async entra(generazione) {\n this.verificaIngresso();\n const dipendenze = this.richiediDipendenze();\n const audioContext = dipendenze.creaAudioContext();\n this.audioContext = audioContext;\n try {\n await audioContext.resume();\n } catch {\n }\n if (this.micDesiderato) {\n let stream;\n try {\n stream = await dipendenze.getUserMedia({ audio: true });\n } catch (cause) {\n if (this.permessoNegato(cause)) {\n throw creaErrore("permission_denied", "Microphone permission was denied.");\n }\n throw creaErrore("voice_error", "The microphone could not be opened.");\n }\n try {\n this.controllaGenerazione(generazione);\n } catch (cause) {\n for (const track of stream.getTracks()) track.stop();\n throw cause;\n }\n const mic = stream.getAudioTracks()[0];\n if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");\n this.stream = stream;\n this.tracciaMic = mic;\n mic.enabled = !this.mutedCorrente;\n this.preparaAnalizzatore(stream);\n }\n const risposta = await this.richiedi({ t: "voice", op: "ice" });\n this.controllaGenerazione(generazione);\n if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");\n this.modeCorrente = risposta.mode;\n if (risposta.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");\n this.trasporto = risposta.transport;\n if (risposta.transport === "sfu") {\n await this.entraSfu(risposta.iceServers, generazione);\n } else {\n await this.richiedi({ t: "voice", op: "publish", mic: this.micDesiderato });\n }\n if (this.micDesiderato && this.mutedCorrente) {\n await this.richiedi({ t: "voice", op: "mute", muted: true });\n }\n this.controllaGenerazione(generazione);\n this.tentativoRiconnessione = 0;\n this.aggiornaState("on");\n this.avviaMisuraAudio();\n for (const playerId of this.gains.keys()) this.aggiornaZero(playerId);\n this.accodaRiconciliazione();\n }\n async entraSfu(iceServers, generazione) {\n const pc = this.richiediDipendenze().creaPeerConnection({\n iceServers,\n bundlePolicy: "max-bundle"\n });\n this.peerSfu = pc;\n pc.ontrack = (event) => {\n const mid = event.transceiver.mid;\n const playerId = mid === null ? void 0 : this.midGiocatori.get(mid);\n if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);\n };\n this.osservaCaduta(pc);\n let risposta;\n if (this.micDesiderato) {\n const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });\n const offer = await pc.createOffer();\n await pc.setLocalDescription(offer);\n this.controllaGenerazione(generazione);\n const mid = transceiver.mid;\n const sdp = pc.localDescription?.sdp;\n if (mid === null || sdp === void 0) {\n throw creaErrore("voice_error", "The voice connection could not create an offer.");\n }\n risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });\n } else {\n risposta = await this.richiedi({ t: "voice", op: "session" });\n }\n if (risposta.op !== "session") {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n this.sessioneSfu = risposta.session;\n if (this.micDesiderato) {\n if (risposta.sdp === null) {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });\n await this.attendiConnessione(pc, generazione);\n this.connessioneSfuAttesa = true;\n return;\n }\n if (risposta.sdp !== null) {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n if (this.publisherDesiderati().length > 0) {\n await this.riconciliaSfu();\n }\n }\n attendiConnessione(pc, generazione) {\n if (pc.connectionState === "connected") return Promise.resolve();\n const dipendenze = this.richiediDipendenze();\n return new Promise((resolve, reject) => {\n const pulisci = () => {\n pc.removeEventListener("connectionstatechange", cambiata);\n if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);\n this.timerConnessione = null;\n this.cancellaAttesaConnessione = null;\n };\n const cambiata = () => {\n if (generazione !== this.generazione) {\n pulisci();\n reject(creaErrore("offline", "Voice was stopped."));\n } else if (pc.connectionState === "connected") {\n pulisci();\n resolve();\n } else if (pc.connectionState === "failed" || pc.connectionState === "closed") {\n pulisci();\n reject(creaErrore("voice_error", "The voice connection failed."));\n }\n };\n pc.addEventListener("connectionstatechange", cambiata);\n this.cancellaAttesaConnessione = () => {\n pulisci();\n reject(creaErrore("offline", "Voice was stopped."));\n };\n this.timerConnessione = dipendenze.setTimeout(() => {\n pulisci();\n reject(creaErrore("voice_error", "The voice connection timed out."));\n }, TIMEOUT_CONNESSIONE);\n });\n }\n accodaRiconciliazione() {\n if (this.stateCorrente !== "on") return;\n this.negoziazione = this.negoziazione.then(async () => {\n if (this.stateCorrente !== "on") return;\n if (this.trasporto === "sfu") await this.riconciliaSfu();\n else if (this.trasporto === "mesh") this.riconciliaMesh();\n }).catch(() => this.avviaRiconnessione());\n }\n async riconciliaSfu() {\n const sessione = this.sessioneSfu;\n const pc = this.peerSfu;\n if (sessione === null || pc === null) return;\n const desiderati = new Map(this.publisherDesiderati().map((peer) => [peer.id, peer]));\n const daChiudere = [];\n for (const [playerId, attiva] of this.sfuAttive) {\n const peer = desiderati.get(playerId);\n if (peer !== void 0 && peer.session === attiva.session && peer.track === attiva.track) continue;\n daChiudere.push(attiva);\n if (!this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();\n this.sfuAttive.delete(playerId);\n this.midGiocatori.delete(attiva.mid);\n this.scollegaTraccia(playerId);\n }\n if (daChiudere.length > 0) {\n await this.richiedi({\n t: "voice",\n op: "close",\n session: sessione,\n mids: daChiudere.map((item) => item.mid)\n });\n }\n const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));\n if (nuove.length === 0) return;\n const risposta = await this.richiedi({\n t: "voice",\n op: "subscribe",\n session: sessione,\n tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))\n });\n if (risposta.op !== "subscribe") {\n throw creaErrore("voice_error", "The voice service returned an invalid response.");\n }\n for (const risultato of risposta.tracks) {\n const peer = nuove.find(\n (item) => item.session === risultato.session && item.track === risultato.track\n );\n if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;\n this.midGiocatori.set(risultato.mid, peer.id);\n this.sfuAttive.set(peer.id, {\n session: peer.session,\n track: peer.track,\n mid: risultato.mid,\n receiver: null\n });\n }\n await pc.setRemoteDescription({ type: "offer", sdp: risposta.sdp });\n const answer = await pc.createAnswer();\n await pc.setLocalDescription(answer);\n const sdp = pc.localDescription?.sdp;\n if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");\n await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });\n if (!this.connessioneSfuAttesa) {\n await this.attendiConnessione(pc, this.generazione);\n this.connessioneSfuAttesa = true;\n }\n }\n riconciliaMesh() {\n const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));\n for (const [playerId, item] of this.mesh) {\n if (desiderati.has(playerId)) continue;\n item.pc.close();\n this.mesh.delete(playerId);\n this.scollegaTraccia(playerId);\n }\n for (const peer of desiderati.values()) {\n if (!this.mesh.has(peer.id)) this.creaMesh(peer);\n }\n }\n creaMesh(peer) {\n const playerId = peer.id;\n const pc = this.richiediDipendenze().creaPeerConnection();\n const item = {\n pc,\n makingOffer: false,\n ignoreOffer: false,\n settingRemoteAnswer: false,\n polite: this.contesto.you() > playerId,\n receiver: null\n };\n this.mesh.set(playerId, item);\n pc.onicecandidate = (event) => {\n if (event.candidate === null) return;\n void this.inviaSegnale(playerId, { kind: "candidate", candidate: event.candidate.toJSON() });\n };\n if (!item.polite) pc.onnegotiationneeded = () => {\n void this.offriMesh(playerId, item);\n };\n pc.ontrack = (event) => {\n item.receiver = event.receiver;\n this.collegaTraccia(playerId, event.track, event.receiver);\n };\n this.osservaCaduta(pc);\n if (this.micDesiderato) {\n pc.addTransceiver(this.richiediMic(), {\n direction: peer.mic ? "sendrecv" : "sendonly"\n });\n } else {\n pc.addTransceiver("audio", { direction: "recvonly" });\n }\n }\n async offriMesh(playerId, item) {\n try {\n item.makingOffer = true;\n const offer = await item.pc.createOffer();\n await item.pc.setLocalDescription(offer);\n const sdp = item.pc.localDescription?.sdp;\n if (sdp !== void 0) await this.inviaSegnale(playerId, { kind: "offer", sdp });\n } finally {\n item.makingOffer = false;\n }\n }\n async riceviSegnale(from, data) {\n if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;\n const peer = this.peerDesiderati().find((item2) => item2.id === from);\n if (peer === void 0) return;\n if (!this.mesh.has(from)) this.creaMesh(peer);\n const item = this.mesh.get(from);\n if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;\n const segnale = data;\n try {\n if (segnale.kind === "candidate") {\n if (!item.ignoreOffer) await item.pc.addIceCandidate(segnale.candidate);\n return;\n }\n if (segnale.kind !== "offer" && segnale.kind !== "answer" || typeof segnale.sdp !== "string") return;\n const pronta = !item.makingOffer && (item.pc.signalingState === "stable" || item.settingRemoteAnswer);\n const collisione = segnale.kind === "offer" && !pronta;\n item.ignoreOffer = !item.polite && collisione;\n if (item.ignoreOffer) return;\n item.settingRemoteAnswer = segnale.kind === "answer";\n await item.pc.setRemoteDescription({ type: segnale.kind, sdp: segnale.sdp });\n item.settingRemoteAnswer = false;\n if (segnale.kind === "offer") {\n const answer = await item.pc.createAnswer();\n await item.pc.setLocalDescription(answer);\n const sdp = item.pc.localDescription?.sdp;\n if (sdp !== void 0) await this.inviaSegnale(from, { kind: "answer", sdp });\n }\n } catch {\n this.avviaRiconnessione();\n }\n }\n inviaSegnale(to, data) {\n return this.richiedi({ t: "voice", op: "signal", to, data });\n }\n peerDesiderati() {\n const you = this.contesto.you();\n const giocatori = this.contesto.giocatori();\n const player = giocatori.find((item) => item.id === you);\n return this.roster.filter((peer) => {\n if (peer.id === you) return false;\n if (!this.micDesiderato && !peer.mic) return false;\n if (this.modeCorrente === "team") {\n const altro = giocatori.find((item) => item.id === peer.id);\n if (player?.role !== "spectator" && altro?.team !== player?.team) return false;\n }\n return true;\n });\n }\n publisherDesiderati() {\n return this.peerDesiderati().filter(\n (peer) => {\n if (!peer.mic) return false;\n const zeroAt = this.zeroDa.get(peer.id);\n return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;\n }\n );\n }\n aggiornaZero(playerId) {\n const dipendenze = this.dipendenze;\n if (dipendenze === null) return;\n const precedente = this.timerZero.get(playerId);\n if (precedente !== void 0) dipendenze.clearTimeout(precedente);\n this.timerZero.delete(playerId);\n if ((this.gains.get(playerId) ?? 1) > 0) {\n this.zeroDa.delete(playerId);\n return;\n }\n if (!this.zeroDa.has(playerId)) this.zeroDa.set(playerId, dipendenze.ora());\n const trascorso = dipendenze.ora() - (this.zeroDa.get(playerId) ?? dipendenze.ora());\n const timer = dipendenze.setTimeout(() => {\n this.timerZero.delete(playerId);\n this.accodaRiconciliazione();\n }, Math.max(0, DURATA_ZERO - trascorso));\n this.timerZero.set(playerId, timer);\n }\n collegaTraccia(playerId, track, receiver) {\n this.scollegaTraccia(playerId);\n const dipendenze = this.richiediDipendenze();\n const media = dipendenze.creaMediaStream([track]);\n const source = this.richiediAudioContext().createMediaStreamSource(media);\n const gain = this.richiediAudioContext().createGain();\n source.connect(gain);\n gain.connect(this.richiediAudioContext().destination);\n let analyser = null;\n try {\n analyser = this.richiediAudioContext().createAnalyser();\n analyser.fftSize = 256;\n source.connect(analyser);\n } catch {\n analyser = null;\n }\n const audio = dipendenze.creaAudioElement();\n audio.srcObject = media;\n audio.muted = true;\n audio.playsInline = true;\n void audio.play().catch(() => void 0);\n this.riproduzioni.set(playerId, { source, gain, analyser, audio, track, receiver });\n const attiva = this.sfuAttive.get(playerId);\n if (attiva !== void 0) attiva.receiver = receiver;\n this.aggiornaGuadagno(playerId);\n }\n scollegaTraccia(playerId) {\n const riproduzione = this.riproduzioni.get(playerId);\n if (riproduzione === void 0) return;\n riproduzione.source.disconnect();\n riproduzione.gain.disconnect();\n riproduzione.analyser?.disconnect();\n riproduzione.track.stop();\n riproduzione.audio.pause();\n riproduzione.audio.srcObject = null;\n this.riproduzioni.delete(playerId);\n this.speakingPeers.delete(playerId);\n this.ultimoAudio.delete(playerId);\n }\n aggiornaGuadagno(playerId) {\n const riproduzione = this.riproduzioni.get(playerId);\n if (riproduzione !== void 0) {\n riproduzione.gain.gain.value = (this.volumi.get(playerId) ?? 1) * (this.gains.get(playerId) ?? 1);\n }\n }\n preparaAnalizzatore(stream) {\n const context = this.richiediAudioContext();\n const analyser = context.createAnalyser();\n analyser.fftSize = 256;\n context.createMediaStreamSource(stream).connect(analyser);\n this.analyser = analyser;\n }\n avviaMisuraAudio() {\n const dipendenze = this.richiediDipendenze();\n if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);\n this.intervalloAudio = dipendenze.setInterval(() => this.misuraAudio(), INTERVALLO_AUDIO);\n }\n misuraAudio() {\n const dipendenze = this.dipendenze;\n if (dipendenze === null) return;\n let sopraSoglia = false;\n if (this.analyser !== null) sopraSoglia = this.livelloAnalizzatore(this.analyser) > SOGLIA_AUDIO;\n if (sopraSoglia) this.ultimoAudioMic = dipendenze.ora();\n const parlando = !this.mutedCorrente && dipendenze.ora() - this.ultimoAudioMic <= DURATA_PARLANTE;\n if (parlando !== this.speakingCorrente) {\n this.speakingCorrente = parlando;\n this.notificaPeers();\n }\n let cambiato = false;\n for (const peer of this.copiaPeers()) {\n const riproduzione = this.riproduzioni.get(peer.id);\n if (this.livelloAnalizzatore(riproduzione?.analyser ?? null) > SOGLIA_AUDIO) {\n this.ultimoAudio.set(peer.id, dipendenze.ora());\n } else if (riproduzione?.analyser === null || riproduzione?.analyser === void 0) {\n const sources = riproduzione?.receiver?.getSynchronizationSources?.() ?? [];\n if (sources.some((source) => (source.audioLevel ?? 0) > SOGLIA_AUDIO)) {\n this.ultimoAudio.set(peer.id, dipendenze.ora());\n }\n }\n const speaking = !peer.muted && dipendenze.ora() - (this.ultimoAudio.get(peer.id) ?? 0) <= DURATA_PARLANTE;\n if ((this.speakingPeers.get(peer.id) ?? false) !== speaking) {\n this.speakingPeers.set(peer.id, speaking);\n cambiato = true;\n }\n }\n if (cambiato) this.notificaPeers();\n }\n livelloAnalizzatore(analyser) {\n const nodo = analyser;\n if (nodo?.getFloatTimeDomainData === void 0) return 0;\n const campioni = new Float32Array(nodo.fftSize);\n nodo.getFloatTimeDomainData(campioni);\n return Math.sqrt(campioni.reduce((somma, valore) => somma + valore * valore, 0) / Math.max(1, campioni.length));\n }\n copiaPeers() {\n const you = this.contesto.you();\n const giocatori = this.contesto.giocatori();\n const player = giocatori.find((item) => item.id === you);\n return this.roster.flatMap((peer) => {\n if (peer.id === you) return [];\n if (this.modeCorrente === "team") {\n const altro = giocatori.find((item) => item.id === peer.id);\n if (player?.role !== "spectator" && altro?.team !== player?.team) return [];\n }\n return [{\n id: peer.id,\n mic: peer.mic,\n muted: peer.muted,\n speaking: peer.mic && !peer.muted && (this.speakingPeers.get(peer.id) ?? false),\n volume: this.volumi.get(peer.id) ?? 1,\n gain: this.gains.get(peer.id) ?? 1\n }];\n });\n }\n pulisciPeerAssenti() {\n const presenti = new Set(this.roster.map((peer) => peer.id));\n for (const playerId of this.speakingPeers.keys()) {\n if (!presenti.has(playerId)) this.speakingPeers.delete(playerId);\n }\n for (const playerId of this.zeroDa.keys()) {\n if (presenti.has(playerId)) continue;\n this.zeroDa.delete(playerId);\n const timer = this.timerZero.get(playerId);\n if (timer !== void 0) this.dipendenze?.clearTimeout(timer);\n this.timerZero.delete(playerId);\n }\n }\n osservaCaduta(pc) {\n pc.addEventListener("connectionstatechange", () => {\n if (this.stateCorrente === "on" && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) this.avviaRiconnessione();\n });\n }\n avviaRiconnessione() {\n if (!this.desiderata || this.stateCorrente === "reconnecting") return;\n this.generazione++;\n this.rifiutaRichieste(creaErrore("voice_error", "The voice connection was restarted."));\n this.chiudiRisorse();\n this.tentativoRiconnessione = 0;\n this.aggiornaState("reconnecting");\n this.programmaRiconnessione();\n }\n programmaRiconnessione() {\n if (!this.desiderata || !this.contesto.connessa() || this.timerRiconnessione !== null || this.stateCorrente !== "reconnecting") return;\n const ritardo = RITARDI_RICONNESSIONE[this.tentativoRiconnessione];\n if (ritardo === void 0) {\n this.desiderata = false;\n this.aggiornaState("off");\n return;\n }\n this.tentativoRiconnessione++;\n this.timerRiconnessione = this.richiediDipendenze().setTimeout(() => {\n this.timerRiconnessione = null;\n const generazione = ++this.generazione;\n void this.entra(generazione).catch(() => {\n if (generazione !== this.generazione || !this.desiderata) return;\n this.chiudiRisorse();\n this.aggiornaState("reconnecting");\n this.programmaRiconnessione();\n });\n }, ritardo);\n }\n fermaRiconnessione() {\n if (this.timerRiconnessione === null || this.dipendenze === null) return;\n this.dipendenze.clearTimeout(this.timerRiconnessione);\n this.timerRiconnessione = null;\n }\n chiudiRisorse() {\n const dipendenze = this.dipendenze;\n this.cancellaAttesaConnessione?.();\n this.cancellaAttesaConnessione = null;\n if (dipendenze !== null) {\n if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);\n if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);\n for (const timer of this.timerZero.values()) dipendenze.clearTimeout(timer);\n }\n this.intervalloAudio = null;\n this.timerConnessione = null;\n this.timerZero.clear();\n for (const playerId of [...this.riproduzioni.keys()]) this.scollegaTraccia(playerId);\n this.peerSfu?.close();\n this.peerSfu = null;\n for (const item of this.mesh.values()) item.pc.close();\n this.mesh.clear();\n this.sfuAttive.clear();\n this.midGiocatori.clear();\n for (const track of this.stream?.getTracks() ?? []) track.stop();\n this.stream = null;\n this.tracciaMic = null;\n this.analyser = null;\n void this.audioContext?.close().catch(() => void 0);\n this.audioContext = null;\n this.sessioneSfu = null;\n this.connessioneSfuAttesa = false;\n this.trasporto = null;\n this.speakingCorrente = false;\n this.ultimoAudioMic = Number.NEGATIVE_INFINITY;\n this.speakingPeers.clear();\n this.ultimoAudio.clear();\n this.negoziazione = Promise.resolve();\n }\n richiedi(message) {\n if (!this.contesto.connessa()) return Promise.reject(creaErrore("offline", "The room is reconnecting."));\n const r = ++this.sequenzaRichieste;\n return new Promise((resolve, reject) => {\n this.richieste.set(r, { resolve, reject });\n try {\n this.contesto.invia({ ...message, r });\n } catch (cause) {\n this.richieste.delete(r);\n reject(cause);\n }\n });\n }\n rifiutaRichieste(reason) {\n for (const richiesta of this.richieste.values()) richiesta.reject(reason);\n this.richieste.clear();\n }\n aggiornaState(state) {\n if (state === this.stateCorrente) return;\n this.stateCorrente = state;\n for (const listener of this.ascoltatoriState) {\n try {\n listener(state);\n } catch {\n }\n }\n }\n notificaPeers() {\n const peers = this.copiaPeers();\n for (const listener of this.ascoltatoriPeers) {\n try {\n listener(peers);\n } catch {\n }\n }\n }\n controllaGenerazione(generazione) {\n if (generazione !== this.generazione || !this.desiderata) {\n throw creaErrore("offline", "Voice was stopped.");\n }\n }\n richiediDipendenze() {\n if (this.dipendenze === null) throw creaErrore("unsupported", "Voice is not supported.");\n return this.dipendenze;\n }\n richiediMic() {\n if (this.tracciaMic === null) throw creaErrore("voice_error", "The microphone is not ready.");\n return this.tracciaMic;\n }\n richiediAudioContext() {\n if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");\n return this.audioContext;\n }\n permessoNegato(cause) {\n return typeof cause === "object" && cause !== null && "name" in cause && (cause.name === "NotAllowedError" || cause.name === "SecurityError");\n }\n mappaErrore(cause) {\n if (typeof cause === "object" && cause !== null && "code" in cause) {\n const code = cause.code;\n if (code === "voice_disabled" || code === "permission_denied" || code === "unsupported" || code === "spectator" || code === "offline" || code === "voice_error") return cause;\n return creaErrore("voice_error", "Voice could not be started.");\n }\n return creaErrore("voice_error", "Voice could not be started.");\n }\n};\n\n// src/stanza-client/index.ts\nvar APERTO = 1;\nvar RITARDI_RICONNESSIONE2 = [1e3, 2e3, 4e3, 8e3];\nvar GRAZIA_RICONNESSIONE = 6e4;\nvar INTERVALLO_PING = 5e3;\nvar RITARDO_FLUSH = 500;\nvar ATTESA_ROSTER = 2e3;\nvar CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);\nfunction record2(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;\n}\nfunction ingressoValido(value) {\n const dati = record2(value);\n return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";\n}\nfunction rispostaMatchValida(value) {\n const dati = record2(value);\n const players = record2(dati?.players);\n 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;\n}\nfunction copiaJson(value) {\n return JSON.parse(JSON.stringify(value));\n}\nfunction applicaPatch(state, value) {\n let risultato = copiaJson(state);\n for (const operazione of value) {\n if (operazione.path.length === 0) {\n if (operazione.op !== "set") return { ok: false };\n risultato = copiaJson(operazione.value);\n continue;\n }\n let contenitore = risultato;\n const percorso = operazione.path;\n for (let indice = 0; indice < percorso.length - 1; indice++) {\n const parte = percorso[indice];\n if (Array.isArray(contenitore)) {\n if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };\n contenitore = contenitore[parte];\n } else {\n const oggetto = record2(contenitore);\n if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {\n return { ok: false };\n }\n contenitore = oggetto[parte];\n }\n }\n const ultima = percorso.at(-1);\n if (Array.isArray(contenitore)) {\n if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };\n contenitore[ultima] = copiaJson(operazione.value);\n } else {\n const oggetto = record2(contenitore);\n if (oggetto === null || typeof ultima !== "string") return { ok: false };\n if (operazione.op === "del") {\n if (!Object.hasOwn(oggetto, ultima)) return { ok: false };\n delete oggetto[ultima];\n } else {\n Object.defineProperty(oggetto, ultima, {\n configurable: true,\n enumerable: true,\n value: copiaJson(operazione.value),\n writable: true\n });\n }\n }\n }\n return { ok: true, state: risultato };\n}\nfunction creaApiLive(input) {\n const richiesta = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);\n async function ingresso(path, body, rinnova = false) {\n const value = await richiesta(path, "POST", body, rinnova);\n if (!ingressoValido(value)) {\n throw creaErrore("internal_error", "The room service returned an invalid response.");\n }\n return value;\n }\n async function match(options) {\n const value = await richiesta("/match", "POST", {\n mode: options.mode,\n key: options.key\n });\n if (!rispostaMatchValida(value)) {\n throw creaErrore("internal_error", "The matchmaking service returned an invalid response.");\n }\n return value;\n }\n return {\n create: (mode) => ingresso("/rooms", { mode }),\n joinCode: (code) => ingresso("/rooms/join", { code }),\n joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),\n match,\n flush: (roomId) => richiesta(\n `/rooms/${encodeURIComponent(roomId)}/flush`,\n "POST"\n )\n };\n}\nvar StanzaClient = class {\n constructor(roomId, codice, url, input, api, segnalaStanza) {\n this.roomId = roomId;\n this.codice = codice;\n this.input = input;\n this.api = api;\n this.segnalaStanza = segnalaStanza;\n this.statoPubblico = null;\n this.statoSincronizzato = null;\n this.tickCorrente = 0;\n this.seedCorrente = 0;\n this.statusCorrente = "lobby";\n this.giocatoriCorrenti = [];\n this.youCorrente = "";\n this.hostCorrente = null;\n this.resultCorrente = null;\n this.socket = null;\n this.seq = 0;\n this.scartoOrario = 0;\n this.timerPing = null;\n this.timerRiconnessione = null;\n this.timerFlush = null;\n this.flushInCorso = false;\n this.flushRichiesto = false;\n this.ritardoIndice = 0;\n this.tempoRiconnessione = 0;\n this.resyncRichiesto = false;\n this.terminata = false;\n this.lasciata = false;\n this.prontaRisolta = false;\n this.welcomeRicevuto = false;\n this.rosterRicevuto = false;\n this.timerRoster = null;\n this.risolviPronta = () => void 0;\n this.rifiutaPronta = () => void 0;\n this.ascoltatoriStato = /* @__PURE__ */ new Set();\n this.ascoltatoriGiocatori = /* @__PURE__ */ new Set();\n this.ascoltatoriStatus = /* @__PURE__ */ new Set();\n this.ascoltatoriMessaggi = /* @__PURE__ */ new Set();\n this.promessaPronta = new Promise((resolve, reject) => {\n this.risolviPronta = resolve;\n this.rifiutaPronta = reject;\n });\n this.voice = new VoceClient({\n invia: (message) => this.invia(message),\n connessa: () => this.socket?.readyState === APERTO && this.welcomeRicevuto && !this.terminata && !this.lasciata,\n you: () => this.youCorrente,\n giocatori: () => this.copiaGiocatori(),\n rosterPronto: () => {\n this.rosterRicevuto = true;\n this.risolviProntaSePossibile();\n }\n }, input, input.voce);\n this.apri(url);\n }\n get state() {\n return this.statoPubblico;\n }\n get tick() {\n return this.tickCorrente;\n }\n get seed() {\n return this.seedCorrente;\n }\n get status() {\n return this.statusCorrente;\n }\n get players() {\n return this.copiaGiocatori();\n }\n get you() {\n return this.youCorrente;\n }\n get host() {\n return this.hostCorrente;\n }\n get code() {\n return this.codice;\n }\n get result() {\n return this.resultCorrente;\n }\n pronta() {\n return this.promessaPronta;\n }\n invite() {\n return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };\n }\n onState(listener) {\n this.ascoltatoriStato.add(listener);\n return () => {\n this.ascoltatoriStato.delete(listener);\n };\n }\n onPlayers(listener) {\n this.ascoltatoriGiocatori.add(listener);\n return () => {\n this.ascoltatoriGiocatori.delete(listener);\n };\n }\n onStatus(listener) {\n this.ascoltatoriStatus.add(listener);\n return () => {\n this.ascoltatoriStatus.delete(listener);\n };\n }\n onMessage(listener) {\n this.ascoltatoriMessaggi.add(listener);\n return () => {\n this.ascoltatoriMessaggi.delete(listener);\n };\n }\n send(message) {\n const prossimo = this.seq + 1;\n this.invia({ t: "msg", seq: prossimo, m: message });\n this.seq = prossimo;\n }\n ready(ready) {\n this.invia({ t: "ready", ready });\n }\n setRole(role) {\n this.invia({ t: "role", role });\n }\n setTeam(team) {\n this.invia({ t: "team", team });\n }\n start() {\n this.invia({ t: "start" });\n }\n leave() {\n if (this.lasciata) return;\n this.voice.leave();\n this.lasciata = true;\n this.segnalaStanza(null);\n if (this.socket?.readyState === APERTO) this.invia({ t: "leave" });\n this.termina(1e3);\n }\n serverTime() {\n return this.input.ora() + this.scartoOrario;\n }\n copiaGiocatori() {\n return this.giocatoriCorrenti.map((player) => ({ ...player }));\n }\n notifica(listeners, ...args) {\n for (const listener of listeners) {\n try {\n listener(...args);\n } catch {\n }\n }\n }\n invia(message) {\n if (this.socket?.readyState !== APERTO) {\n throw creaErrore("offline", "The room is reconnecting.");\n }\n let frame;\n try {\n frame = JSON.stringify(message);\n } catch {\n throw creaErrore("invalid_request", "Room messages must be valid JSON.");\n }\n this.socket.send(frame);\n }\n apri(url) {\n let socket;\n try {\n socket = this.input.apriSocket(url);\n } catch {\n this.programmaRiconnessione();\n return;\n }\n this.socket = socket;\n socket.addEventListener("open", () => {\n if (this.socket === socket) this.avviaPing();\n });\n socket.addEventListener("message", (evento) => {\n if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);\n });\n socket.addEventListener("close", (evento) => {\n if (this.socket === socket) this.chiuso(evento.code);\n });\n }\n avviaPing() {\n if (this.timerPing !== null) this.input.clearInterval(this.timerPing);\n this.timerPing = this.input.setInterval(() => {\n if (this.socket?.readyState !== APERTO) return;\n try {\n this.invia({ t: "ping", c: this.input.ora() });\n } catch {\n }\n }, INTERVALLO_PING);\n }\n fermaPing() {\n if (this.timerPing === null) return;\n this.input.clearInterval(this.timerPing);\n this.timerPing = null;\n }\n ricevi(frame) {\n let dati;\n try {\n const value = JSON.parse(frame);\n const oggetto = record2(value);\n if (oggetto === null || typeof oggetto.t !== "string") return;\n dati = oggetto;\n } catch {\n return;\n }\n try {\n if (dati.t === "welcome") this.riceviWelcome(dati);\n else if (dati.t === "players") this.riceviGiocatori(dati.players);\n else if (dati.t === "status") this.riceviStatus(dati);\n else if (dati.t === "state") this.riceviDiff(dati);\n else if (dati.t === "snapshot") this.riceviSnapshot(dati);\n else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));\n else if (dati.t === "pong") this.riceviPong(dati);\n else if (dati.t === "flush") this.richiediFlush();\n else if (dati.t === "voice") this.voice.ricevi(dati);\n } catch {\n if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();\n }\n }\n riceviWelcome(dati) {\n const room = dati.room;\n if (room.id !== this.roomId) return;\n this.youCorrente = dati.you;\n this.seedCorrente = room.seed;\n this.hostCorrente = room.host;\n this.statusCorrente = room.status;\n this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));\n this.aggiornaStato(dati.state, room.tick, room.serverTime);\n this.scartoOrario = room.serverTime - this.input.ora();\n this.resyncRichiesto = false;\n this.welcomeRicevuto = true;\n if (!this.rosterRicevuto && this.timerRoster === null) {\n this.timerRoster = this.input.setTimeout(() => {\n this.timerRoster = null;\n this.rosterRicevuto = true;\n this.risolviProntaSePossibile();\n }, ATTESA_ROSTER);\n }\n this.ritardoIndice = 0;\n this.tempoRiconnessione = 0;\n this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());\n this.voice.giocatoriCambiati();\n this.voice.socketRiconnesso();\n this.notifica(\n this.ascoltatoriStatus,\n this.statusCorrente,\n this.resultCorrente,\n room.serverTime\n );\n this.risolviProntaSePossibile();\n }\n riceviGiocatori(value) {\n this.giocatoriCorrenti = value.map((player) => ({ ...player }));\n if (!this.giocatoriCorrenti.some(\n (player) => player.id === this.hostCorrente && player.connected\n )) {\n this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;\n }\n this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());\n this.voice.giocatoriCambiati();\n }\n riceviStatus(dati) {\n this.statusCorrente = dati.status;\n this.resultCorrente = copiaJson(dati.result);\n if (dati.status === "ended") {\n this.terminata = true;\n this.segnalaStanza(null);\n this.voice.termina();\n this.fermaPing();\n this.fermaRiconnessione();\n }\n this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);\n }\n riceviDiff(dati) {\n if (dati.base !== this.tickCorrente) {\n this.chiediResync();\n return;\n }\n const risultato = applicaPatch(this.statoSincronizzato, dati.patch);\n if (!risultato.ok) {\n this.chiediResync();\n return;\n }\n this.resyncRichiesto = false;\n this.aggiornaStato(risultato.state, dati.tick, dati.serverTime);\n }\n riceviSnapshot(dati) {\n if (dati.tick < this.tickCorrente) return;\n this.resyncRichiesto = false;\n this.aggiornaStato(dati.state, dati.tick, dati.serverTime);\n }\n aggiornaStato(state, tick, serverTime) {\n this.statoSincronizzato = copiaJson(state);\n this.statoPubblico = copiaJson(state);\n this.tickCorrente = tick;\n this.notifica(this.ascoltatoriStato, this.statoPubblico, tick, serverTime);\n }\n chiediResync() {\n if (this.resyncRichiesto || this.socket?.readyState !== APERTO) return;\n this.resyncRichiesto = true;\n try {\n this.invia({ t: "resync" });\n } catch {\n this.resyncRichiesto = false;\n }\n }\n riceviPong(dati) {\n this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;\n }\n chiuso(code) {\n this.socket = null;\n this.welcomeRicevuto = false;\n this.fermaPing();\n if (CHIUSURE_DEFINITIVE.has(code)) {\n this.termina(code);\n return;\n }\n if (this.lasciata || this.terminata) return;\n this.voice.socketDisconnesso();\n this.programmaRiconnessione();\n }\n programmaRiconnessione() {\n if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;\n const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);\n const ritardo = RITARDI_RICONNESSIONE2[indice];\n if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {\n this.termina("timeout");\n return;\n }\n this.ritardoIndice++;\n this.tempoRiconnessione += ritardo;\n this.timerRiconnessione = this.input.setTimeout(() => {\n this.timerRiconnessione = null;\n void this.riconnetti();\n }, ritardo);\n }\n async riconnetti() {\n if (this.terminata || this.lasciata) return;\n try {\n const ingresso = await this.api.joinRoom(this.roomId);\n const codiceCambiato = this.codice !== ingresso.code;\n this.codice = ingresso.code;\n if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {\n this.segnalaStanza({ code: this.codice });\n }\n this.apri(ingresso.url);\n } catch {\n this.programmaRiconnessione();\n }\n }\n fermaRiconnessione() {\n if (this.timerRiconnessione === null) return;\n this.input.clearTimeout(this.timerRiconnessione);\n this.timerRiconnessione = null;\n }\n termina(code) {\n const risultato = { closed: code };\n const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);\n this.terminata = true;\n this.segnalaStanza(null);\n this.statusCorrente = "ended";\n this.resultCorrente = risultato;\n this.voice.termina();\n this.fermaPing();\n this.fermaRiconnessione();\n if (cambiato) this.notifica(this.ascoltatoriStatus, "ended", risultato, this.serverTime());\n if (!this.prontaRisolta) {\n this.prontaRisolta = true;\n const codici = {\n 4003: "kicked",\n 4004: "room_ended",\n 4005: "version_closed",\n 4006: "replaced"\n };\n const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";\n this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));\n }\n }\n risolviProntaSePossibile() {\n if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;\n if (this.timerRoster !== null) {\n this.input.clearTimeout(this.timerRoster);\n this.timerRoster = null;\n }\n this.prontaRisolta = true;\n if (!this.terminata && !this.lasciata) this.segnalaStanza({ code: this.codice });\n this.risolviPronta();\n }\n richiediFlush() {\n this.flushRichiesto = true;\n if (this.flushInCorso || this.timerFlush !== null) return;\n this.timerFlush = this.input.setTimeout(() => {\n this.timerFlush = null;\n void this.eseguiFlush();\n }, RITARDO_FLUSH);\n }\n async eseguiFlush() {\n if (this.flushInCorso || !this.flushRichiesto) return;\n this.flushInCorso = true;\n this.flushRichiesto = false;\n try {\n await this.api.flush(this.roomId);\n } catch {\n } finally {\n this.flushInCorso = false;\n if (this.flushRichiesto) this.richiediFlush();\n }\n }\n};\nfunction creaStanzeOffline(invited = null) {\n return {\n invited,\n async create() {\n throw erroreOffline();\n },\n async join() {\n throw erroreOffline();\n },\n async match() {\n throw erroreOffline();\n }\n };\n}\nfunction creaGestoreStanze(input, invited) {\n const api = creaApiLive(input);\n let haSegnalato = false;\n let ultimoCodice = null;\n const segnalaStanza = (room) => {\n const codice = room?.code ?? null;\n if (haSegnalato && codice === ultimoCodice) return;\n haSegnalato = true;\n ultimoCodice = codice;\n input.segnalaStanza?.(room);\n };\n const collega = async (ingresso) => {\n const stanza = new StanzaClient(\n ingresso.roomId,\n ingresso.code,\n ingresso.url,\n input,\n api,\n segnalaStanza\n );\n await stanza.pronta();\n return stanza;\n };\n const attendiMatch = (url, options) => new Promise((resolve, reject) => {\n let socket;\n let conclusa = false;\n const pulisci = () => {\n socket.removeEventListener("message", ricevi);\n socket.removeEventListener("close", chiuso);\n socket.removeEventListener("error", caduto);\n options.signal?.removeEventListener("abort", annulla);\n };\n const chiudi = () => {\n try {\n socket.close(1e3);\n } catch {\n }\n };\n const fallisci = (errore, chiudiSocket) => {\n if (conclusa) return;\n conclusa = true;\n pulisci();\n if (chiudiSocket) chiudi();\n reject(errore);\n };\n function annulla() {\n fallisci(\n creaErrore("cancelled", "The matchmaking search was cancelled."),\n true\n );\n }\n function chiuso() {\n fallisci(erroreOffline(), false);\n }\n function caduto() {\n fallisci(erroreOffline(), true);\n }\n function ricevi(evento) {\n let dati = null;\n try {\n dati = typeof evento.data === "string" ? record2(JSON.parse(evento.data)) : null;\n } catch {\n }\n if (dati === null || typeof dati.t !== "string") {\n fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);\n return;\n }\n if (dati.t === "waiting") {\n if (!Number.isInteger(dati.players) || !Number.isInteger(dati.min) || !Number.isInteger(dati.max)) {\n fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);\n return;\n }\n try {\n options.onWaiting?.({\n players: dati.players,\n min: dati.min,\n max: dati.max\n });\n } catch {\n }\n return;\n }\n if (dati.t === "matched") {\n if (!ingressoValido(dati)) {\n fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);\n return;\n }\n conclusa = true;\n pulisci();\n chiudi();\n resolve(dati);\n return;\n }\n if (dati.t === "no_match") {\n fallisci(creaErrore("no_match", "No match was found before the timeout."), true);\n return;\n }\n if (dati.t === "error") {\n fallisci(creaErrore(\n typeof dati.code === "string" ? dati.code : "internal_error",\n typeof dati.message === "string" ? dati.message : "The matchmaking service could not complete the search."\n ), true);\n return;\n }\n if (dati.t !== "pong") {\n fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);\n }\n }\n try {\n socket = input.apriSocket(url);\n } catch {\n reject(erroreOffline());\n return;\n }\n socket.addEventListener("message", ricevi);\n socket.addEventListener("close", chiuso);\n socket.addEventListener("error", caduto);\n options.signal?.addEventListener("abort", annulla, { once: true });\n if (options.signal?.aborted === true) annulla();\n });\n return {\n invited,\n async create(options) {\n return collega(await api.create(options.mode));\n },\n async join(code) {\n const scelto = code ?? invited;\n if (scelto === null || scelto === void 0 || scelto.length === 0) {\n throw creaErrore("invalid_request", "A room invitation code is required.");\n }\n return collega(await api.joinCode(scelto));\n },\n async match(options) {\n const annullata = () => options.signal?.aborted === true;\n if (annullata()) {\n throw creaErrore("cancelled", "The matchmaking search was cancelled.");\n }\n const risposta = await api.match(options);\n if (annullata()) {\n throw creaErrore("cancelled", "The matchmaking search was cancelled.");\n }\n return collega(await attendiMatch(risposta.url, options));\n }\n };\n}\n\n// src/standalone.ts\nvar PREFISSO = "caisual:save:";\nvar CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;\nfunction verificaChiave(key) {\n if (!CHIAVE_VALIDA.test(key)) {\n throw creaErrore("invalid_request", "Save keys must use lowercase letters, numbers, underscores, or hyphens.");\n }\n}\nfunction leggiSalvataggio(testo) {\n if (testo === null) return null;\n try {\n return JSON.parse(testo);\n } catch {\n return null;\n }\n}\nfunction chiavi(archivio) {\n const risultato = [];\n for (let indice = 0; indice < archivio.length; indice++) {\n const key = archivio.key(indice);\n if (key?.startsWith(PREFISSO)) risultato.push(key.slice(PREFISSO.length));\n }\n return risultato;\n}\nfunction creaSave(archivio, ora) {\n const disponibile = () => {\n if (archivio === null) throw erroreOffline();\n return archivio;\n };\n return {\n async set(key, value) {\n verificaChiave(key);\n const locale = disponibile();\n const corpo = JSON.stringify({ value });\n const bytes = new TextEncoder().encode(corpo).byteLength;\n if (bytes > 262144) {\n throw creaErrore("payload_too_large", "The save is larger than 262144 bytes.");\n }\n if (locale.getItem(PREFISSO + key) === null && chiavi(locale).length >= 32) {\n throw creaErrore("save_limit", "A game can store at most 32 save keys.");\n }\n const voce = { value, bytes, updatedAt: ora() };\n locale.setItem(PREFISSO + key, JSON.stringify(voce));\n return { key, bytes, updatedAt: voce.updatedAt };\n },\n async get(key) {\n verificaChiave(key);\n return leggiSalvataggio(disponibile().getItem(PREFISSO + key))?.value ?? null;\n },\n async remove(key) {\n verificaChiave(key);\n disponibile().removeItem(PREFISSO + key);\n },\n async list() {\n const locale = disponibile();\n return chiavi(locale).flatMap((key) => {\n const voce = leggiSalvataggio(locale.getItem(PREFISSO + key));\n return voce === null ? [] : [{ key, bytes: voce.bytes, updatedAt: voce.updatedAt }];\n }).sort((a, b) => a.key.localeCompare(b.key));\n }\n };\n}\nasync function creaStandalone(input, invited = null) {\n const day = giornoUtc(input.ora());\n const seed = await calcolaSeed(input.hostname, day, input.subtle);\n return {\n connected: false,\n player: { id: "local", name: "Guest", guest: true },\n daily: { day, seed, random: creaMulberry32(seed) },\n time: { now: input.ora },\n save: creaSave(input.archivio, input.ora),\n board: {\n async submit() {\n return { accepted: false, reason: "offline" };\n },\n async top(_board, opzioni = {}) {\n return { day: opzioni.daily ? day : null, entries: [], me: null };\n }\n },\n room: creaStanzeOffline(invited)\n };\n}\n\n// src/kit.ts\nfunction leggiAppOrigin(documento) {\n const valore = documento?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");\n if (valore === null || valore === void 0) return null;\n try {\n const url = new URL(valore);\n return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;\n } catch {\n return null;\n }\n}\nfunction archivioReale() {\n try {\n return typeof localStorage === "undefined" ? null : localStorage;\n } catch {\n return null;\n }\n}\nfunction dipendenzeReali2() {\n return {\n finestra: typeof window === "undefined" ? null : window,\n documento: typeof document === "undefined" ? null : document,\n fetcher: (input, init) => globalThis.fetch(input, init),\n archivio: archivioReale(),\n hostname: typeof location === "undefined" ? "" : location.hostname,\n subtle: globalThis.crypto.subtle,\n ora: Date.now,\n sonda: () => probeDevice()\n };\n}\nasync function connetti(input) {\n const appOrigin = leggiAppOrigin(input.documento);\n const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;\n if (appOrigin === null || senzaPadre) {\n return creaStandalone(input);\n }\n const handshake = await attendiHandshake(\n input.finestra,\n appOrigin,\n input.timeoutHandshake\n );\n if (handshake === null) return creaStandalone(input);\n const biglietto = creaGestoreBiglietto(\n handshake.ticket,\n handshake.porta,\n input.finestra,\n input.ora,\n input.timeoutRinnovo,\n "portal"\n );\n const api = creaClienteApi(appOrigin, input.fetcher, biglietto);\n const prima = input.ora();\n let me;\n try {\n me = await api.me();\n } catch {\n return creaStandalone(input, handshake.invite);\n }\n const dopo = input.ora();\n const scartoOrario = me.serverTime - (prima + dopo) / 2;\n const room = handshake.live === null ? creaStanzeOffline(handshake.invite) : creaGestoreStanze({\n appOrigin,\n liveOrigin: handshake.live,\n fetcher: input.fetcher,\n biglietto: creaGestoreBiglietto(\n null,\n handshake.porta,\n input.finestra,\n input.ora,\n input.timeoutRinnovo,\n "live"\n ),\n apriSocket(url) {\n if (input.apriSocket !== void 0) return input.apriSocket(url);\n if (typeof WebSocket === "undefined") throw erroreOffline();\n return new WebSocket(url);\n },\n ora: input.ora,\n setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout),\n clearTimeout: (id) => globalThis.clearTimeout(id),\n setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),\n clearInterval: (id) => globalThis.clearInterval(id),\n voce: input.voce,\n segnalaStanza(room2) {\n try {\n handshake.porta.postMessage({ type: "caisual:room", room: room2 });\n } catch {\n }\n }\n }, handshake.invite);\n return {\n connected: true,\n player: me.player,\n daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },\n time: { now: () => input.ora() + scartoOrario },\n save: {\n set: (key, value) => api.saveSet(key, value),\n get: (key) => api.saveGet(key),\n remove: (key) => api.saveRemove(key),\n list: () => api.saveList()\n },\n board: {\n async submit(board, score, opzioni = {}) {\n try {\n return await api.boardSubmit(board, score, opzioni.daily === true);\n } catch (errore) {\n if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline" };\n throw errore;\n }\n },\n top: (board, opzioni = {}) => api.boardTop(board, opzioni)\n },\n room\n };\n}\nfunction dispositivoSconosciuto() {\n return {\n webgl2: false,\n webgpu: false,\n wasm: false,\n threads: false,\n isolated: false,\n gpu: "none",\n memoryMb: null,\n cores: null,\n mobile: false,\n tier: "low"\n };\n}\nasync function attendiSonda(sonda) {\n let timer;\n try {\n return await Promise.race([\n Promise.resolve().then(sonda).catch(() => dispositivoSconosciuto()),\n new Promise((resolve) => {\n timer = globalThis.setTimeout(() => resolve(dispositivoSconosciuto()), 1500);\n })\n ]);\n } finally {\n if (timer !== void 0) globalThis.clearTimeout(timer);\n }\n}\nfunction creaKit(input = dipendenzeReali2()) {\n let promessa = null;\n return {\n connect() {\n promessa ?? (promessa = Promise.all([connetti(input), attendiSonda(input.sonda)]).then(([connessione, device]) => ({ ...connessione, device })));\n return promessa;\n }\n };\n}\n\n// src/index.ts\nvar caisual = creaKit();\nglobalThis.caisual = caisual;\nvar index_default = caisual;\nexport {\n caisual,\n index_default as default\n};\n');
|
|
2834
3532
|
return;
|
|
2835
3533
|
}
|
|
2836
3534
|
let decoded;
|
|
@@ -2842,22 +3540,22 @@ var DevService = class {
|
|
|
2842
3540
|
}
|
|
2843
3541
|
const relativePath = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
|
|
2844
3542
|
const candidate = resolve(this.clientRoot, relativePath);
|
|
2845
|
-
if (
|
|
3543
|
+
if (relative2(this.clientRoot, candidate).startsWith(`..${sep}`) || candidate === this.clientRoot) {
|
|
2846
3544
|
sendError(response, new DevHttpError(404, "not_found", "The game file was not found."));
|
|
2847
3545
|
return;
|
|
2848
3546
|
}
|
|
2849
|
-
const real = await
|
|
3547
|
+
const real = await fs2.realpath(candidate).catch(() => null);
|
|
2850
3548
|
if (real === null || real !== this.clientRoot && !real.startsWith(`${this.clientRoot}${sep}`)) {
|
|
2851
3549
|
sendError(response, new DevHttpError(404, "not_found", "The game file was not found."));
|
|
2852
3550
|
return;
|
|
2853
3551
|
}
|
|
2854
|
-
const stat = await
|
|
3552
|
+
const stat = await fs2.stat(real);
|
|
2855
3553
|
if (!stat.isFile()) {
|
|
2856
3554
|
sendError(response, new DevHttpError(404, "not_found", "The game file was not found."));
|
|
2857
3555
|
return;
|
|
2858
3556
|
}
|
|
2859
3557
|
const html = extname(real).toLowerCase() === ".html";
|
|
2860
|
-
const body = html ? Buffer.from(injectAppMeta(await
|
|
3558
|
+
const body = html ? Buffer.from(injectAppMeta(await fs2.readFile(real, "utf8"), this.portalOrigin)) : await fs2.readFile(real);
|
|
2861
3559
|
response.statusCode = 200;
|
|
2862
3560
|
response.setHeader("Content-Type", contentType(real));
|
|
2863
3561
|
response.setHeader("Content-Length", body.byteLength);
|
|
@@ -2907,7 +3605,7 @@ var DevService = class {
|
|
|
2907
3605
|
await this.handleKit(request, response, url);
|
|
2908
3606
|
return;
|
|
2909
3607
|
}
|
|
2910
|
-
if (url.pathname === "/rooms" || url.pathname === "/rooms/join" || /^\/rooms\/[^/]+(?:\/flush)?$/.test(url.pathname)) {
|
|
3608
|
+
if (url.pathname === "/match" || url.pathname === "/rooms" || url.pathname === "/rooms/join" || /^\/rooms\/[^/]+(?:\/flush)?$/.test(url.pathname)) {
|
|
2911
3609
|
await this.handleLive(request, response, url);
|
|
2912
3610
|
return;
|
|
2913
3611
|
}
|
|
@@ -3144,6 +3842,10 @@ var DevService = class {
|
|
|
3144
3842
|
}
|
|
3145
3843
|
const ticket = readServiceTicket(request, this.manifest.id, "live", this.secret);
|
|
3146
3844
|
this.checkRate(this.liveRequests, ticket.sub);
|
|
3845
|
+
if (url.pathname === "/match" && request.method === "POST") {
|
|
3846
|
+
await this.startMatch(request, response, ticket, origin);
|
|
3847
|
+
return;
|
|
3848
|
+
}
|
|
3147
3849
|
if (url.pathname === "/rooms" && request.method === "POST") {
|
|
3148
3850
|
await this.createRoom(request, response, ticket, origin);
|
|
3149
3851
|
return;
|
|
@@ -3199,35 +3901,101 @@ var DevService = class {
|
|
|
3199
3901
|
if (body === null || !Object.hasOwn(body, "mode") || body.mode !== null && typeof body.mode !== "string") {
|
|
3200
3902
|
throw new DevHttpError(400, "invalid_request", "mode must be null or a valid mode name.");
|
|
3201
3903
|
}
|
|
3202
|
-
|
|
3203
|
-
|
|
3904
|
+
let opened;
|
|
3905
|
+
try {
|
|
3906
|
+
opened = await this.openLocalRoom(body.mode, playerFromTicket(ticket));
|
|
3907
|
+
} catch (cause) {
|
|
3908
|
+
if (cause instanceof DevHttpError) throw cause;
|
|
3909
|
+
throw new DevHttpError(
|
|
3910
|
+
400,
|
|
3911
|
+
"invalid_request",
|
|
3912
|
+
cause instanceof Error ? cause.message : "The room request is invalid."
|
|
3913
|
+
);
|
|
3914
|
+
}
|
|
3915
|
+
sendJson(
|
|
3916
|
+
response,
|
|
3917
|
+
this.joinResponse(opened.roomId, opened.localRoom.code, playerFromTicket(ticket)),
|
|
3918
|
+
201,
|
|
3919
|
+
origin
|
|
3920
|
+
);
|
|
3921
|
+
}
|
|
3922
|
+
async startMatch(request, response, ticket, origin) {
|
|
3923
|
+
if (this.definition === null) {
|
|
3924
|
+
throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
|
|
3925
|
+
}
|
|
3926
|
+
const body = object(await readBody(request));
|
|
3927
|
+
if (body === null || !Object.hasOwn(body, "mode") || !Object.hasOwn(body, "key") || Object.keys(body).some((field) => field !== "mode" && field !== "key")) {
|
|
3928
|
+
throw new DevHttpError(400, "invalid_request", "The match request must contain only mode and key.");
|
|
3929
|
+
}
|
|
3930
|
+
if (typeof body.mode !== "string") {
|
|
3931
|
+
throw new DevHttpError(400, "invalid_request", "mode must be a valid mode name.");
|
|
3932
|
+
}
|
|
3933
|
+
const mode = this.manifest.modes.find((item) => item.id === body.mode);
|
|
3934
|
+
if (mode === void 0) {
|
|
3935
|
+
throw new DevHttpError(400, "invalid_request", "The matchmaking mode does not exist.");
|
|
3936
|
+
}
|
|
3937
|
+
if (mode.matchmaking === void 0) {
|
|
3938
|
+
throw new DevHttpError(400, "invalid_request", "This mode does not support matchmaking.");
|
|
3939
|
+
}
|
|
3940
|
+
const key = canonicalMatchKey(body.key, mode.matchmaking.key);
|
|
3941
|
+
const token = matchTicket(
|
|
3942
|
+
playerFromTicket(ticket),
|
|
3943
|
+
ticket.game,
|
|
3944
|
+
mode.id,
|
|
3945
|
+
key,
|
|
3946
|
+
mode.matchmaking,
|
|
3947
|
+
this.manifest.players,
|
|
3948
|
+
this.manifest.lobby,
|
|
3949
|
+
this.secret
|
|
3950
|
+
);
|
|
3951
|
+
sendJson(response, {
|
|
3952
|
+
url: `ws://localhost:${this.port}/match?j=${encodeURIComponent(token)}`,
|
|
3953
|
+
timeoutMs: mode.matchmaking.timeoutMs,
|
|
3954
|
+
players: this.manifest.players
|
|
3955
|
+
}, 200, origin);
|
|
3956
|
+
}
|
|
3957
|
+
roomManifest() {
|
|
3958
|
+
return {
|
|
3204
3959
|
id: this.manifest.id,
|
|
3205
3960
|
players: this.manifest.players,
|
|
3206
3961
|
lobby: this.manifest.lobby,
|
|
3962
|
+
persistent: this.manifest.persistent,
|
|
3207
3963
|
roles: this.manifest.roles,
|
|
3208
3964
|
teams: this.manifest.teams,
|
|
3209
3965
|
modes: this.manifest.modes,
|
|
3210
3966
|
voice: this.manifest.voice
|
|
3211
3967
|
};
|
|
3968
|
+
}
|
|
3969
|
+
async openLocalRoom(mode, creator) {
|
|
3970
|
+
if (this.definition === null) {
|
|
3971
|
+
throw new DevHttpError(409, "no_server", "This game has no multiplayer server.");
|
|
3972
|
+
}
|
|
3973
|
+
const roomId = `g1-1.${randomUniform("abcdefghijklmnopqrstuvwxyz0123456789", 16)}`;
|
|
3212
3974
|
const room = await createNodeRoom(
|
|
3213
3975
|
this.definition,
|
|
3214
|
-
roomManifest,
|
|
3215
|
-
{
|
|
3976
|
+
this.roomManifest(),
|
|
3977
|
+
{
|
|
3978
|
+
storageFile: join2(this.root, ".caisual-dev", "rooms", `${roomId}.json`),
|
|
3979
|
+
deposito: this.deposito
|
|
3980
|
+
}
|
|
3216
3981
|
);
|
|
3217
3982
|
try {
|
|
3218
|
-
await room.create(roomId,
|
|
3983
|
+
const created = await room.create(roomId, mode, creator);
|
|
3984
|
+
if (!created) throw new Error("The room could not be created.");
|
|
3219
3985
|
} catch (cause) {
|
|
3220
3986
|
await room.close();
|
|
3221
|
-
throw
|
|
3222
|
-
400,
|
|
3223
|
-
"invalid_request",
|
|
3224
|
-
cause instanceof Error ? cause.message : "The room request is invalid."
|
|
3225
|
-
);
|
|
3987
|
+
throw cause;
|
|
3226
3988
|
}
|
|
3227
3989
|
const code = this.uniqueCode();
|
|
3228
|
-
|
|
3990
|
+
const localRoom = {
|
|
3991
|
+
code,
|
|
3992
|
+
game: this.manifest.id,
|
|
3993
|
+
room,
|
|
3994
|
+
pendingMatch: /* @__PURE__ */ new Map()
|
|
3995
|
+
};
|
|
3996
|
+
this.rooms.set(roomId, localRoom);
|
|
3229
3997
|
this.roomByCode.set(code, roomId);
|
|
3230
|
-
|
|
3998
|
+
return { roomId, localRoom };
|
|
3231
3999
|
}
|
|
3232
4000
|
async joinRoom(request, response, ticket, origin) {
|
|
3233
4001
|
const body = object(await readBody(request));
|
|
@@ -3256,12 +4024,12 @@ var DevService = class {
|
|
|
3256
4024
|
sendJson(response, this.joinResponse(roomId, localRoom.code, playerFromTicket(ticket)), 200, origin);
|
|
3257
4025
|
}
|
|
3258
4026
|
joinResponse(roomId, code, player) {
|
|
3259
|
-
const
|
|
4027
|
+
const join4 = joinTicket(player, roomId, this.secret);
|
|
3260
4028
|
return {
|
|
3261
4029
|
roomId,
|
|
3262
4030
|
code,
|
|
3263
|
-
join:
|
|
3264
|
-
url: `ws://localhost:${this.port}/rooms/${roomId}?j=${encodeURIComponent(
|
|
4031
|
+
join: join4,
|
|
4032
|
+
url: `ws://localhost:${this.port}/rooms/${roomId}?j=${encodeURIComponent(join4)}`
|
|
3265
4033
|
};
|
|
3266
4034
|
}
|
|
3267
4035
|
uniqueCode() {
|
|
@@ -3294,7 +4062,8 @@ var DevService = class {
|
|
|
3294
4062
|
400: "Bad Request",
|
|
3295
4063
|
401: "Unauthorized",
|
|
3296
4064
|
404: "Not Found",
|
|
3297
|
-
409: "Conflict"
|
|
4065
|
+
409: "Conflict",
|
|
4066
|
+
429: "Too Many Requests"
|
|
3298
4067
|
};
|
|
3299
4068
|
socket.end(
|
|
3300
4069
|
`HTTP/1.1 ${status} ${names[status] ?? "Error"}\r
|
|
@@ -3309,7 +4078,7 @@ Connection: close\r
|
|
|
3309
4078
|
};
|
|
3310
4079
|
async function runDev(options) {
|
|
3311
4080
|
const root = resolve(process.cwd(), options.folder);
|
|
3312
|
-
const stat = await
|
|
4081
|
+
const stat = await fs2.stat(root).catch(() => null);
|
|
3313
4082
|
if (stat === null || !stat.isDirectory()) throw new Error(`The game folder was not found: ${root}`);
|
|
3314
4083
|
const [{ manifest, clientRoot }, definition] = await Promise.all([
|
|
3315
4084
|
readGame(root),
|
|
@@ -3353,6 +4122,143 @@ async function runDev(options) {
|
|
|
3353
4122
|
});
|
|
3354
4123
|
}
|
|
3355
4124
|
|
|
4125
|
+
// src/scan.ts
|
|
4126
|
+
var MASSIMO_BYTE_SCANSIONE = 8e6;
|
|
4127
|
+
var ESTENSIONI_TESTO = /* @__PURE__ */ new Set([".js", ".mjs", ".cjs", ".html"]);
|
|
4128
|
+
function estensione(path) {
|
|
4129
|
+
const indice = path.lastIndexOf(".");
|
|
4130
|
+
return indice < 0 ? "" : path.slice(indice).toLowerCase();
|
|
4131
|
+
}
|
|
4132
|
+
function leggiU32(bytes, cursore, fine) {
|
|
4133
|
+
let risultato = 0;
|
|
4134
|
+
for (let giro = 0; giro < 5; giro += 1) {
|
|
4135
|
+
if (cursore.posizione >= fine) throw new Error("leb incompleto");
|
|
4136
|
+
const byte = bytes[cursore.posizione++];
|
|
4137
|
+
if (giro === 4 && (byte & 240) !== 0) throw new Error("leb fuori limite");
|
|
4138
|
+
risultato += (byte & 127) * 2 ** (giro * 7);
|
|
4139
|
+
if ((byte & 128) === 0) return risultato;
|
|
4140
|
+
}
|
|
4141
|
+
throw new Error("leb troppo lungo");
|
|
4142
|
+
}
|
|
4143
|
+
function saltaNome(bytes, cursore, fine) {
|
|
4144
|
+
const lunghezza = leggiU32(bytes, cursore, fine);
|
|
4145
|
+
if (cursore.posizione + lunghezza > fine) throw new Error("nome incompleto");
|
|
4146
|
+
cursore.posizione += lunghezza;
|
|
4147
|
+
}
|
|
4148
|
+
function leggiLimits(bytes, cursore, fine) {
|
|
4149
|
+
if (cursore.posizione >= fine) throw new Error("limits assenti");
|
|
4150
|
+
const flags = bytes[cursore.posizione++];
|
|
4151
|
+
if (flags > 3 || flags === 2) throw new Error("limits non validi");
|
|
4152
|
+
leggiU32(bytes, cursore, fine);
|
|
4153
|
+
if ((flags & 1) !== 0) leggiU32(bytes, cursore, fine);
|
|
4154
|
+
return flags === 3;
|
|
4155
|
+
}
|
|
4156
|
+
function memoriaImportataCondivisa(bytes, inizio, fine) {
|
|
4157
|
+
const cursore = { posizione: inizio };
|
|
4158
|
+
const totale = leggiU32(bytes, cursore, fine);
|
|
4159
|
+
let condivisa = false;
|
|
4160
|
+
for (let indice = 0; indice < totale; indice += 1) {
|
|
4161
|
+
saltaNome(bytes, cursore, fine);
|
|
4162
|
+
saltaNome(bytes, cursore, fine);
|
|
4163
|
+
if (cursore.posizione >= fine) throw new Error("descrittore import assente");
|
|
4164
|
+
const tipo = bytes[cursore.posizione++];
|
|
4165
|
+
if (tipo === 0) leggiU32(bytes, cursore, fine);
|
|
4166
|
+
else if (tipo === 1) {
|
|
4167
|
+
if (cursore.posizione >= fine) throw new Error("tabella incompleta");
|
|
4168
|
+
cursore.posizione += 1;
|
|
4169
|
+
leggiLimits(bytes, cursore, fine);
|
|
4170
|
+
} else if (tipo === 2) condivisa = leggiLimits(bytes, cursore, fine) || condivisa;
|
|
4171
|
+
else if (tipo === 3) {
|
|
4172
|
+
if (cursore.posizione + 2 > fine) throw new Error("globale incompleta");
|
|
4173
|
+
cursore.posizione += 2;
|
|
4174
|
+
} else if (tipo === 4) {
|
|
4175
|
+
if (cursore.posizione >= fine) throw new Error("tag incompleto");
|
|
4176
|
+
cursore.posizione += 1;
|
|
4177
|
+
leggiU32(bytes, cursore, fine);
|
|
4178
|
+
} else throw new Error("descrittore import sconosciuto");
|
|
4179
|
+
}
|
|
4180
|
+
if (cursore.posizione !== fine) throw new Error("sezione import non consumata");
|
|
4181
|
+
return condivisa;
|
|
4182
|
+
}
|
|
4183
|
+
function memoriaDefinitaCondivisa(bytes, inizio, fine) {
|
|
4184
|
+
const cursore = { posizione: inizio };
|
|
4185
|
+
const totale = leggiU32(bytes, cursore, fine);
|
|
4186
|
+
let condivisa = false;
|
|
4187
|
+
for (let indice = 0; indice < totale; indice += 1) {
|
|
4188
|
+
condivisa = leggiLimits(bytes, cursore, fine) || condivisa;
|
|
4189
|
+
}
|
|
4190
|
+
if (cursore.posizione !== fine) throw new Error("sezione memory non consumata");
|
|
4191
|
+
return condivisa;
|
|
4192
|
+
}
|
|
4193
|
+
function usaMemoriaCondivisa(bytes) {
|
|
4194
|
+
try {
|
|
4195
|
+
const intestazione = [0, 97, 115, 109, 1, 0, 0, 0];
|
|
4196
|
+
if (bytes.length < intestazione.length || intestazione.some((byte, indice) => bytes[indice] !== byte)) {
|
|
4197
|
+
return false;
|
|
4198
|
+
}
|
|
4199
|
+
const cursore = { posizione: intestazione.length };
|
|
4200
|
+
let condivisa = false;
|
|
4201
|
+
while (cursore.posizione < bytes.length) {
|
|
4202
|
+
const id = bytes[cursore.posizione++];
|
|
4203
|
+
const dimensione = leggiU32(bytes, cursore, bytes.length);
|
|
4204
|
+
const fine = cursore.posizione + dimensione;
|
|
4205
|
+
if (fine > bytes.length) throw new Error("sezione incompleta");
|
|
4206
|
+
if (id === 2) condivisa = memoriaImportataCondivisa(bytes, cursore.posizione, fine) || condivisa;
|
|
4207
|
+
if (id === 5) condivisa = memoriaDefinitaCondivisa(bytes, cursore.posizione, fine) || condivisa;
|
|
4208
|
+
cursore.posizione = fine;
|
|
4209
|
+
}
|
|
4210
|
+
return condivisa;
|
|
4211
|
+
} catch {
|
|
4212
|
+
return false;
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
function avviso(path, nome, campo) {
|
|
4216
|
+
return `client/${path} seems to use ${nome} but caisual.json does not declare requires.${campo}. Players on devices without it will not be warned.`;
|
|
4217
|
+
}
|
|
4218
|
+
async function scanClient(files, manifest) {
|
|
4219
|
+
const primi = {};
|
|
4220
|
+
const decoder = new TextDecoder();
|
|
4221
|
+
for (const file of files) {
|
|
4222
|
+
const tipo = estensione(file.path);
|
|
4223
|
+
if (!ESTENSIONI_TESTO.has(tipo) && tipo !== ".wasm" || file.bytes > MASSIMO_BYTE_SCANSIONE) continue;
|
|
4224
|
+
let bytes;
|
|
4225
|
+
try {
|
|
4226
|
+
bytes = await file.read();
|
|
4227
|
+
} catch {
|
|
4228
|
+
continue;
|
|
4229
|
+
}
|
|
4230
|
+
if (tipo === ".wasm") {
|
|
4231
|
+
primi.wasm ??= file.path;
|
|
4232
|
+
if (primi.threads === void 0 && usaMemoriaCondivisa(bytes)) primi.threads = file.path;
|
|
4233
|
+
continue;
|
|
4234
|
+
}
|
|
4235
|
+
const source = decoder.decode(bytes);
|
|
4236
|
+
if (primi.webgl2 === void 0 && /getContext\s*\(\s*(["'`])webgl2\1/.test(source)) {
|
|
4237
|
+
primi.webgl2 = file.path;
|
|
4238
|
+
}
|
|
4239
|
+
if (primi.webgpu === void 0 && (/navigator\s*\.\s*gpu\b/.test(source) || /requestAdapter\s*\(/.test(source) || /getContext\s*\(\s*(["'`])webgpu\1/.test(source))) primi.webgpu = file.path;
|
|
4240
|
+
if (primi.wasm === void 0 && /WebAssembly\s*\.\s*(?:instantiate|compile)(?:Streaming)?\s*\(/.test(source)) {
|
|
4241
|
+
primi.wasm = file.path;
|
|
4242
|
+
}
|
|
4243
|
+
if (primi.threads === void 0 && (/\bSharedArrayBuffer\b/.test(source) || /\bAtomics\s*\.\s*wait\s*\(/.test(source))) primi.threads = file.path;
|
|
4244
|
+
}
|
|
4245
|
+
const warnings = [];
|
|
4246
|
+
const nomi = {
|
|
4247
|
+
webgl2: "WebGL2",
|
|
4248
|
+
webgpu: "WebGPU",
|
|
4249
|
+
wasm: "WebAssembly",
|
|
4250
|
+
threads: "shared memory"
|
|
4251
|
+
};
|
|
4252
|
+
for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
|
|
4253
|
+
const path = primi[campo];
|
|
4254
|
+
if (path !== void 0 && !manifest.requires[campo]) warnings.push(avviso(path, nomi[campo], campo));
|
|
4255
|
+
}
|
|
4256
|
+
if (primi.threads !== void 0 && !manifest.isolated) {
|
|
4257
|
+
warnings.push(`client/${primi.threads} seems to use shared memory but caisual.json does not set isolated: true. Shared memory will not be available.`);
|
|
4258
|
+
}
|
|
4259
|
+
return warnings;
|
|
4260
|
+
}
|
|
4261
|
+
|
|
3356
4262
|
// src/caisual.ts
|
|
3357
4263
|
var DEFAULT_ORIGIN = "https://caisual.com";
|
|
3358
4264
|
var MAX_FILE_BYTES = 5e7;
|
|
@@ -3360,14 +4266,6 @@ var MAX_VERSION_BYTES = 2e8;
|
|
|
3360
4266
|
var MAX_FILES = 2e3;
|
|
3361
4267
|
var UPLOAD_CONCURRENCY = 4;
|
|
3362
4268
|
var MAX_RETRIES = 3;
|
|
3363
|
-
var CliError = class extends Error {
|
|
3364
|
-
constructor(exitCode, message) {
|
|
3365
|
-
super(message);
|
|
3366
|
-
this.exitCode = exitCode;
|
|
3367
|
-
this.name = "CliError";
|
|
3368
|
-
}
|
|
3369
|
-
exitCode;
|
|
3370
|
-
};
|
|
3371
4269
|
var ApiError = class extends Error {
|
|
3372
4270
|
constructor(status, code, message, hints) {
|
|
3373
4271
|
super(message);
|
|
@@ -3381,7 +4279,7 @@ var ApiError = class extends Error {
|
|
|
3381
4279
|
hints;
|
|
3382
4280
|
};
|
|
3383
4281
|
function help() {
|
|
3384
|
-
return `Caisual ${"0.
|
|
4282
|
+
return `Caisual ${"0.4.0"}
|
|
3385
4283
|
|
|
3386
4284
|
Usage:
|
|
3387
4285
|
caisual init [--multiplayer] [folder]
|
|
@@ -3408,7 +4306,7 @@ function displayName(folderName) {
|
|
|
3408
4306
|
}
|
|
3409
4307
|
async function writeNewFile(path, content) {
|
|
3410
4308
|
try {
|
|
3411
|
-
await
|
|
4309
|
+
await fs3.writeFile(path, content, { encoding: "utf8", flag: "wx" });
|
|
3412
4310
|
return true;
|
|
3413
4311
|
} catch (error) {
|
|
3414
4312
|
if (error.code === "EEXIST") return false;
|
|
@@ -3418,7 +4316,7 @@ async function writeNewFile(path, content) {
|
|
|
3418
4316
|
async function init(folderArgument, multiplayer) {
|
|
3419
4317
|
const root = resolve2(process.cwd(), folderArgument);
|
|
3420
4318
|
try {
|
|
3421
|
-
await
|
|
4319
|
+
await fs3.mkdir(join3(root, "client"), { recursive: true });
|
|
3422
4320
|
} catch {
|
|
3423
4321
|
throw new CliError(2, `The game folder could not be created: ${root}`);
|
|
3424
4322
|
}
|
|
@@ -3430,8 +4328,8 @@ async function init(folderArgument, multiplayer) {
|
|
|
3430
4328
|
platform: "both",
|
|
3431
4329
|
...multiplayer ? { players: { min: 1, max: 4 }, lobby: true, voice: "room" } : {}
|
|
3432
4330
|
};
|
|
3433
|
-
const manifestPath =
|
|
3434
|
-
const indexPath =
|
|
4331
|
+
const manifestPath = join3(root, "caisual.json");
|
|
4332
|
+
const indexPath = join3(root, "client", "index.html");
|
|
3435
4333
|
const singlePlayerIndex = `<!doctype html>
|
|
3436
4334
|
<html lang="en">
|
|
3437
4335
|
<head>
|
|
@@ -3552,7 +4450,7 @@ export default defineGame({
|
|
|
3552
4450
|
process.stdout.write(`${indexCreated ? "Created" : "Kept"} ${indexPath}
|
|
3553
4451
|
`);
|
|
3554
4452
|
if (multiplayer) {
|
|
3555
|
-
const serverPath =
|
|
4453
|
+
const serverPath = join3(root, "server.js");
|
|
3556
4454
|
const serverCreated = await writeNewFile(serverPath, server);
|
|
3557
4455
|
process.stdout.write(`${serverCreated ? "Created" : "Kept"} ${serverPath}
|
|
3558
4456
|
`);
|
|
@@ -3583,19 +4481,19 @@ async function mapLimited(items, limit, operation) {
|
|
|
3583
4481
|
async function listClientFiles(clientRoot) {
|
|
3584
4482
|
let rootStat;
|
|
3585
4483
|
try {
|
|
3586
|
-
rootStat = await
|
|
4484
|
+
rootStat = await fs3.stat(clientRoot);
|
|
3587
4485
|
} catch {
|
|
3588
4486
|
throw new CliError(2, "client/: folder not found.");
|
|
3589
4487
|
}
|
|
3590
4488
|
if (!rootStat.isDirectory()) throw new CliError(2, "client/: must be a folder.");
|
|
3591
4489
|
const found = [];
|
|
3592
4490
|
async function visit(folder, prefix) {
|
|
3593
|
-
const entries = await
|
|
4491
|
+
const entries = await fs3.readdir(folder, { withFileTypes: true });
|
|
3594
4492
|
entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
3595
4493
|
for (const entry of entries) {
|
|
3596
4494
|
if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
3597
4495
|
const relativePath = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
3598
|
-
const absolutePath =
|
|
4496
|
+
const absolutePath = join3(folder, entry.name);
|
|
3599
4497
|
if (entry.isDirectory()) {
|
|
3600
4498
|
await visit(absolutePath, relativePath);
|
|
3601
4499
|
continue;
|
|
@@ -3603,7 +4501,7 @@ async function listClientFiles(clientRoot) {
|
|
|
3603
4501
|
if (!entry.isFile()) {
|
|
3604
4502
|
throw new CliError(2, `${relativePath}: only regular files are supported.`);
|
|
3605
4503
|
}
|
|
3606
|
-
const fileStat = await
|
|
4504
|
+
const fileStat = await fs3.stat(absolutePath);
|
|
3607
4505
|
if (fileStat.size > MAX_FILE_BYTES) {
|
|
3608
4506
|
throw new CliError(2, `${relativePath}: file is larger than 50 MB (${fileStat.size} bytes).`);
|
|
3609
4507
|
}
|
|
@@ -3623,36 +4521,54 @@ async function listClientFiles(clientRoot) {
|
|
|
3623
4521
|
}
|
|
3624
4522
|
return await mapLimited(found, UPLOAD_CONCURRENCY, async (file) => ({
|
|
3625
4523
|
...file,
|
|
3626
|
-
sha256: await sha256(file.absolutePath)
|
|
4524
|
+
sha256: await sha256(file.absolutePath),
|
|
4525
|
+
read: () => fs3.readFile(file.absolutePath)
|
|
3627
4526
|
}));
|
|
3628
4527
|
}
|
|
3629
4528
|
async function readServerFile(root) {
|
|
3630
|
-
const absolutePath =
|
|
4529
|
+
const absolutePath = join3(root, "server.js");
|
|
3631
4530
|
let stat;
|
|
3632
4531
|
try {
|
|
3633
|
-
stat = await
|
|
4532
|
+
stat = await fs3.lstat(absolutePath);
|
|
3634
4533
|
} catch (error) {
|
|
3635
|
-
if (error.code === "ENOENT")
|
|
4534
|
+
if (error.code === "ENOENT") {
|
|
4535
|
+
return { file: null, temporaryDirectory: null };
|
|
4536
|
+
}
|
|
3636
4537
|
throw new CliError(2, "server.js: file not readable.");
|
|
3637
4538
|
}
|
|
3638
4539
|
if (!stat.isFile()) throw new CliError(2, "server.js: must be a regular file.");
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
4540
|
+
const result = await bundleServer(root);
|
|
4541
|
+
if (!result.bundled) {
|
|
4542
|
+
return {
|
|
4543
|
+
file: {
|
|
4544
|
+
path: "server.js",
|
|
4545
|
+
absolutePath,
|
|
4546
|
+
bytes: stat.size,
|
|
4547
|
+
sha256: await sha256(absolutePath)
|
|
4548
|
+
},
|
|
4549
|
+
temporaryDirectory: null
|
|
4550
|
+
};
|
|
3644
4551
|
}
|
|
3645
|
-
const
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
4552
|
+
const temporaryDirectory = await fs3.mkdtemp(join3(tmpdir(), "caisual-server-"));
|
|
4553
|
+
const bundledPath = join3(temporaryDirectory, "server.js");
|
|
4554
|
+
try {
|
|
4555
|
+
await fs3.writeFile(bundledPath, result.source, "utf8");
|
|
4556
|
+
const bytes = Buffer.byteLength(result.source);
|
|
4557
|
+
process.stdout.write(`Bundling server.js (${Math.ceil(bytes / 1e3)} KB).
|
|
4558
|
+
`);
|
|
4559
|
+
return {
|
|
4560
|
+
file: {
|
|
4561
|
+
path: "server.js",
|
|
4562
|
+
absolutePath: bundledPath,
|
|
4563
|
+
bytes,
|
|
4564
|
+
sha256: await sha256(bundledPath)
|
|
4565
|
+
},
|
|
4566
|
+
temporaryDirectory
|
|
4567
|
+
};
|
|
4568
|
+
} catch (error) {
|
|
4569
|
+
await fs3.rm(temporaryDirectory, { recursive: true, force: true });
|
|
4570
|
+
throw error;
|
|
3649
4571
|
}
|
|
3650
|
-
return {
|
|
3651
|
-
path: "server.js",
|
|
3652
|
-
absolutePath,
|
|
3653
|
-
bytes: stat.size,
|
|
3654
|
-
sha256: await sha256(absolutePath)
|
|
3655
|
-
};
|
|
3656
4572
|
}
|
|
3657
4573
|
function portalOrigin() {
|
|
3658
4574
|
const raw = process.env.CAISUAL_ORIGIN?.trim() || DEFAULT_ORIGIN;
|
|
@@ -3849,10 +4765,10 @@ function parseUploads(payload, files, server) {
|
|
|
3849
4765
|
};
|
|
3850
4766
|
}
|
|
3851
4767
|
async function readManifest(root) {
|
|
3852
|
-
const path =
|
|
4768
|
+
const path = join3(root, "caisual.json");
|
|
3853
4769
|
let source;
|
|
3854
4770
|
try {
|
|
3855
|
-
source = await
|
|
4771
|
+
source = await fs3.readFile(path, "utf8");
|
|
3856
4772
|
} catch {
|
|
3857
4773
|
throw new CliError(2, "caisual.json: file not found or unreadable.");
|
|
3858
4774
|
}
|
|
@@ -3873,79 +4789,88 @@ async function publish(folderArgument) {
|
|
|
3873
4789
|
const root = resolve2(process.cwd(), folderArgument);
|
|
3874
4790
|
let rootStat;
|
|
3875
4791
|
try {
|
|
3876
|
-
rootStat = await
|
|
4792
|
+
rootStat = await fs3.stat(root);
|
|
3877
4793
|
} catch {
|
|
3878
4794
|
throw new CliError(2, `The game folder was not found: ${root}`);
|
|
3879
4795
|
}
|
|
3880
4796
|
if (!rootStat.isDirectory()) throw new CliError(2, `The game path is not a folder: ${root}`);
|
|
3881
4797
|
const manifest = await readManifest(root);
|
|
3882
|
-
const
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
const filePaths = new Set(files.map((file) => file.path));
|
|
3887
|
-
for (const required of [manifest.cover, ...manifest.screenshots]) {
|
|
3888
|
-
if (required !== null && !filePaths.has(required)) {
|
|
3889
|
-
throw new CliError(2, `caisual.json: referenced file not found in client/: ${required}`);
|
|
3890
|
-
}
|
|
3891
|
-
}
|
|
3892
|
-
const key = process.env.CAISUAL_KEY?.trim();
|
|
3893
|
-
if (!key) {
|
|
3894
|
-
throw new CliError(3, "CAISUAL_KEY is required. Set it with: export CAISUAL_KEY=ck_...");
|
|
4798
|
+
const files = await listClientFiles(join3(root, "client"));
|
|
4799
|
+
for (const warning of await scanClient(files, manifest)) {
|
|
4800
|
+
process.stderr.write(`Warning: ${warning}
|
|
4801
|
+
`);
|
|
3895
4802
|
}
|
|
3896
|
-
const
|
|
3897
|
-
const
|
|
3898
|
-
|
|
3899
|
-
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
4803
|
+
const serverResult = await readServerFile(root);
|
|
4804
|
+
const server = serverResult.file;
|
|
4805
|
+
try {
|
|
4806
|
+
const filePaths = new Set(files.map((file) => file.path));
|
|
4807
|
+
for (const required of [manifest.cover, ...manifest.screenshots]) {
|
|
4808
|
+
if (required !== null && !filePaths.has(required)) {
|
|
4809
|
+
throw new CliError(2, `caisual.json: referenced file not found in client/: ${required}`);
|
|
4810
|
+
}
|
|
4811
|
+
}
|
|
4812
|
+
const key = process.env.CAISUAL_KEY?.trim();
|
|
4813
|
+
if (!key) {
|
|
4814
|
+
throw new CliError(3, "CAISUAL_KEY is required. Set it with: export CAISUAL_KEY=ck_...");
|
|
4815
|
+
}
|
|
4816
|
+
const origin = portalOrigin();
|
|
4817
|
+
const declared = files.map(({ path, bytes, sha256: digest }) => ({
|
|
4818
|
+
path,
|
|
4819
|
+
bytes,
|
|
4820
|
+
sha256: digest
|
|
4821
|
+
}));
|
|
4822
|
+
process.stdout.write(
|
|
4823
|
+
`Preparing ${files.length} client file${files.length === 1 ? "" : "s"}${server === null ? "" : " and server.js"}.
|
|
3904
4824
|
`
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
3912
|
-
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
});
|
|
3920
|
-
const version = parseUploads(opened, files, server);
|
|
3921
|
-
const caricamenti = files.map((file, index) => ({
|
|
3922
|
-
file,
|
|
3923
|
-
target: version.targets[index]
|
|
3924
|
-
}));
|
|
3925
|
-
if (server !== null && version.serverTarget !== null) {
|
|
3926
|
-
caricamenti.push({
|
|
3927
|
-
file: server,
|
|
3928
|
-
target: { path: "server.js", ...version.serverTarget }
|
|
4825
|
+
);
|
|
4826
|
+
const opened = await requestJson(`${origin}/api/versions`, {
|
|
4827
|
+
method: "POST",
|
|
4828
|
+
headers: {
|
|
4829
|
+
Authorization: `Bearer ${key}`,
|
|
4830
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
4831
|
+
},
|
|
4832
|
+
body: JSON.stringify({
|
|
4833
|
+
manifest,
|
|
4834
|
+
files: declared,
|
|
4835
|
+
...server === null ? {} : {
|
|
4836
|
+
server: { bytes: server.bytes, sha256: server.sha256 }
|
|
4837
|
+
}
|
|
4838
|
+
})
|
|
3929
4839
|
});
|
|
3930
|
-
|
|
3931
|
-
|
|
3932
|
-
|
|
3933
|
-
|
|
3934
|
-
|
|
3935
|
-
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
4840
|
+
const version = parseUploads(opened, files, server);
|
|
4841
|
+
const caricamenti = files.map((file, index) => ({
|
|
4842
|
+
file,
|
|
4843
|
+
target: version.targets[index]
|
|
4844
|
+
}));
|
|
4845
|
+
if (server !== null && version.serverTarget !== null) {
|
|
4846
|
+
caricamenti.push({
|
|
4847
|
+
file: server,
|
|
4848
|
+
target: { path: "server.js", ...version.serverTarget }
|
|
4849
|
+
});
|
|
4850
|
+
}
|
|
4851
|
+
await mapLimited(caricamenti, UPLOAD_CONCURRENCY, async ({ file, target }) => {
|
|
4852
|
+
await uploadFile(file, target, key, origin);
|
|
4853
|
+
});
|
|
4854
|
+
const completed = await requestJson(`${origin}/api/versions/${version.versionId}/complete`, {
|
|
4855
|
+
method: "POST",
|
|
4856
|
+
headers: { Authorization: `Bearer ${key}` }
|
|
4857
|
+
});
|
|
4858
|
+
if (typeof completed.url !== "string") {
|
|
4859
|
+
throw new CliError(1, "The portal completed the version without returning the game URL.");
|
|
4860
|
+
}
|
|
4861
|
+
if (version.n !== null) process.stdout.write(`Published version ${version.n}.
|
|
3942
4862
|
`);
|
|
3943
|
-
|
|
4863
|
+
process.stdout.write(`${completed.url}
|
|
3944
4864
|
`);
|
|
4865
|
+
} finally {
|
|
4866
|
+
if (serverResult.temporaryDirectory !== null) {
|
|
4867
|
+
await fs3.rm(serverResult.temporaryDirectory, { recursive: true, force: true });
|
|
4868
|
+
}
|
|
4869
|
+
}
|
|
3945
4870
|
}
|
|
3946
4871
|
async function installSkill() {
|
|
3947
4872
|
const root = process.cwd();
|
|
3948
|
-
const skillPath =
|
|
4873
|
+
const skillPath = join3(root, ".claude", "skills", "caisual", "SKILL.md");
|
|
3949
4874
|
const skill = `---
|
|
3950
4875
|
name: caisual
|
|
3951
4876
|
description: Create and publish a browser game on Caisual, with player identity, cloud saves, leaderboards and a daily challenge.
|
|
@@ -3955,25 +4880,25 @@ ${publish_default.trim()}
|
|
|
3955
4880
|
|
|
3956
4881
|
${kit_default.trim()}
|
|
3957
4882
|
`;
|
|
3958
|
-
await
|
|
4883
|
+
await fs3.mkdir(join3(root, ".claude", "skills", "caisual"), { recursive: true });
|
|
3959
4884
|
let currentSkill = null;
|
|
3960
4885
|
try {
|
|
3961
|
-
currentSkill = await
|
|
4886
|
+
currentSkill = await fs3.readFile(skillPath, "utf8");
|
|
3962
4887
|
} catch (error) {
|
|
3963
4888
|
if (error.code !== "ENOENT") throw error;
|
|
3964
4889
|
}
|
|
3965
|
-
if (currentSkill !== skill) await
|
|
3966
|
-
const agentsPath =
|
|
4890
|
+
if (currentSkill !== skill) await fs3.writeFile(skillPath, skill, "utf8");
|
|
4891
|
+
const agentsPath = join3(root, "AGENTS.md");
|
|
3967
4892
|
let agents = "";
|
|
3968
4893
|
try {
|
|
3969
|
-
agents = await
|
|
4894
|
+
agents = await fs3.readFile(agentsPath, "utf8");
|
|
3970
4895
|
} catch (error) {
|
|
3971
4896
|
if (error.code !== "ENOENT") throw error;
|
|
3972
4897
|
}
|
|
3973
4898
|
if (!/^## Caisual\s*$/m.test(agents)) {
|
|
3974
4899
|
const section = "## Caisual\nRead `.claude/skills/caisual/SKILL.md` before creating or publishing a Caisual game.\nUse the current guides at https://caisual.com/publish.md and https://caisual.com/kit.md.\n";
|
|
3975
4900
|
const separator = agents === "" ? "" : agents.endsWith("\n\n") ? "" : agents.endsWith("\n") ? "\n" : "\n\n";
|
|
3976
|
-
await
|
|
4901
|
+
await fs3.writeFile(agentsPath, `${agents}${separator}${section}`, "utf8");
|
|
3977
4902
|
}
|
|
3978
4903
|
process.stdout.write(`Installed ${skillPath}
|
|
3979
4904
|
`);
|
|
@@ -3985,7 +4910,7 @@ async function run(argumentsList) {
|
|
|
3985
4910
|
return;
|
|
3986
4911
|
}
|
|
3987
4912
|
if (command === "--version" || command === "-V") {
|
|
3988
|
-
process.stdout.write(`${"0.
|
|
4913
|
+
process.stdout.write(`${"0.4.0"}
|
|
3989
4914
|
`);
|
|
3990
4915
|
return;
|
|
3991
4916
|
}
|