@caisual/cli 0.24.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/caisual.mjs +233 -404
- package/package.json +3 -2
package/dist/caisual.mjs
CHANGED
|
@@ -35,9 +35,8 @@ var NOMI_RISERVATI = [
|
|
|
35
35
|
];
|
|
36
36
|
var RISERVATI = new Set(NOMI_RISERVATI);
|
|
37
37
|
var SLUG_NUOVO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
38
|
-
var SLUG_STORICO = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
39
38
|
function isValidSlug(value) {
|
|
40
|
-
return value.length >= 3 && value.length <= 32 && SLUG_NUOVO.test(value)
|
|
39
|
+
return value.length >= 3 && value.length <= 32 && SLUG_NUOVO.test(value);
|
|
41
40
|
}
|
|
42
41
|
function isReservedSlug(value) {
|
|
43
42
|
return RISERVATI.has(value);
|
|
@@ -53,7 +52,7 @@ function normalizeLanguage(value) {
|
|
|
53
52
|
}
|
|
54
53
|
}
|
|
55
54
|
function manifestLanguages(manifest) {
|
|
56
|
-
return
|
|
55
|
+
return [...manifest.languages ?? []];
|
|
57
56
|
}
|
|
58
57
|
function languageFallbacks(language, defaultLanguage = "en") {
|
|
59
58
|
const result = [];
|
|
@@ -98,10 +97,6 @@ function modalitaLocale(manifest, mode) {
|
|
|
98
97
|
var SINGLE_PLAYER_RULE = "Single player runs in the browser and never touches the server; a room exists only for two or more players.";
|
|
99
98
|
var MODE_LOCAL_MESSAGE = "Single-player modes run in the browser and have no room.";
|
|
100
99
|
var AVVISO_SERVER_INUTILE = "server.js is unnecessary: all modes run in the browser.";
|
|
101
|
-
var AVVISO_ISOLATED = "isolated has no effect: games run inside the portal page, which is not cross-origin isolated";
|
|
102
|
-
function avvisiManifest(value) {
|
|
103
|
-
return typeof value === "object" && value !== null && Object.hasOwn(value, "isolated") ? [AVVISO_ISOLATED] : [];
|
|
104
|
-
}
|
|
105
100
|
var TETTO_GIOCATORI = 24;
|
|
106
101
|
var CAMPI = /* @__PURE__ */ new Set([
|
|
107
102
|
"manifest",
|
|
@@ -114,13 +109,11 @@ var CAMPI = /* @__PURE__ */ new Set([
|
|
|
114
109
|
"screenshots",
|
|
115
110
|
"tags",
|
|
116
111
|
"languages",
|
|
117
|
-
"language",
|
|
118
112
|
"platform",
|
|
119
113
|
"orientation",
|
|
120
114
|
"input",
|
|
121
115
|
"visibility",
|
|
122
116
|
"network",
|
|
123
|
-
"isolated",
|
|
124
117
|
"requires",
|
|
125
118
|
"players",
|
|
126
119
|
"persistent",
|
|
@@ -129,10 +122,6 @@ var CAMPI = /* @__PURE__ */ new Set([
|
|
|
129
122
|
"voice",
|
|
130
123
|
"modes"
|
|
131
124
|
]);
|
|
132
|
-
var CAMPI_RIMOSSI = /* @__PURE__ */ new Set(["overlay", "replays", "boards", "lobby"]);
|
|
133
|
-
var MOTIVO_LOBBY = "rooms opened by a player always have a lobby; matchmaking rooms never do";
|
|
134
|
-
var MOTIVO_MATCHMAKING = "the matchmaking object no longer exists; use matchmaking: true.";
|
|
135
|
-
var MOTIVO_RIMOSSO = "this field no longer exists.";
|
|
136
125
|
var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
|
|
137
126
|
var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
|
|
138
127
|
var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
|
|
@@ -208,19 +197,11 @@ function testoFacoltativo(value, key, max, path, errors, sottotitolo = false) {
|
|
|
208
197
|
return result;
|
|
209
198
|
}
|
|
210
199
|
function validaManifest(valore) {
|
|
211
|
-
return validaDocumentoManifest(valore, false);
|
|
212
|
-
}
|
|
213
|
-
function validaManifestPubblicazione(valore) {
|
|
214
|
-
return validaDocumentoManifest(valore, true);
|
|
215
|
-
}
|
|
216
|
-
function validaDocumentoManifest(valore, pubblicazione) {
|
|
217
200
|
const errori = [];
|
|
218
201
|
const dati = oggetto(valore);
|
|
219
202
|
if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
|
|
220
203
|
for (const campo of Object.keys(dati)) {
|
|
221
|
-
if (
|
|
222
|
-
if (pubblicazione) errori.push(`${campo}: ${campo === "lobby" ? MOTIVO_LOBBY : MOTIVO_RIMOSSO}`);
|
|
223
|
-
} else if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
|
|
204
|
+
if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
|
|
224
205
|
}
|
|
225
206
|
if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
|
|
226
207
|
else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
|
|
@@ -228,7 +209,7 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
228
209
|
if (dati.id === void 0) errori.push("id: is required.");
|
|
229
210
|
else if (typeof dati.id === "string") {
|
|
230
211
|
if (!isValidSlug(id)) {
|
|
231
|
-
errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens
|
|
212
|
+
errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens.");
|
|
232
213
|
} else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");
|
|
233
214
|
}
|
|
234
215
|
const name = stringaDefault(dati, "name", "", errori);
|
|
@@ -236,7 +217,7 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
236
217
|
else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
|
|
237
218
|
errori.push("name: must contain 1-60 characters.");
|
|
238
219
|
}
|
|
239
|
-
const description = dati.description === "" ? "" : testoFacoltativo(dati, "description",
|
|
220
|
+
const description = dati.description === "" ? "" : testoFacoltativo(dati, "description", 80, "", errori, true) ?? "";
|
|
240
221
|
const immagini = { cover: "", card: "", icon: "" };
|
|
241
222
|
const usati = /* @__PURE__ */ new Set();
|
|
242
223
|
for (const campo of ["cover", "card", "icon"]) {
|
|
@@ -276,10 +257,6 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
276
257
|
}
|
|
277
258
|
}
|
|
278
259
|
}
|
|
279
|
-
const legacyLanguage = stringaDefault(dati, "language", "en", errori);
|
|
280
|
-
if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {
|
|
281
|
-
errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
|
|
282
|
-
}
|
|
283
260
|
const languages = [];
|
|
284
261
|
if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
|
|
285
262
|
errori.push("languages: must be a non-empty array of BCP 47 language tags.");
|
|
@@ -290,15 +267,11 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
290
267
|
else languages.push(tag);
|
|
291
268
|
}
|
|
292
269
|
if (!languages.includes("en")) errori.push("languages: English is always required alongside the game's own languages.");
|
|
293
|
-
const language = languages[0] ?? legacyLanguage;
|
|
294
270
|
if (typeof description === "object") {
|
|
295
271
|
for (const tag of Object.keys(description)) {
|
|
296
272
|
if (!languages.includes(tag)) errori.push(`description.${tag}: language must be declared in languages.`);
|
|
297
273
|
}
|
|
298
274
|
}
|
|
299
|
-
if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
|
|
300
|
-
errori.push("language: must match the first entry in languages when both are present.");
|
|
301
|
-
}
|
|
302
275
|
let platform = "both";
|
|
303
276
|
if (dati.platform === void 0) errori.push("platform: is required.");
|
|
304
277
|
else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
|
|
@@ -336,9 +309,6 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
336
309
|
else network.push(value);
|
|
337
310
|
}
|
|
338
311
|
}
|
|
339
|
-
if (dati.isolated !== void 0) {
|
|
340
|
-
if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
|
|
341
|
-
}
|
|
342
312
|
const requires = {
|
|
343
313
|
webgl2: false,
|
|
344
314
|
webgpu: false,
|
|
@@ -406,9 +376,7 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
406
376
|
continue;
|
|
407
377
|
}
|
|
408
378
|
for (const campo of Object.keys(value)) {
|
|
409
|
-
if (
|
|
410
|
-
if (pubblicazione) errori.push(`roles[${indice}].label: ${MOTIVO_RIMOSSO}`);
|
|
411
|
-
} else if (!["id", "min", "max"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
|
|
379
|
+
if (!["id", "min", "max"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
|
|
412
380
|
}
|
|
413
381
|
const idRuolo = value.id;
|
|
414
382
|
const min = value.min;
|
|
@@ -475,9 +443,7 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
475
443
|
continue;
|
|
476
444
|
}
|
|
477
445
|
for (const campo of Object.keys(value)) {
|
|
478
|
-
if (
|
|
479
|
-
if (pubblicazione) errori.push(`modes[${indice}].${campo}: ${MOTIVO_RIMOSSO}`);
|
|
480
|
-
} else if (!["id", "players", "lobby", "matchmaking"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
|
|
446
|
+
if (!["id", "players", "matchmaking"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
|
|
481
447
|
}
|
|
482
448
|
if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
|
|
483
449
|
errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
|
|
@@ -505,15 +471,11 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
505
471
|
}
|
|
506
472
|
}
|
|
507
473
|
}
|
|
508
|
-
if (pubblicazione && value.lobby !== void 0) errori.push(`modes[${indice}].lobby: ${MOTIVO_LOBBY}`);
|
|
509
474
|
if (value.matchmaking !== void 0) {
|
|
510
|
-
if (
|
|
511
|
-
if (pubblicazione) errori.push(`modes[${indice}].matchmaking: ${MOTIVO_MATCHMAKING}`);
|
|
512
|
-
modo.matchmaking = true;
|
|
513
|
-
} else if (typeof value.matchmaking !== "boolean") {
|
|
475
|
+
if (typeof value.matchmaking !== "boolean") {
|
|
514
476
|
errori.push(`modes[${indice}].matchmaking: must be a boolean.`);
|
|
515
477
|
} else modo.matchmaking = value.matchmaking;
|
|
516
|
-
if (
|
|
478
|
+
if (modo.matchmaking && (modo.players ?? players).max === 1) {
|
|
517
479
|
errori.push(`modes[${indice}].matchmaking: ${MODE_LOCAL_MESSAGE}`);
|
|
518
480
|
}
|
|
519
481
|
}
|
|
@@ -533,7 +495,6 @@ function validaDocumentoManifest(valore, pubblicazione) {
|
|
|
533
495
|
screenshots,
|
|
534
496
|
tags,
|
|
535
497
|
languages,
|
|
536
|
-
language,
|
|
537
498
|
platform,
|
|
538
499
|
orientation,
|
|
539
500
|
input,
|
|
@@ -877,14 +838,16 @@ var MASSIMO_BYTE_TOTALI = 5e8;
|
|
|
877
838
|
var MASSIMO_BYTE_FILE = 1e8;
|
|
878
839
|
|
|
879
840
|
// src/agent-instructions.ts
|
|
841
|
+
var AGENT_RULES = `${NETWORK_GUIDANCE}
|
|
842
|
+
${SINGLE_PLAYER_RULE}
|
|
843
|
+
The game fills the window and draws everything: menu, lobby, invites, results, "play again". The platform draws nothing over it.`;
|
|
880
844
|
function updateAgentInstructions(agents, site) {
|
|
881
845
|
const block = `<!-- caisual:begin -->
|
|
882
|
-
${
|
|
883
|
-
${SINGLE_PLAYER_RULE}
|
|
884
|
-
The game fills the window and draws everything: menu, lobby, invites, results, "play again". The platform draws nothing over it.
|
|
846
|
+
${AGENT_RULES}
|
|
885
847
|
The kit gives functions only: player identity and language, cloud saves, the daily seed, rooms (create, join with a code, invite link, ready, rematch), matchmaking, friends and party, roles and teams, voice, and the server side of a room.
|
|
886
848
|
Player-created rooms always have a lobby with ready, roles and teams. Matchmaking uses matchmaking: true and c.room.match({ mode }); it enters a room immediately. No search screen, ready or setup choices. The server assigns roles and teams. Draw waiting below players.min as a playable practice area with a short notice. Matchmaking starts a three-second countdown at the minimum and restarts automatically eight seconds after a round.
|
|
887
849
|
Read \`.claude/skills/caisual/SKILL.md\` before creating or publishing a Caisual game.
|
|
850
|
+
Read \`.claude/skills/caisual/publish.md\` for publishing and \`.claude/skills/caisual/kit.md\` for game APIs.
|
|
888
851
|
Use the current guides at ${site}/publish.md and ${site}/kit.md; the index of every guide is at ${site}/llms.txt.
|
|
889
852
|
<!-- caisual:end -->`;
|
|
890
853
|
if (agents.includes("<!-- caisual:begin -->") && agents.includes("<!-- caisual:end -->")) {
|
|
@@ -1132,19 +1095,19 @@ async function checkGameTexts(clientRoot, manifest, warn = defaultWarn) {
|
|
|
1132
1095
|
}
|
|
1133
1096
|
|
|
1134
1097
|
// src/caisual.ts
|
|
1135
|
-
import { createHash as
|
|
1098
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
1136
1099
|
import { createReadStream, promises as fs4 } from "node:fs";
|
|
1137
1100
|
import { tmpdir } from "node:os";
|
|
1138
1101
|
import { basename as basename2, dirname as dirname3, extname as extname2, join as join4, resolve as resolve3 } from "node:path";
|
|
1139
1102
|
|
|
1140
1103
|
// ../../docs/publish.md
|
|
1141
|
-
var publish_default = '# Publish a game on Caisual\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version\'s worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version. It becomes current unless another version was activated after the upload opened.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\nCaisual draws nothing over the game: the game fills the window and draws its own menu, lobby, invitation, results and "play again" with the kit\'s functions. `caisual init` writes a working minimal menu in `client/menu.js` to copy or replace. See [The game draws everything](./kit.md#the-game-draws-everything).\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 i18n/\n en.json\n it.json\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 with one local mode. Run `npx @caisual/cli init --multiplayer my-game` to add a room mode with matchmaking and a `server.js`. Both templates include `client/i18n/en.json`, used by the example client through `const t = await c.text()`, and `client/menu.js`, the game\'s own menu: solo or online, create room, copy invite, join with a code, players with ready, start, play again.\n\nThe whole CLI is:\n\n```text\ncaisual init [--multiplayer | --arcade] [folder]\ncaisual dev [folder] [--port 8790] [--day YYYY-MM-DD] [--latency ms [--jitter ms] [--loss percent]]\ncaisual check [folder] [--json]\ncaisual publish [folder]\ncaisual versions [folder|id]\ncaisual rollback [folder|id] --to <n>\ncaisual unlist [folder|id]\ncaisual relist [folder|id]\ncaisual delete [folder|id] --yes\ncaisual skill\ncaisual --help\ncaisual --version\n```\n\n`caisual dev` and `caisual publish` check for a newer CLI in the background and print an update notice; set `CAISUAL_NO_UPDATE_CHECK=1` to disable this check.\n\nPublishing requires CLI 0.24.0 or newer. If the portal returns `cli_outdated`, run `npm install -g @caisual/cli@latest` and publish again.\n\n`caisual init --arcade my-arena` creates a complete online action starter in English and Italian. It includes a shared fixed-step simulation, an authoritative `server.js`, numbered and acknowledged controls, local prediction with reconciliation, remote interpolation, its own menu and lobby, standings and fast rematches. All `init` variants also generate `package.json` with `dev`, `test` and optional `test:browser` scripts. See [Responsive action games](./kit.md#responsive-action-games) and [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n`caisual check [folder] [--json]` runs every local check used by publish: the manifest, game texts, client files, the `server.js` bundle, the three required images, and screenshots. It needs no key and uploads nothing. It validates files without launching or playing the game in a browser. With `--json` it prints a report for tools and agents. It exits with code 2 when the report has errors.\n\n`caisual skill` writes this guide, [kit.md](./kit.md) and the index of the guides at [/docs](/docs) into `.claude/skills/caisual/SKILL.md` in the current folder and adds a `## Caisual` section to `AGENTS.md`, so an agent working in that repository reads the rules before it starts. `caisual init` does the same in the new game folder, so a fresh game already carries the skill.\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": { "en": "Grow huge. Guard your tail. Devour light in a cosmic arena." },\n "cover": "cover.png",\n "card": "card.png",\n "icon": "icon.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "languages": ["en", "it"],\n "platform": "both",\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "requires": { "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" },\n "players": { "min": 1, "max": 1 },\n "persistent": false,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": [\n { "id": "solo" }\n ]\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 an optional one-line subtitle, shown below the game name on cards. It defaults to an empty string and accepts a plain string or a localized object such as `{ "en": "Grow huge. Guard your tail. Devour light in a cosmic arena.", "it": "Diventa enorme. Proteggi la coda. Divora luce in un\'arena cosmica." }`. For new publications, every value must contain 1-80 characters after trimming whitespace, on one line, with a BCP 47 key listed in `languages`. The limit applies to every language, including translations other than the default. A plain empty string means no subtitle. Previously published versions with longer descriptions remain readable; publishing an update requires the new limit.\n- `cover`, `card` and `icon` are required, distinct relative file paths inside `client/`. Use PNG, JPEG or WebP, at most 2 MB (2,000,000 bytes) per image. Do not include a query, fragment, empty segment or parent segment. See the exact dimensions below.\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- `languages` is required: a non-empty array of distinct BCP 47 tags that includes `en`, such as `["it", "en", "pt-BR"]`. English is always required alongside the game\'s own languages. The first entry remains the default and may be a language other than English. Tags are normalized to canonical casing. The catalog and standard menu show the available languages.\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- `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`. Shared memory and threaded WebAssembly are unavailable inside the portal page; use a build without threads. `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 24 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is removed at the root and on modes. Player-created rooms always have a lobby; matchmaking rooms never do. Publication and `caisual check` reject this field.\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 24, and an optional `max` in the same range. Rooms enforce these capacities in the lobby. The name the player reads comes from the game\'s own dictionary, not from the manifest.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 24, 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` defaults to `[]`. Each mode has a unique `id` of 1 to 32 lowercase letters, digits or internal hyphens. Optional `players: { min, max }` replaces the whole root range. Omitted ranges inherit the root; `mode: null` uses the root. Set `matchmaking: true` for immediate entry into rooms with server-assigned roles and teams. Roles, teams, voice and persistence remain game-wide. Catalogue labels reflect the resolved player ranges.\n- Single player runs in the browser and never touches the server; a room exists only for two or more players. A mode with resolved `players.max: 1` is local; room creation, joining and matchmaking reject it with `mode_local`. Modes with `players.max > 1` require `server.js`, checked by the CLI and again when the version is published. A server supplied for an entirely single-player game produces a warning because it is unnecessary. The manifest carries no player-facing text for modes or roles: the game names them in its own dictionaries.\n- The old matchmaking object is removed. Use `"matchmaking": true`. Publication and `caisual check` reject the object form. Published manifests remain readable.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\n`requires` is also available to the game itself through `c.device` in the kit, so the game can show its own warning or pick a lighter renderer. The portal does not gate the Play link on it.\n\n## Game translations\n\nUse this convention for every new game, including games with only one language:\n\n1. Put the supported languages in `languages`, always including `en`, with the default first.\n2. Put game UI strings in `client/i18n/<lang>.json`, with canonical filenames such as `en.json`, `it.json` and `pt-BR.json`. Dictionaries are flat objects with identical keys and string values, including placeholders such as `{n}`.\n3. Call `const t = await c.text()` after `caisual.connect()`, during setup. Render with `t(\'score\', { n: 3 })`. Use `c.player.language` when formatting dates or numbers.\n4. Translate `description` in the manifest; it is the only localized manifest field. `name` and `tags` are not localized. Mode and role names are the game\'s own text, so they live in the dictionaries with everything else.\n\nA dictionary at `client/i18n/en.json` can contain:\n\n```json\n{ "score": "Lights: {n} / 3", "done": "Complete" }\n```\n\nSee [Game language and strings](./kit.md#game-language-and-strings) for a complete manifest, two dictionaries and a working client.\n\nThe kit makes one request to the game\'s own origin. The kit first resolves the player\'s ordered preferences against declared game languages, using exact tags, parent tags, then the game\'s default. `c.player.language` is that declared game language. Caisual resolves each text key from the selected game language, its parent language tags, then the manifest\'s default language, then the key itself. For `pt-BR` with English as default, that is `pt-BR`, `pt`, `en`, key. The same chain selects the description from the page language in the catalogue, game page, creator profiles and invitations, including description metadata. A string continues to appear as written. Translation objects must be non-empty, contain valid language tags and satisfy the original text limits for every value. Empty strings are allowed in game dictionaries, but not in manifest translation objects. Description translations must use languages declared in `languages`; a missing description is omitted.\n\n`caisual dev` at startup and `caisual publish` before any upload check `client/i18n/`. No folder is required for an existing game. If the folder exists, the default language file must exist as a regular file or the command fails. All other dictionary issues produce warnings: invalid JSON, non-string values, non-canonical filenames, missing dictionaries for declared languages, and differing keys. Missing-key warnings compare the union of keys across every usable file, including keys absent from the default. Invalid dictionaries are ignored at runtime. Fix the warnings before sharing the game; they do not block development or publication. Restart dev after changing the manifest to reload its language list and repeat the checks.\n\nDeclare `languages: ["it", "en"]` to keep Italian as the default. Add English game strings and translate the description too. Declaring English does not create translations. A manifest without `languages`, or without `en`, is rejected.\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, 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\nThe game fills the window: `html`, `body` and the game surface are 100% of the viewport, with no maximum width, no header, no footer and no editorial frame, and the document must not scroll at 1366x768 or at 390x844 with safe areas applied. Aim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile; a board with a fixed aspect ratio uses the geometric exception described in [kit.md](./kit.md#full-screen).\n\nCaisual draws nothing on top, so the whole surface and every corner belong to the game. Use `env(safe-area-inset-*)` for the notch and keep the menu, the HUD and the pause action inside 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`. Relative default imports of `.wasm` stay external and their files are copied separately.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n tickRate: 0,\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\n`tickRate` is required and must be an integer from 0 to 60; `defineGame` throws without it. Use `0` for a server that runs only in response to events. Every callback is optional.\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 final bundle may only import `@caisual/kit/server` and default-import `.wasm` files, for example `import engine from \'./physics/add.wasm\'`. Paths stay inside the game folder without `..` segments. The value is an already compiled `WebAssembly.Module`; use `new WebAssembly.Instance(engine, imports)` in `onCreate` or on first use. No shared memory or threads. At most 8 files are allowed, 8,000,000 bytes per file and 16,000,000 bytes total. No manifest field is added: `requires.wasm` still describes the browser client. Use this only for existing engines. Budget for compilation on room wake, because a larger binary delays resumption; recreate instances lazily and restore their state after a wake. See [WebAssembly on the server](./kit.md#webassembly-on-the-server).\n\nThe bundled `server.js` may be at most 4,000,000 bytes. Room state must remain plain JSON and may be at most 512 KB when serialized. Game messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`. Room save values may be at most 256 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. Each imported binary is declared in the optional `server.wasm` array as `{ path, bytes, sha256 }`, uploaded to its `serverWasmUploads` URL with Content-Length, and verified with SHA-256. The files stay in the private server archive and follow the version retention rules. The portal validates the stored bundle, the imported file list and the binaries 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 --day 2026-09-04\n```\n\nThe optional `--day YYYY-MM-DD` flag pins the UTC date for daily seeds. Invalid dates are usage errors; omitting the flag uses today in UTC. Saves, identities and rooms stay shared. Room daily contexts stay fixed at creation, including on restoration; new rooms follow the simulated day. Daily `expiresAt` stays on the next real UTC midnight, so it can be compared with the unchanged server clock. Reload the game after restarting dev. Real clocks and timers are unchanged.\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, daily data, invitations, and rooms all use local data. Add `?lang=` with any game language to test the manifest resolution, including regional tags such as `pt-BR`: for `?lang=ja` with Japanese declared, `c.player.language` is `ja`. Without the parameter, the game uses the browser\'s ordered preferences. Friends are empty locally. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nOpen `/__caisual/players?n=4` on the printed portal URL for independent guest frames. Each has a Drop control that interrupts that guest\'s room connection. Use `dev --latency 120 --jitter 40 --loss 2` to delay room WebSocket messages in each direction, vary the delay and discard 2% of messages for recovery testing. Latency and jitter accept integer milliseconds from 0 to 60000, loss accepts 0 to 100 percent; jitter and loss require latency. HTTP, matchmaking and audio are unaffected. See [Local dev](/docs/local-development) for precise semantics and frame sizes.\n\nReload after client edits; restart dev after editing `caisual.json`, `server.js`, or server imports, including shared physics. Rooms restore from `.caisual-dev/`, so incompatible state changes may need a new room. There is no automatic reload. If a port is busy, dev suggests a command using a currently available port.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Single-player modes run in the browser and reject room operations with `mode_local`; multiplayer modes require `server.js`.\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 3,000 files per version.\n- At most 100,000,000 bytes per file.\n- At most 500,000,000 bytes for all files in one version.\n- At most 4,000,000 bytes for `server.js`.\n- At most 60 versions per publishing key in any 24-hour window. Beyond that the portal answers `publish_rate_limit`.\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\nnpx @caisual/cli check\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 use a build without threads if shared memory is detected. 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## Versions and rollback\n\nNew games start on the current version. An existing room stays on its own version for its entire life, including players arriving later through an invitation, a typed code or a friend. Its client, manifest, iframe permissions and images all come from that version.\n\nEvery `publish` creates a new immutable version, even for a tiny correction. The permanent address stays `/g/<id>`. The home page sorts games by the creation date of the current version; publishing can move a game up and a rollback can move it down.\n\n## Updates while a page is open\n\nCreating a room or requesting a matchmaking room from an outdated page fails with `version_outdated` and `currentVersion`. Joining an existing room from another version fails with `version_mismatch` and `roomVersion`. A room whose version is no longer ready, or whose game was deleted, shows **This room is no longer available**, with a link to the current game.\n\nMatchmaking keeps versions separate. A reservation already accepted before an update can finish on its original version. Existing rooms are not restarted by an update or rollback.\n\nThe game receives these errors both as rejected room operations and through `c.room.onError(listener)`. Show a button that calls `c.room.reload()` after either error, to load the current game or the room referenced by the failed join:\n\n```js\nc.room.onError((error) => {\n if (error.code === \'version_outdated\' || error.code === \'version_mismatch\') {\n showReloadButton(() => c.room.reload());\n }\n});\n```\n\n## List and restore versions\n\nUse the same `CAISUAL_KEY` environment variable as for publishing:\n\n```sh\ncaisual versions\ncaisual versions ./my-game\ncaisual rollback --to 7\ncaisual rollback my-game --to 7\n```\n\nThe target defaults to the current folder, or accepts a folder or game ID. `versions` lists the number, date, state and size and marks the current version. The account page also marks it.\n\nRollback selects an existing ready version of that game. It copies no files, creates no new number and does not consume the 60-version daily allowance. Visibility and moderation stay unchanged. **Rollback restores code, not saved data.**\n\nIf another version was activated while a publish was uploading, the upload becomes ready but does not replace it. The CLI reports:\n\n```text\nVersion N is ready but not current: version M was activated in the meantime. Run caisual rollback --to N to activate it.\n```\n\nA manifest\'s visibility takes effect only when activation succeeds. An `unlist` or `relist` issued during an upload wins over that upload\'s manifest visibility.\n\n## Game versions and data formats\n\nSaves belong to the game, not to a game version. The creator is responsible for data compatibility. A game version and a data format version are separate things.\n\nFor a compatible change, keep the same keys. For an incompatible change, use a new key such as `progress_v2`. Import from `progress` only when `progress_v2` is missing. Keep the original, identify the format inside each value and never overwrite a format you do not recognize. Progress written later by an old version is not automatically merged into the new key.\n\nThe daily seed does not depend on the game version. Do not change the generator or rules halfway through a UTC day without changing the board ID.\n\n## Retention and local development\n\nGood versions stay. Old ready versions are retained for rooms and rollback, without automatic age-based deletion. Failed uploads are cleaned from both client and server storage; uploads left open for more than 24 hours fail with a note and are cleaned. Version numbers are never reused. Deleting a game removes its client and server files.\n\n`caisual dev` always uses game version 1. It does not simulate publishing, version changes or rollback.\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 the current game from the catalog without publishing a new version, run:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli unlist\n```\n\nRestore its public visibility with:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli relist\n```\n\nDelete it permanently only when you are certain:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli delete --yes\n```\n\nEach command reads the `id` from `caisual.json` in the current folder. You may instead pass a game folder or an ID directly, for example `npx @caisual/cli unlist ./my-game` or `npx @caisual/cli relist my-game`. The publishing key always comes from `CAISUAL_KEY`, never from a flag. Deletion has no interactive prompt, is permanent, removes the stored game files, and never frees the ID for reuse.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing or managing a game.\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- `game_not_found`: check that the game ID is correct and belongs to the creator represented by `CAISUAL_KEY`; deleted games return the same error.\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`, `card`, `icon` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 100 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- `publish_rate_limit`: this key has already created 60 versions in the last 24 hours. Wait until the oldest one leaves the window.\n- `burst_rate_limit`: too many publishing or management requests arrived at once. Wait briefly and retry.\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: use a build without threads. Games embedded in the portal cannot use shared memory.\n\n## Required game images\n\nThe look of the game belongs to its creator: templates are deliberately neutral, and their placeholder images must be replaced.\n\nEvery manifest must declare three different files inside `client/`. All three are required PNG, JPEG or WebP images, at most 2 MB (2,000,000 bytes) each:\n\n| Field | Exact size | Use |\n| --- | --- | --- |\n| `cover` | 1536x1024, 3:2 | Featured home card, game page background, social preview, mobile invitation |\n| `card` | 1024x1024, 1:1 | Secondary home cards and square invitation artwork |\n| `icon` | 1024x1024, 1:1 | Game window favicon, friends and parties |\n\n**No text inside any image:** no title, slogan, letters or numbers. The portal displays the game name. Keep the icon simple enough to read at a small size. The files must be different, including `card` and `icon`. Screenshots keep their existing rules.\n\nThe 3:2 and 1:1 ratios match native formats of widely used image generators. Export at the exact sizes above: Caisual does not crop, stretch or accept a size range. `caisual check` and publish validate the format from the file headers, exact dimensions and weight. The portal repeats these checks for direct publication. The absence of text is an editorial requirement, not an automatic check.\n\nAll three `caisual init` variants include small, real PNG examples at these sizes. Replace them with artwork for your game before sharing it. English (`en`) is always required in `languages`; the first language remains the default, for example `["it", "en"]`.\n';
|
|
1104
|
+
var publish_default = '# Publish a game on Caisual\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version\'s worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nCaisual hosts browser games supplied as folders. Each publish creates an immutable version. It becomes current unless another version was activated after the upload opened.\nThe publishing flow supports both single-player and multiplayer games and does not require changes in the Caisual dashboard. Player identity, rooms, cloud saves, and the daily challenge come from the game kit, documented in [kit.md](./kit.md).\n\nCaisual draws nothing over the game: the game fills the window and draws its own menu, lobby, invitation, results and "play again" with the kit\'s functions. `caisual init` writes a working minimal menu in `client/menu.js` to copy or replace. See [The game draws everything](./kit.md#the-game-draws-everything).\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 i18n/\n en.json\n it.json\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 with one local mode. Run `npx @caisual/cli init --multiplayer my-game` to add a room mode with matchmaking and a `server.js`. Both templates include `client/i18n/en.json`, used by the example client through `const t = await c.text()`, and `client/menu.js`, the game\'s own menu: solo or online, create room, copy invite, join with a code, players with ready, start, play again.\n\nThe whole CLI is:\n\n```text\ncaisual init [--multiplayer | --arcade] [folder]\ncaisual dev [folder] [--port 8790] [--day YYYY-MM-DD] [--latency ms [--jitter ms] [--loss percent]]\ncaisual check [folder] [--json]\ncaisual publish [folder]\ncaisual versions [folder|id]\ncaisual rollback [folder|id] --to <n>\ncaisual unlist [folder|id]\ncaisual relist [folder|id]\ncaisual delete [folder|id] --yes\ncaisual skill\ncaisual --help\ncaisual --version\n```\n\n`caisual dev` and `caisual publish` check for a newer CLI in the background and print an update notice; set `CAISUAL_NO_UPDATE_CHECK=1` to disable this check.\n\nPublishing requires CLI 0.25.0 or newer. If the portal returns `cli_outdated`, run `npm install -g @caisual/cli@latest` and publish again.\n\n`caisual init --arcade my-arena` creates a complete online action starter in English and Italian. It includes a shared fixed-step simulation, an authoritative `server.js`, numbered and acknowledged controls, local prediction with reconciliation, remote interpolation, its own menu and lobby, standings and fast rematches. All `init` variants also generate `package.json` with `dev`, `test` and optional `test:browser` scripts. See [Responsive action games](./kit.md#responsive-action-games) and [Testing with a browser](/docs/local-development#testing-with-a-browser).\n\n`caisual check [folder] [--json]` runs every local check used by publish: the manifest, game texts, client files, the `server.js` bundle, the three required images, and screenshots. It needs no key and uploads nothing. It validates files without launching or playing the game in a browser. With `--json` it prints a report for tools and agents. It exits with code 2 when the report has errors.\n\n`caisual skill` installs three files in `.claude/skills/caisual/`. `SKILL.md` contains the rules, commands and indexes for this guide, `kit.md` and [/docs](/docs). The full guides are in `publish.md` and `kit.md`. The command adds or refreshes the Caisual rules and guide paths in `AGENTS.md`. `caisual init` installs the same files in a new game folder.\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": { "en": "Grow huge. Guard your tail. Devour light in a cosmic arena." },\n "cover": "cover.png",\n "card": "card.png",\n "icon": "icon.png",\n "screenshots": ["screenshots/level-one.png"],\n "tags": ["puzzle"],\n "languages": ["en", "it"],\n "platform": "both",\n "orientation": "landscape",\n "input": ["keyboard", "mouse", "touch"],\n "visibility": "public",\n "network": [],\n "requires": { "webgl2": false, "webgpu": false, "wasm": false, "threads": false, "memoryMb": null, "performance": "light" },\n "players": { "min": 1, "max": 1 },\n "persistent": false,\n "roles": [],\n "teams": null,\n "voice": "none",\n "modes": [\n { "id": "solo" }\n ]\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 an optional one-line subtitle, shown below the game name on cards. It defaults to an empty string and accepts a plain string or a localized object such as `{ "en": "Grow huge. Guard your tail. Devour light in a cosmic arena.", "it": "Diventa enorme. Proteggi la coda. Divora luce in un\'arena cosmica." }`. Every value must contain 1-80 characters after trimming whitespace, on one line, with a BCP 47 key listed in `languages`. The limit applies to every language, including translations other than the default. A plain empty string means no subtitle.\n- `cover`, `card` and `icon` are required, distinct relative file paths inside `client/`. Use PNG, JPEG or WebP, at most 2 MB (2,000,000 bytes) per image. Do not include a query, fragment, empty segment or parent segment. See the exact dimensions below.\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- `languages` is required: a non-empty array of distinct BCP 47 tags that includes `en`, such as `["it", "en", "pt-BR"]`. English is always required alongside the game\'s own languages. The first entry remains the default and may be a language other than English. Tags are normalized to canonical casing. The catalog and standard menu show the available languages.\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- `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`. Shared memory and threaded WebAssembly are unavailable inside the portal page; use a build without threads. `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 24 and `max` must be at least `min`. Set the range that a room needs before play can start.\n- `lobby` is removed at the root and on modes. Player-created rooms always have a lobby; matchmaking rooms never do. Publication and `caisual check` reject this field.\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 24, and an optional `max` in the same range. Rooms enforce these capacities in the lobby. The name the player reads comes from the game\'s own dictionary, not from the manifest.\n- `teams` is optional and defaults to `null`. An object has `min` and `max` integers from 2 to 24, 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` defaults to `[]`. Each mode has a unique `id` of 1 to 32 lowercase letters, digits or internal hyphens. Optional `players: { min, max }` replaces the whole root range. Omitted ranges inherit the root; `mode: null` uses the root. Set `matchmaking: true` for immediate entry into rooms with server-assigned roles and teams. Roles, teams, voice and persistence remain game-wide. Catalogue labels reflect the resolved player ranges.\n- Single player runs in the browser and never touches the server; a room exists only for two or more players. A mode with resolved `players.max: 1` is local; room creation, joining and matchmaking reject it with `mode_local`. Modes with `players.max > 1` require `server.js`, checked by the CLI and again when the version is published. A server supplied for an entirely single-player game produces a warning because it is unnecessary. The manifest carries no player-facing text for modes or roles: the game names them in its own dictionaries.\n- The old matchmaking object is removed. Use `"matchmaking": true`. Publication and `caisual check` reject the object form.\n\nThe CLI prints every manifest error in one run. Fix every listed field and rule before retrying.\n\n`requires` is also available to the game itself through `c.device` in the kit, so the game can show its own warning or pick a lighter renderer. The portal does not gate the Play link on it.\n\n## Game translations\n\nUse this convention for every new game, including games with only one language:\n\n1. Put the supported languages in `languages`, always including `en`, with the default first.\n2. Put game UI strings in `client/i18n/<lang>.json`, with canonical filenames such as `en.json`, `it.json` and `pt-BR.json`. Dictionaries are flat objects with identical keys and string values, including placeholders such as `{n}`.\n3. Call `const t = await c.text()` after `caisual.connect()`, during setup. Render with `t(\'score\', { n: 3 })`. Use `c.player.language` when formatting dates or numbers.\n4. Translate `description` in the manifest; it is the only localized manifest field. `name` and `tags` are not localized. Mode and role names are the game\'s own text, so they live in the dictionaries with everything else.\n\nA dictionary at `client/i18n/en.json` can contain:\n\n```json\n{ "score": "Lights: {n} / 3", "done": "Complete" }\n```\n\nSee [Game language and strings](./kit.md#game-language-and-strings) for a complete manifest, two dictionaries and a working client.\n\nThe kit makes one request to the game\'s own origin. The kit first resolves the player\'s ordered preferences against declared game languages, using exact tags, parent tags, then the game\'s default. `c.player.language` is that declared game language. Caisual resolves each text key from the selected game language, its parent language tags, then the manifest\'s default language, then the key itself. For `pt-BR` with English as default, that is `pt-BR`, `pt`, `en`, key. The same chain selects the description from the page language in the catalogue, game page, creator profiles and invitations, including description metadata. A string continues to appear as written. Translation objects must be non-empty, contain valid language tags and satisfy the original text limits for every value. Empty strings are allowed in game dictionaries, but not in manifest translation objects. Description translations must use languages declared in `languages`; a missing description is omitted.\n\n`caisual dev` at startup and `caisual publish` before any upload check `client/i18n/`. No folder is required for an existing game. If the folder exists, the default language file must exist as a regular file or the command fails. All other dictionary issues produce warnings: invalid JSON, non-string values, non-canonical filenames, missing dictionaries for declared languages, and differing keys. Missing-key warnings compare the union of keys across every usable file, including keys absent from the default. Invalid dictionaries are ignored at runtime. Fix the warnings before sharing the game; they do not block development or publication. Restart dev after changing the manifest to reload its language list and repeat the checks.\n\nDeclare `languages: ["it", "en"]` to keep Italian as the default. Add English game strings and translate the description too. Declaring English does not create translations. A manifest without `languages`, or without `en`, is rejected.\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, import the kit from `/__caisual/kit/v1.js?v=0.25.1` as shown in [kit.md](./kit.md). The path `/__caisual/` is reserved: do not put game files under it.\n\nThe game fills the window: `html`, `body` and the game surface are 100% of the viewport, with no maximum width, no header, no footer and no editorial frame, and the document must not scroll at 1366x768 or at 390x844 with safe areas applied. Aim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile; a board with a fixed aspect ratio uses the geometric exception described in [kit.md](./kit.md#full-screen).\n\nCaisual draws nothing on top, so the whole surface and every corner belong to the game. Use `env(safe-area-inset-*)` for the notch and keep the menu, the HUD and the pause action inside 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`. Relative default imports of `.wasm` stay external and their files are copied separately.\n\nA minimal relay server looks like this:\n\n```js\nimport { defineGame } from \'@caisual/kit/server\';\n\nexport default defineGame({\n tickRate: 0,\n onMessage(room, player, message) {\n room.broadcast(message);\n },\n});\n```\n\n`tickRate` is required and must be an integer from 0 to 60; `defineGame` throws without it. Use `0` for a server that runs only in response to events. Every callback is optional.\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 final bundle may only import `@caisual/kit/server` and default-import `.wasm` files, for example `import engine from \'./physics/add.wasm\'`. Paths stay inside the game folder without `..` segments. The value is an already compiled `WebAssembly.Module`; use `new WebAssembly.Instance(engine, imports)` in `onCreate` or on first use. No shared memory or threads. At most 8 files are allowed, 8,000,000 bytes per file and 16,000,000 bytes total. No manifest field is added: `requires.wasm` still describes the browser client. Use this only for existing engines. Budget for compilation on room wake, because a larger binary delays resumption; recreate instances lazily and restore their state after a wake. See [WebAssembly on the server](./kit.md#webassembly-on-the-server).\n\nThe bundled `server.js` may be at most 4,000,000 bytes. Room state must remain plain JSON and may be at most 512 KB when serialized. Game messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`. Room save values may be at most 256 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. Each imported binary is declared in the optional `server.wasm` array as `{ path, bytes, sha256 }`, uploaded to its `serverWasmUploads` URL with Content-Length, and verified with SHA-256. The files stay in the private server archive and follow the version retention rules. The portal validates the stored bundle, the imported file list and the binaries 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 --day 2026-09-04\n```\n\nThe optional `--day YYYY-MM-DD` flag pins the UTC date for daily seeds. Invalid dates are usage errors; omitting the flag uses today in UTC. Saves, identities and rooms stay shared. Room daily contexts stay fixed at creation, including on restoration; new rooms follow the simulated day. Daily `expiresAt` stays on the next real UTC midnight, so it can be compared with the unchanged server clock. Reload the game after restarting dev. Real clocks and timers are unchanged.\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, daily data, invitations, and rooms all use local data. Add `?lang=` with any game language to test the manifest resolution, including regional tags such as `pt-BR`: for `?lang=ja` with Japanese declared, `c.player.language` is `ja`. Without the parameter, the game uses the browser\'s ordered preferences. Friends are empty locally. Each new browser tab gets a different guest identity, while reloading one tab keeps that tab\'s identity.\n\nOpen `/__caisual/players?n=4` on the printed portal URL for independent guest frames. Each has a Drop control that interrupts that guest\'s room connection. Use `dev --latency 120 --jitter 40 --loss 2` to delay room WebSocket messages in each direction, vary the delay and discard 2% of messages for recovery testing. Latency and jitter accept integer milliseconds from 0 to 60000, loss accepts 0 to 100 percent; jitter and loss require latency. HTTP, matchmaking and audio are unaffected. See [Local dev](/docs/local-development) for precise semantics and frame sizes.\n\nReload after client edits; restart dev after editing `caisual.json`, `server.js`, or server imports, including shared physics. Rooms restore from `.caisual-dev/`, so incompatible state changes may need a new room. There is no automatic reload. If a port is busy, dev suggests a command using a currently available port.\n\nWhen `server.js` exists, room data is stored as JSON under `.caisual-dev/` in the game folder. Single-player modes run in the browser and reject room operations with `mode_local`; multiplayer modes require `server.js`.\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 3,000 files per version.\n- At most 100,000,000 bytes per file.\n- At most 500,000,000 bytes for all files in one version.\n- At most 4,000,000 bytes for `server.js`.\n- At most 60 versions per publishing key in any 24-hour window. Beyond that the portal answers `publish_rate_limit`.\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\nnpx @caisual/cli check\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 use a build without threads if shared memory is detected. If the signature belongs to unused code, remove that code from the published client bundle.\n\nNew games from a creator enter review before they can appear in the public catalog. Once the creator has three approved, undeleted games with a current version, new games are approved automatically. During review, anyone with the stable link can open the game and use its online features, including multiplayer.\n\n**Your games** in [your account](/account) shows game opens and new online rooms for the last 7 and 30 UTC days, including today. Game opens are counted when a browser starts the embedded game. Online rooms include rooms opened by a player and rooms opened by matchmaking.\n\n## Versions and rollback\n\nNew games start on the current version. An existing room stays on its own version for its entire life, including players arriving later through an invitation, a typed code or a friend. Its client, manifest, iframe permissions and images all come from that version.\n\nEvery `publish` creates a new immutable version, even for a tiny correction. The permanent address stays `/g/<id>`. The home page sorts games by the creation date of the current version; publishing can move a game up and a rollback can move it down.\n\n## Updates while a page is open\n\nCreating a room or requesting a matchmaking room from an outdated page fails with `version_outdated` and `currentVersion`. Joining an existing room from another version fails with `version_mismatch` and `roomVersion`. A room whose version is no longer ready, or whose game was deleted, shows **This room is no longer available**, with a link to the current game.\n\nMatchmaking keeps versions separate. A reservation already accepted before an update can finish on its original version. Existing rooms are not restarted by an update or rollback.\n\nThe game receives these errors both as rejected room operations and through `c.room.onError(listener)`. Show a button that calls `c.room.reload()` after either error, to load the current game or the room referenced by the failed join:\n\n```js\nc.room.onError((error) => {\n if (error.code === \'version_outdated\' || error.code === \'version_mismatch\') {\n showReloadButton(() => c.room.reload());\n }\n});\n```\n\n## List and restore versions\n\nUse the same `CAISUAL_KEY` environment variable as for publishing:\n\n```sh\ncaisual versions\ncaisual versions ./my-game\ncaisual rollback --to 7\ncaisual rollback my-game --to 7\n```\n\nThe target defaults to the current folder, or accepts a folder or game ID. `versions` lists the number, date, state and size and marks the current version. The account page also marks it.\n\nRollback selects an existing ready version of that game. It copies no files, creates no new number and does not consume the 60-version daily allowance. Visibility and moderation stay unchanged. **Rollback restores code, not saved data.**\n\nIf another version was activated while a publish was uploading, the upload becomes ready but does not replace it. The CLI reports:\n\n```text\nVersion N is ready but not current: version M was activated in the meantime. Run caisual rollback --to N to activate it.\n```\n\nA manifest\'s visibility takes effect only when activation succeeds. An `unlist` or `relist` issued during an upload wins over that upload\'s manifest visibility.\n\n## Game versions and data formats\n\nSaves belong to the game, not to a game version. The creator is responsible for data compatibility. A game version and a data format version are separate things.\n\nFor a compatible change, keep the same keys. For an incompatible change, use a new key such as `progress_v2`. Import from `progress` only when `progress_v2` is missing. Keep the original, identify the format inside each value and never overwrite a format you do not recognize. Progress written later by an old version is not automatically merged into the new key.\n\nThe daily seed does not depend on the game version. Do not change the generator or rules halfway through a UTC day without changing the board ID.\n\n## Retention and local development\n\nGood versions stay. Old ready versions are retained for rooms and rollback, without automatic age-based deletion. Failed uploads are cleaned from both client and server storage; uploads left open for more than 24 hours fail with a note and are cleaned. Version numbers are never reused. Deleting a game removes its client and server files.\n\n`caisual dev` always uses game version 1. It does not simulate publishing, version changes or rollback.\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 the current game from the catalog without publishing a new version, run:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli unlist\n```\n\nRestore its public visibility with:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli relist\n```\n\nDelete it permanently only when you are certain:\n\n```sh\nCAISUAL_KEY=\'ck_...\' npx @caisual/cli delete --yes\n```\n\nEach command reads the `id` from `caisual.json` in the current folder. You may instead pass a game folder or an ID directly, for example `npx @caisual/cli unlist ./my-game` or `npx @caisual/cli relist my-game`. The publishing key always comes from `CAISUAL_KEY`, never from a flag. Deletion has no interactive prompt, is permanent, removes the stored game files, and never frees the ID for reuse.\n\nTo close your account, open **Delete account** in **Your account** and type your username. This permanently removes your published games, API keys, and saves and signs you out.\n\n## Common errors\n\n- `CAISUAL_KEY is required`: export the creator\'s key in the same shell before publishing or managing a game.\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- `game_not_found`: check that the game ID is correct and belongs to the creator represented by `CAISUAL_KEY`; deleted games return the same error.\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`, `card`, `icon` and every screenshot path match a file under `client/`, including letter case.\n- `file is larger than 100 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- `publish_rate_limit`: this key has already created 60 versions in the last 24 hours. Wait until the oldest one leaves the window.\n- `burst_rate_limit`: too many publishing or management requests arrived at once. Wait briefly and retry.\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: use a build without threads. Games embedded in the portal cannot use shared memory.\n\n## Required game images\n\nThe look of the game belongs to its creator: templates are deliberately neutral, and their placeholder images must be replaced.\n\nEvery manifest must declare three different files inside `client/`. All three are required PNG, JPEG or WebP images, at most 2 MB (2,000,000 bytes) each:\n\n| Field | Exact size | Use |\n| --- | --- | --- |\n| `cover` | 1536x1024, 3:2 | Featured home card, game page background, social preview, mobile invitation |\n| `card` | 1024x1024, 1:1 | Secondary home cards and square invitation artwork |\n| `icon` | 1024x1024, 1:1 | Game window favicon, friends and parties |\n\n**No text inside any image:** no title, slogan, letters or numbers. The portal displays the game name. Keep the icon simple enough to read at a small size. The files must be different, including `card` and `icon`. Screenshots keep their existing rules.\n\nThe 3:2 and 1:1 ratios match native formats of widely used image generators. Export at the exact sizes above: Caisual does not crop, stretch or accept a size range. `caisual check` and publish validate the format from the file headers, exact dimensions and weight. The portal repeats these checks for direct publication. The absence of text is an editorial requirement, not an automatic check.\n\nAll three `caisual init` variants include small, real PNG examples at these sizes. Replace them with artwork for your game before sharing it. English (`en`) is always required in `languages`; the first language remains the default, for example `["it", "en"]`.\n';
|
|
1142
1105
|
|
|
1143
1106
|
// ../../docs/kit.md
|
|
1144
|
-
var kit_default = "# Caisual game kit\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version's worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nThe kit gives a published game a stable player identity, cloud saves, a daily challenge seed, multiplayer rooms with server-owned state, and the player's friends.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page and never draws anything: the game fills the window and draws its own menu, lobby, results and HUD.\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, language }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or a stable `Guest-XXXX` name derived from the player id. The four-character suffix uses `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, excluding I, O, 0 and 1; it helps distinguish guests but is not a unique identifier. `guest` is `true` for players without an account. `language` selects game strings. On first sign-in to an account without a player identity, the browser guest is adopted with its existing id and saves. An account that already has a player identity uses that identity instead; guest data is not merged.\n- When not connected, `c.player` has `id: \"local\"`, `name: \"Guest\"`, `guest: true` and a `language`. If the host answered, its language information is kept; without a handshake, `language` is the normalized `navigator.language`, or `en`.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\n## Game language and strings\n\n`c.player.language` is the game's language, chosen by the site. Use it for game strings and formatting.\n\nThe kit resolves the player's explicit portal language choice, otherwise `navigator.languages` in order, against `manifest.languages`. For each preference it tries the exact tag and then its parent tags; if none of the preferences match, it uses the game's first declared language. The result is always a normalized declared tag. For example, `ja-JP` with `languages: [\"en\", \"ja\"]` selects `ja`. The site itself speaks English, Italian, Spanish, French, German, Portuguese and Japanese; a game may declare any language.\n\nA localized portal URL counts as a language choice. The language selector remembers explicit choices, including English; without either, the browser's ordered preferences apply. The handshake sends `language`, `languagePreferences` and `gameLanguages`. The kit resolves the game language, including when player services fail after a successful handshake.\n\nWithout a handshake, no declared language list is available: `language` is the raw preference from `navigator.language`, normalized as a BCP 47 tag, or `en` if invalid or unavailable. In `caisual dev`, `?lang=ja` selects `ja` when the manifest declares it. Without `?lang=`, dev uses `navigator.languages` in order.\n\nPut all game UI strings in flat JSON dictionaries named `client/i18n/<lang>.json`. Use canonical BCP 47 filenames, for example `en.json`, `it.json`, `pt.json`, `pt-BR.json`. Every value is a string; keys are identical across dictionaries. Text can contain named placeholders such as `{n}`.\n\nDeclare supported languages in `caisual.json`, always including `en`. English is required alongside the game's own languages; the first entry is the default and may be another language. This complete manifest supports a local game:\n\n```json\n{\n \"manifest\": 1,\n \"cover\": \"cover.png\",\n \"card\": \"card.png\",\n \"icon\": \"icon.png\",\n \"id\": \"three-lights\",\n \"name\": \"Three Lights\",\n \"platform\": \"both\",\n \"languages\": [\"en\", \"it\"],\n \"modes\": [{ \"id\": \"solo\" }]\n}\n```\n\n`client/i18n/en.json`:\n\n```json\n{ \"score\": \"Lights: {n} / 3\", \"light\": \"Light up\", \"done\": \"Complete\" }\n```\n\n`client/i18n/it.json`:\n\n```json\n{ \"score\": \"Luci: {n} / 3\", \"light\": \"Accendi\", \"done\": \"Tutte accese!\" }\n```\n\nLoad the dictionary once during setup. The returned function is synchronous and can be used in every draw call:\n\n```html\n<!doctype html>\n<html>\n<head><meta charset=\"utf-8\"><title>Three Lights</title></head>\n<body style=\"margin:0;min-height:100dvh;display:grid;place-content:center\">\n <p id=\"score\"></p>\n <button id=\"light\" disabled></button>\n <script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js';\n const c = await caisual.connect();\n const t = await c.text();\n document.documentElement.lang = c.player.language;\n const score = document.querySelector('#score');\n const light = document.querySelector('#light');\n let n = 0;\n function draw() {\n score.textContent = n === 3 ? t('done') : t('score', { n });\n light.textContent = t('light');\n light.disabled = n === 3;\n }\n light.onclick = () => { n += 1; draw(); };\n draw();\n </script>\n</body>\n</html>\n```\n\n`c.text(): Promise<Text>` makes one request to the game's own origin, tied to the version currently open. Caisual and `caisual dev` read the matching files and merge them per key: `pt-BR` then `pt` then the manifest's default language. Longer tags fall back through their parent tags, such as `zh-Hant-TW`, `zh-Hant`, `zh`. The default file is tried once. If no file contains a key, `t` returns that key. Empty strings are valid translations.\n\nConcurrent and later `c.text()` calls share the same promise and translator for that connection. There are no dependencies, eager downloads, or per-call network requests. Missing files, invalid dictionaries and network failures do not prevent startup. If the Caisual text service is unavailable, for example on a plain static host outside Caisual, the translator returns keys; it does not probe other URLs. Use `caisual dev` to preview the complete convention.\n\n`t('score', { n: 3 })` replaces named placeholders with strings or numbers. An omitted placeholder stays unchanged, such as `{n}`. The result is plain text, with no HTML processing, plural rules or automatic translation. Set `textContent` or draw it on the canvas; do not insert it as HTML. A new document gets the host's current language and a fresh translator.\n\n`description` accepts a string or a language-to-text object, and resolves from the page language in the catalogue, profiles, invitations and metadata. `description` is an optional one-line subtitle, at most 80 characters after trimming whitespace in every language for new publications, for example `{ \"en\": \"Grow huge. Guard your tail. Devour light in a cosmic arena.\" }`. Each translation must be non-empty and use a key declared in `languages`; an absent field or a plain empty string omits the subtitle. Previously published versions with longer descriptions remain readable. `name` and `tags` keep their existing forms. See [manifest languages and validation](./publish.md#game-translations) for CLI checks and migration from `language`.\n\n## The game draws everything\n\nCaisual draws nothing over the game. The game gets the whole window and builds its own menu, lobby, invitation, result and \"play again\" from the calls below. There is no platform overlay, no menu, no pill, no reserved rectangles, no keyboard shortcut and no end-of-match screen. `env(safe-area-inset-*)` inside the game document is the real safe area.\n\n`caisual init` writes that minimal menu in `client/menu.js`: solo or online, create room, copy invite, join with a code, the player list with ready, start, and play again. It is about a hundred lines with no dependencies. Copy it, recolour it, or delete it and draw the same actions in your own style.\n\n```js\nconst c = await caisual.connect();\n\n// Solo: the state belongs to the game.\nstartLocalRun();\n\n// Online: the state belongs to the server.\nconst room = await c.room.create({ mode: 'duel' });\nroom.onPlayers((players) => drawLobby(players));\nroom.onStatus((status, result) => {\n if (status === 'playing') hideMenu();\n if (status === 'finished') drawResult(result); // then room.restart() for a rematch\n});\nroom.ready(true);\n```\n\nNothing has to be announced at startup: there is no handshake call, no session object and no capability flag. Draw your menu when the assets are ready. `c.connected` is `false` when the game runs outside caisual.com: rooms and friends are unavailable, everything else works on local data.\n\n### Full screen\n\nThe game fills the window. `html`, `body` and the game surface are 100% of the viewport: no maximum width, no header, no footer, no editorial frame, and no document scrolling at 1366x768 or 390x844, safe areas included. Only the HUD, the menu and compact controls sit over the scene.\n\nAim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile, counting only what shows or controls the game. A board with a fixed aspect ratio cannot always reach that: a square board on a 1366x768 window tops out near 56% before any HUD. That is the declared geometric exception: the board must then fill at least 90% of the largest rectangle that fits the area left free, and the HUD must have a stated ceiling, typically 48 to 64 pixels on desktop and about 160 pixels of controls on a phone.\n\n## Friends and party\n\n`c.crew` mirrors the player's Caisual friends inside the game, so the game can draw its own friends list and its own invitations. The platform owns the relationships; the game reads them and asks for the few actions it needs.\n\n```js\nc.crew.available; // false in a copy of the game running outside caisual.com\nc.crew.connected; // the friends channel is live\nc.crew.you; // { id, name } or null\nc.crew.friends; // [{ id, name, online, game: { slug, name, iconUrl } | null, room: { code } | null }]\nc.crew.party; // { id, leader, members: [...] } or null\nc.crew.invites; // [{ party, from: { id, name }, at }]\n\nconst stop = c.crew.onChange((crew) => drawFriends(crew));\n\nc.crew.createParty();\nc.crew.invite('player-id');\nc.crew.accept('party-id');\nc.crew.decline('party-id');\nc.crew.kick('player-id');\nc.crew.leave();\n\nconst room = await c.crew.join('player-id'); // enter the friend's room, in this game\nc.crew.follow('player-id'); // the site opens the friend's game, even another one\n```\n\n`onChange` repeats the current value immediately and returns a function that removes the listener. `join()` rejects with `no_room` when that player is not in a room, `other_game` when the friend is playing something else, which is what `follow()` is for, and `friend_not_found` for an unknown id. `follow()` hands navigation to the site, so the page changes. Outside caisual.com the lists stay empty, the actions do nothing, and `join()` rejects with `offline`.\n\nThe kit reports the player's current room to the site by itself, so friends can also join from the site with one click.\n\n## Daily challenge\n\n`c.daily` describes the day selected when the connection opened. `day`, `seed` and `expiresAt` stay fixed for that connection, including across UTC midnight. `expiresAt` is the next UTC midnight in milliseconds on the server clock.\n\n```js\nc.daily.day;\nc.daily.seed;\nc.daily.expiresAt;\nconst random = c.daily.rng();\nconst stop = c.daily.onChange(({ day, seed, expiresAt }) => {\n offerNextDailyRun({ day, seed, expiresAt });\n});\n```\n\n`onChange` reports a new `{ day, seed, expiresAt }` when the current UTC day changes. It returns an unsubscribe function and does not immediately replay the initial value. A suspended browser or a connection failure can delay the notification; the kit retries and reports the latest day when it can. The event does not mutate `c.daily` or reseed either generator. `rng()` always creates a fresh generator from the connection's original seed, and `random()` keeps advancing the original shared generator. Use the event's context explicitly for a new daily run, or open a new document. Repeated `connect()` calls return the same connection.\n\n`day` is a UTC date such as `\"2026-09-04\"`; `seed` is an unsigned 32-bit integer shared by all players of that game on that day. Both generators produce values in [0, 1). `c.time.now()` is in milliseconds aligned with the portal clock. Without a connection, daily data uses the local clock and hostname, with the same listener and generator behavior.\n\nOn the server, `room.daily` is `{ day, seed, expiresAt }`, fixed at **room creation**, persisted across sleep and rematches. Its seed matches a client connection opened for that game on the creation day. A client connected yesterday can therefore have a different `c.daily` from a room created today: send the room's daily context through game state when rendering its course. To switch a persistent or rematched room to a new daily course, create a new room.\n\n`caisual dev --day YYYY-MM-DD` fixes the simulated day and seed for new connections and rooms. Clocks stay real: `expiresAt` is the next **real** UTC midnight at connection or room creation, so comparing it with `c.time.now()` or `room.time.now()` remains valid even for a simulated date. Restored rooms keep their original daily context. Restart dev and reload to change the flag; create a new room for the newly selected day.\n\n## Saves\n\nEach player has up to 64 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## 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\n`device.isolated` measures the browser's actual `crossOriginIsolated` state. Games embedded in the portal report `false`; shared memory and threaded WebAssembly are unavailable there. This runtime probe does not enable isolation.\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### Two front ends, one game\n\nKeep one `client/index.html`, one game ID and one server. With `platform: \"both\"`, choose separate front ends in that entry without navigating or adding another iframe:\n```js\nimport { caisual } from '/__caisual/kit/v1.js';\nconst c = await caisual.connect();\nlet preference = null;\ntry { preference = localStorage.getItem('layout'); } catch {}\nconst touch = preference === 'touch' || (preference !== 'desktop' && (c.device.mobile || matchMedia('(pointer: coarse)').matches));\nconst screen = touch ? await import('./touch/main.js') : await import('./desktop/main.js');\nscreen.mount({ c, root: document.querySelector('#app') });\n```\nOffer a manual layout choice, persist it when storage is available, and keep rules and room connections shared. Both front ends use relative asset paths inside `client/`.\n\n## Game version changes\n\nNew games use the current version. Existing rooms retain their version for their whole life, including invitations, typed codes and friends. Matchmaking never mixes versions; an accepted reservation can finish on its original version. Saves remain per game, with data compatibility handled by the creator. See [Versions and rollback](./publish.md#versions-and-rollback).\n\nA room create or match operation rejects with `version_outdated` and `currentVersion` when the loaded game is no longer current. A join or reconnect rejects with `version_mismatch` and `roomVersion` when the room uses another version.\n\nSubscribe with `c.room.onError(listener)`, which returns an unsubscribe function. The error has `code`, `message`, and the applicable version number. The operation also rejects with that error. `c.room.reload()` reloads the page on the current game after `version_outdated`, or on the last mismatched room after `version_mismatch`. Show a button calling it after either error: it is the only way out of both.\n\n`caisual dev` always uses game version 1 and does not simulate version changes.\n\n## Rooms\n\nA room brings players into the same running game. Single player runs in the browser and never touches the server; a room exists only for two or more players. Creating and joining require a published `server.js` and a mode with `players.max > 1`. A local mode rejects room operations with `mode_local`.\n\nAn optional [MatchResult](#recognized-match-results) in `room.end` gives the game a ready shape for winners and standings, while `room.result` keeps the original JSON.\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.tickRate;\nroom.latency;\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nA room you create always has a lobby. Matchmaking rooms never have one.\nRead `room.origin` (`player` or `matchmaking`) to distinguish them. Games published before version 0.23 read `room.metadata.configuration.lobby` instead: it still works and is `true` exactly when the origin is `player`. During play, a player-created room only admits returning members. Matchmaking admits new players up to `players.max`.\n\nPass a mode id from the manifest to `create({ mode })`, or `null` to use the root configuration. Optional `players` on that mode replaces the root range. Joining keeps the configuration and origin of the room being joined. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. `invite()` returns the code and the link to copy.\n\n### Friends in a room\n\nThe kit reports the player's current room to the site by itself, so friends can see where the player is and join. See [Friends and party](#friends-and-party) for the data and the calls.\n\n### Matchmaking\n\nDeclare `\"matchmaking\": true` on a mode with resolved `players.max > 1`.\n\n```js\nconst room = await c.room.match({ mode: 'arena' });\n```\n\nYou enter immediately, even alone. There is no search screen or lobby. Roles and teams are assigned by the server. Below `players.min`, `room.status` is `waiting`: draw a playable practice area with a short notice above the scene. At the minimum, a three-second countdown starts. New players can join during countdown and play without resetting it.\n\nA normal round ends in `finished` and restarts automatically at `room.metadata.rematch.deadline`, eight seconds after the result. Compare the deadline with `room.serverTime()`; see [Rematch in the same room](#rematch-in-the-same-room). `ready()` and `restart()` are ignored. Lobby role and team calls fail with `matchmaking_room`; gameplay `requestRole()` remains available when the server supports it. Make character and equipment choices during the first seconds of play with a timer.\n\nPass an optional `signal` to cancel before assignment (`cancelled`). Errors are `invalid_request`, `mode_local`, `no_server`, `rate_limited`, `offline`, `version_outdated` and `room_full`. See [Matchmaking](/docs/matchmaking) for examples and the full waiting rules.\n\nRoom status is one of:\n\n- `waiting`: a matchmaking room is below `players.min`. Draw a playable practice scene.\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: play begins at the announced server time, three seconds after the start condition is met.\n- `playing`: the game server is running the match.\n- `finished`: the match is over and the room is waiting for a rematch, with sockets open and `room.result` available.\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 }` when the player was kicked, `{ closed: 4004 }` when the room ended, `{ closed: 4005 }` when the published version closed, or `{ closed: 4006 }` when the same player opened the room in another tab.\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\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n```\n\n`ready`, role and team are the lobby actions for player-created rooms: draw the roster from `room.players` and call them from your own lobby. **Nobody hosts and nobody presses start.** As soon as every connected player is ready and the player, role and team minimums from the manifest are met, the room begins a three-second countdown on its own. If someone joins during the countdown, which they may, or takes back their readiness, or a minimum stops being met, the room returns to the lobby. A role or team change in the lobby clears that player's ready state. Every room member is a player. If all declared roles are full, entry fails with `room_full` before adding a member, even below `players.max`. Roles must be declared in the manifest; assigning an undeclared role fails with `invalid_role`.\n\n### Rematch in the same room\n\nMatchmaking rooms restart automatically eight seconds after a normal round ends. `restart()` and `ready()` are ignored. Reset state in `onRestart`; the next phase is `waiting` below the minimum, otherwise `countdown`. See [Matchmaking](/docs/matchmaking).\n\n\nIn player-created rooms, the server opts in per match with `room.end(result, { rematch: true })`. The room becomes `finished`, keeps its code, members, state and open connections, and exposes the result through `room.result` and `onStatus('finished', result, at)`. Voice stays connected. `room.end(result)` or `{ rematch: false }` still ends the room permanently with status `ended` and close code 4004.\n\nDuring `finished`, `room.metadata.rematch` is `{ keepSetup, deadline }`, already available inside `onStatus('finished', result, at)`. `deadline` is server time in milliseconds, on the same clock as `at` and `countdownAt`; compare it with `room.serverTime()`. In a matchmaking room, the next round starts automatically at `deadline`, eight seconds after the result. In a player-created room, the room closes at `deadline`, after two minutes, if not everyone has accepted and no rematch has started. Once the rematch starts, `room.metadata.rematch` becomes `null`.\n\nFor matchmaking, draw the remaining time on each render:\n\n```js\nconst rematch = room.metadata.rematch;\nif (room.status === 'finished' && room.origin === 'matchmaking' && rematch) {\n const seconds = Math.max(0, Math.ceil((rematch.deadline - room.serverTime()) / 1000));\n draw(`next round in ${seconds} s`);\n}\n```\n\nWith `rematch: true` in a multiplayer room, each connected player calls `room.restart()` once to accept the rematch. In `finished`, `room.players[].ready` means rematch readiness. The rematch starts by itself as soon as every connected player has accepted and the mode's `players.min` is met, including when a departure leaves that condition satisfied. Repeated calls do nothing. Calling outside `finished` fails with `rematch_unavailable`.\n\nDraw \"Play again\" with the readiness count. No member is removed for declining.\n\nAt the start, the kit clears the result to `null` and all readiness flags, then calls optional `onRestart(room)` with status `lobby`. **The kit does not reset `room.state`.** Reset match data in `onRestart`, keeping series scores or other data as needed. Players choose their setup and get ready again before the normal countdown and `onStart`. Clients receive the new state and an `onStatus` transition with a null result. The room identity, seed and tick sequence are retained, so the same room object stays valid. Listen to `room.onState` and `room.onStatus`.\n\n### Fast rematches\n\nThe existing `rematch: true` flow above is unchanged for multiplayer rooms. To shorten it, use:\n\n```js\nroom.end(result, { rematch: { keepSetup: true } });\n```\n\n`keepSetup` defaults to `false`. It restores the previous readiness flags, keeps roles and teams, and skips the lobby: `onRestart` runs with status `countdown`, followed by the usual three-second countdown and `onStart`. The result clears before `onRestart`. Readiness during `finished` is still consent for the next match, separate from the previous setup. Player, role and team minimums are rechecked during the countdown; if they fail, the room returns to the lobby so the setup can be repaired.\n\nMembers who have not accepted remain in the room and join the next phase; they are not removed. Without `keepSetup`, the next phase is the usual lobby.\n\n\nThe waiting rules are:\n\n- All pending `room.schedule` handlers are cancelled when the match finishes, including handlers already due in the same batch. Scheduling during `finished` has no effect. Schedule new work in `onRestart` or `onStart`. Tick callbacks stop immediately; game input during the wait is discarded, and queued continuous input is cleared on the client.\n- `onEnd` runs once for the completed match, with status `finished` and its result. A subsequent timeout only closes the room and does not call `onEnd` again.\n- Disconnecting clears that member's readiness. Disconnected players do not count toward readiness or the minimum, so a departure can be what starts the rematch. The usual 60-second reconnection grace applies; persistent members keep their seats after it. Rejoining requires a new readiness call. Connection and departure callbacks continue during the wait.\n- New members may join by invitation during the wait, up to the resolved `players.max`, and start unready. Player-created rooms reopen admission while `finished`. Disconnected members still occupy seats until removed. Roles and teams retain their existing capacity rules.\n- The room closes with 4004 exactly two minutes after entering `finished` if no restart is confirmed, retaining the last result. Readiness, joins and pings do not extend this deadline. It also applies to persistent rooms and survives sleep or restoration; it does not depend on active ticks.\n\n`finished` is a status, not a terminal connection state: the sockets stay open. Handle it explicitly in the game's status listener, and draw the result and the rematch action there.\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 for both tick-based and event-only servers. Full state is sent on entry, reconnection or resync when an update does not match the current tick; normal updates, including every hundredth tick, remain diffs. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\n`room.tickRate` is the current effective server frequency, including reductions caused by the CPU budget; zero means event-only. Updates arrive with state diffs and snapshots, including an empty diff when only the frequency changes. `room.latency` is the smoothed round-trip time in milliseconds, or `null` before the first pong and after a dropped connection until the next pong. Each pong uses 20% of the new RTT and 80% of the previous estimate, with the first sample used directly. Read the property when drawing network status; there is no `onLatency` listener.\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. `room.send` calls while reconnecting throw an error with `code: \"offline\"`.\n\nUse `room.input(value)` for continuous controls, including calls from every animation frame:\n\n```js\nroom.input({ type: 'move', x: axisX, y: axisY });\nroom.onError(({ code }) => {\n if (code === 'rate_limited') showInputWarning();\n});\n```\n\n`input` copies and keeps only the latest JSON value in one slot. It coalesces updates and sends at most 30 times per second, or at the effective `room.tickRate` when that is lower and positive. With `tickRate: 0`, it still sends at most 30/s. It also waits for budget used by `send`. Values with the same JSON serialization are not resent on the same connection. Combine independent controls into that one value; there is no channel option. On the server it is an ordinary message passed unchanged to `onMessage`, exactly like `send`, with no extra envelope.\n\nDuring reconnection, `input` accepts updates without throwing `offline`. After the new welcome it sends only the latest value, even if it was sent on the previous connection. It never replays intermediate values or old commands. Use `send` for individual actions such as firing or confirming a turn; `send` still throws `offline` during reconnection. Invalid JSON input can throw `invalid_request`. Input stops after leaving, disconnecting intentionally or ending the room.\n\nGame messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`, reported through `room.onError`; malformed frames use 4009 `bad_message`. Neither closure is retried automatically.\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\n`room.disconnect()` is the other departure: it stops the transport, the retries and voice without sending a leave, so the server keeps the seat under its own persistence and grace rules. It is not reversible on the same object; returning means entering again from the code, which is how a \"leave for now\" action works.\n\nA room also exposes `room.mode`, `room.countdownAt`, `room.connection`, `room.metadata`, and the `onMetadata` and `onConnection` listeners. `connection` is one of `connecting`, `connected`, `reconnecting`, `disconnected`, `ended`, `closed`, or `replaced`, where `replaced` means the same player opened the room in another tab. These listeners do not repeat the current value: read the getter first.\n\n`room.onError(listener)` reports technical protocol errors of the room as `{ code, message }`; it is not the place where a game reads its own result.\n\n`await room.requestRole('scout')` asks the server for a role change during a match. It works only while the room is playing, only for a role declared in the manifest, and only when `server.js` defines `onRoleRequest(room, player, role)`; the server approves by calling `room.setRole`. Without that callback nothing changes. It is not a shortcut for changing roles from the browser.\n\nRoom creation, joining, and matchmaking reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `mode_local`, `no_server`, `cancelled`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `mode_local` means \"Single-player modes run in the browser and have no room.\" `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, `create`, `join`, and `match` reject with `offline`.\n\n- `invalid_role`: a requested role id is malformed or is not declared in the manifest. Request a declared role id.\n- `role_change_unavailable`: the room is disconnected, is not playing, or `server.js` has no `onRoleRequest`. Wait for a connected playing state and provide that callback before offering the action.\n- `role_change_refused`: `onRoleRequest` returned without assigning the requested role. Leave the current role in place, or have the server approve with `room.setRole`.\n- `version_closed`: the room connection ended because its published version closed. Reopen the current game version and enter a current room.\n\nEvery listener call on a room returns a function that removes that listener: `onState`, `onPlayers`, `onStatus`, `onMessage`, `onMetadata`, `onConnection`, and `onError`.\n\n### Responsive action games\n\n1. Start with `npx @caisual/cli init --arcade my-arena`, a complete English/Italian canvas game with shared rules and tests.\n2. Accumulate `deltaSeconds` on the server and advance shared physics at a fixed 1/60 second step.\n3. Keep positions, collision or range checks, cooldowns and scores authoritative in `server.js`.\n4. Use `room.input()` for continuous controls and `room.send()` for discrete actions such as the starter's pulse.\n5. Number commands in the game and publish each player's last **applied** `ack` in `room.state`; transport sequence numbers are separate.\n6. Because `input()` coalesces values, send a bounded batch of unacknowledged commands; deduplicate on the server and consume at most one per simulation step.\n7. Predict your own entity with the shared step, replace it with each authoritative snapshot, then replay only commands after `ack`; ease corrections in the drawing only.\n8. Buffer remote samples by the `onState` timestamp and render behind `room.serverTime()`, accounting for RTT in `room.latency` and the effective `room.tickRate`.\n9. Clear pending controls on reconnection or a new round; keep the HUD inside the safe areas, and end with `standings` plus a `keepSetup` rematch.\n10. Run the generated browser fixture and `/__caisual/players?n=2` with `dev --latency 120 --jitter 40 --loss 2`; see [Testing with a browser](/docs/local-development#testing-with-a-browser).\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.\n\nThe game draws the voice controls, and must offer an explicit one: `join()` has to 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.\n\nThe room server authorizes every voice track by team and gain. Listening that is no longer allowed is refused or closed.\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`, `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, // required, an integer from 0 to 60; 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onConnection(room, player, connected) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onRoleRequest(room, player, role) {}, // approve with room.setRole\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n onRestart(room) {},\n});\n```\n\n`tickRate` is the only required field: `defineGame` throws a `TypeError` when it is missing or is not an integer from 0 to 60. All callbacks are optional. A player is `{ id, name, guest, role, team, connected }`.\n\n### Callback order\n\n- `onCreate` runs once when the room is first created, before any player joins.\n- `onJoin` runs when a player first enters the room, not when that same member reconnects. The countdown completes before `onStart`, for both room origins.\n- `onStart` runs when the room changes to `playing`. The three-second countdown starts at the connected player minimum in matchmaking, or when all player-created room members are ready and setup minimums are met.\n- `onTick` runs for each active game tick when `tickRate` is greater than zero. `onMessage` runs for accepted client game messages, and `onRoleRequest` runs for an in-match role request when that callback exists. These events are processed serially, so their relative order is the order in which the room processes them.\n- `onConnection(room, player, connected)` runs with `false` when an existing member loses their connection and with `true` when that disconnected member returns. Both `player.connected` and `room.players` are already updated. It does not run for the first entry, a socket replacement while the member is still connected, or a permanent removal. Restoring a room reconciles actual connections: members saved as connected whose sockets are gone receive `false`, and their later return receives `true`. Surviving sockets receive no extra callback.\n- `onLeave` runs only when a player is removed with reason `left`, `timeout`, or `kicked`. A dropped connection calls `onConnection` during the grace period and does not call `onLeave`.\n- `onEnd` runs after the callback that requested `room.end`, with the final result and status `ended` or `finished`. Automatic room endings also use it, except closure of an already `finished` match, which must not run it twice.\n- `onRestart` runs when a rematch starts, after clearing the result and selecting the next status. Readiness is reset by default or restored with `keepSetup`. Player-created rooms prepare `lobby`, or `countdown` with `keepSetup`. Matchmaking prepares `waiting` at the deadline exposed to clients as `room.metadata.rematch.deadline`, eight seconds after the result, then starts the countdown if the minimum is met. It is optional; `room.state` is preserved unless the game changes it.\n\nThere is no `onResume` callback. A sleeping room restores its saved state without calling one. When a scheduled time arrives, the room invokes the method named by `room.schedule`.\n\nFor a turn-based game, store the active player's id and pause that turn when the player disconnects. This also works with `tickRate: 0`, because callback state changes are published immediately:\n\n```js\nonConnection(room, player, connected) {\n if (room.state.turnPlayerId === player.id) {\n room.state.turnPaused = !connected;\n }\n},\nonMessage(room, player, message) {\n if (room.state.turnPaused || player.id !== room.state.turnPlayerId) return;\n applyTurn(room, player, message);\n},\n```\n\nIf turns have deadlines, save the remaining time when pausing and calculate a new deadline on return. Scheduled handlers must check whether the turn is still paused or current. Decide separately in `onLeave` how to handle a permanent departure. Secret redelivery remains a client responsibility through `room.onConnection`; see [Hidden information](#hidden-information).\n\nThe room object provides:\n\n```js\nroom.id;\nroom.seed;\nroom.mode;\nroom.status;\nroom.tick;\nroom.tickRate;\nroom.result;\nroom.state;\nroom.players;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.setRole(playerOrId, role);\nroom.setTeam(playerOrId, team);\nroom.end(result);\nroom.end(result, { rematch: true });\n\nawait room.save('round', value);\nawait room.load('round');\nroom.schedule(milliseconds, 'methodName', payload);\n\nroom.daily.day;\nroom.daily.seed;\nroom.daily.expiresAt;\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 512 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and closes the room unless rematch is enabled with `true` or an options object. See [Rematch in the same room](#rematch-in-the-same-room) for readiness, callback order, timer cancellation and the waiting deadline. Room saves use keys with the same format as player save keys and values up to 256 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes.\n\n### Recognized match results\n\n`room.end(result)` still accepts any JSON. The optional `MatchResult` type is exported by the contracts and by `@caisual/kit` and `@caisual/kit/server`:\n\n```ts\ntype MatchResult = {\n standings: Array<{ playerId: string; score?: number; rank?: number }>;\n winners?: string[];\n draw?: boolean;\n unit?: 'points' | 'time' | 'distance' | string;\n data?: JsonValue;\n} & Record<string, JsonValue>;\n```\n\nOrder `standings` from first place onward. Scores must be finite numbers; ranks are positive safe integers. `draw: true` takes precedence; otherwise `winners` identifies the winners. Without `winners`, the first row wins, together with rows sharing its explicit rank. Equal scores alone do not imply a draw. An explicit empty `winners` list means nobody won.\n\nThis shape is a convention, not a screen: the game reads `room.result` and draws its own result. `time` and `distance` in `unit` do not convert values or imply a measurement scale. **`room.result` keeps the original JSON without normalization**, including `data` and any other game fields. Results are public to every room member, so keep secrets elsewhere.\n\n```js\nroom.end({\n standings: [{ playerId: winner.id, score: 12, rank: 1 }, { playerId: other.id, score: 9, rank: 2 }],\n winners: [winner.id], unit: 'points', data: { rounds: 3 },\n}, { rematch: true });\n```\n\n### Hidden information\n\nEverything in `room.state` reaches every player in the room. Never store cards in hand, secret roles, fog of war, or any other private value there.\n\nKeep secrets in room saves through `room.save` and `room.load`, which are server-only, or in module-level variables in `server.js`, keyed by room when needed. Deliver a secret to one player with `room.send(player, { type: 'hand', cards })`. `onJoin` runs only on the player's first entry, not on reconnection, so the client requests its secrets for the current connection and every later reconnection:\n\n```js\nif (room.connection === 'connected') room.send({ type: 'hand?' });\nroom.onConnection((state) => {\n if (state === 'connected') room.send({ type: 'hand?' });\n});\n```\n\nThe server answers from `onMessage` with `room.send(player, { type: 'hand', cards })`.\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 fixed at room creation and shared by rooms created for that game on the same 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### WebAssembly on the server\n\nUse WebAssembly only to bring an existing engine, such as physics, pathfinding or a Rust simulation. For new game logic, start with JavaScript.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\nimport engine from './physics/add.wasm';\n\nconst engines = new WeakMap();\nfunction instance(room) {\n if (!engines.has(room)) engines.set(room, new WebAssembly.Instance(engine, {}));\n return engines.get(room);\n}\n\nexport default defineGame({\n tickRate: 0,\n onCreate(room) {\n room.state = { sum: instance(room).exports.add(19, 23) };\n },\n onMessage(room) {\n room.state.sum = instance(room).exports.add(room.state.sum, 1);\n },\n});\n```\n\nA default import such as `import engine from './physics/add.wasm'` returns an already compiled `WebAssembly.Module`. Instantiate it in `onCreate` or on first use with `new WebAssembly.Instance(engine, imports)`. Paths must start with `./`, stay inside the game folder and contain no `..` segments. Named, namespace and dynamic imports of `.wasm` are not supported. Shared memory and threads are not supported.\n\nThe room server accepts at most **8 `.wasm` files, 8,000,000 bytes per file and 16,000,000 bytes in total**, in addition to the 4,000,000-byte `server.js` limit. The CLI discovers them from the bundle and uploads them privately alongside the server, checking size and SHA-256. There is no manifest change; `requires.wasm` describes the browser client only. `caisual check` and publish enforce these limits, and `caisual dev` compiles the same files locally. Restart dev after changing a binary.\n\nBudget for compilation when the room wakes: a large binary makes resumption slower. The platform may reuse compiled code for the same game version, but reuse is not guaranteed. Instances and their memory are temporary, so recreate an instance on first use after a wake and restore any engine state from room JSON state or room saves. `onCreate` does not run again after a wake. Never put a module, instance or binary memory in `room.state`.\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`. The optional `tickRate` field in `state` and `snapshot` protocol messages updates client `room.tickRate`; older clients ignore the added field. A frequency change sends a state diff even when its patch is empty.\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` during a match, contains its result in `finished` or `ended` and inside `onEnd`, and returns to `null` before `onRestart`.\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(result)` without rematch, when its two-minute rematch wait expires, after 30 days without player input, entry, or a state change with `{ error: 'expired' }`, or after five minutes without any members. To offer a \"come back\" action, store `room.code` with `c.save.set()` and call `c.room.join(code)` later. 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: 64 keys per player per game, 256 KB per value.\n- Room state: 512 KB of plain JSON.\n- Game messages: 64 KB each and 30/s per connection; excess messages are dropped with at most one `rate_limited` error per second. Service messages have a separate 30/s budget. More than 150 attempts/s in either budget for three consecutive one-second windows closes with 4008. Oversized frames close with 4009 `message_too_large`.\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 signaling also uses the separate service-message budget; audio traffic does not consume either message budget.\n- Room save values: 256 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 same handshake as the site, so `c.connected` is `true` and the game receives a local guest identity. `?lang=` chooses the language preference, resolved against the manifest: `?lang=ja` gives `c.player.language === \"ja\"` when declared. Friends are empty locally, so `c.crew.friends` is `[]`; everything else, including saves, daily data, invitations and rooms, works on local data. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nUse `npx @caisual/cli dev --day 2026-09-04` to pin the UTC day used by client and room daily seeds. The flag accepts only a real date in `YYYY-MM-DD` format; without it, dev uses today's UTC date. Real clocks and room timers keep running normally. Saves, identities and rooms are shared across these dates. Existing rooms retain their creation context; new rooms follow the selected day. `expiresAt` follows the real clock even with `--day`. A changed flag takes effect after restarting dev and reloading the game.\n\nOpen the printed `/__caisual/players?n=4` URL for 1 to 8 independent guest frames. Use the game's own menu to create a room in one frame and join its code in the others. Each frame has **Drop** (1 to 60 seconds, default 3) to interrupt that guest's room connection. Phone frames are 390 x 844; the desktop preset is 960 x 640. Add `&lang=it` to test Italian.\n\n`dev --latency 120 --jitter 40 --loss 2` delays room WebSocket messages in both directions. Latency and jitter are integer milliseconds from 0 to 60000; loss is a percentage from 0 to 100 and may be fractional. Jitter and loss require `--latency`, which may be zero. Jitter varies delay uniformly within plus/minus the supplied value, clamped at zero, and preserves message order. Loss discards whole application messages, including protocol messages, to exercise recovery; it is not a model of TCP packet retransmission. HTTP, matchmaking and audio are unaffected. Drop closes the guest's room sockets and prevents successful reconnects for the selected duration; the kit's retry schedule can make the return later.\n\nClient files are read on each request: reload the portal or frame after editing, or rebuild into `client/` first if using a bundler. There is no automatic browser reload. Restart dev after changing `caisual.json`, `server.js`, or any server import (including shared client physics). Rooms restore from `.caisual-dev/`; changing the shape of their state may require creating a fresh room. A busy port error suggests a command with a currently available port.\n\nEvery `init` variant generates Node test and optional Playwright browser scripts. Playwright is a development dependency of the generated game, never of the CLI. See [Local dev](/docs/local-development#testing-with-a-browser) for installation and the full browser workflow.\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`, when publishing on Caisual. That URL exists only in `caisual dev` and in the published game.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. Single-player modes reject room operations with `mode_local`. Multiplayer modes require `server.js`.\n\nTo run from any other static server, install `@caisual/kit` from npm and import it with a bundler as `import { caisual } from '@caisual/kit'`. In that build standalone mode applies: `c.connected` is `false`, saves use local storage, 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\nSingle player runs in the browser and never touches the server; a room exists only for two or more players. A mode is local when its resolved `players.max` is 1. Modes with `players.max > 1` require `server.js`. The manifest carries no text for the platform to draw: the names the player reads live in the game's own dictionaries. A mode enables instant matchmaking with `\"matchmaking\": true`.\n\n```json\n{\n \"players\": { \"min\": 2, \"max\": 4 },\n \"modes\": [\n { \"id\": \"practice\", \"players\": { \"min\": 1, \"max\": 1 } },\n { \"id\": \"duel\",\n \"matchmaking\": true }\n ]\n}\n```\n\nNo manifest field is required for identity, saves or the daily challenge. A mode may override `players: { min, max }`; otherwise it inherits the root range. `mode: null` uses the root range. Use `matchmaking: true` for instant online entry. Player-created rooms always have a lobby; matchmaking rooms never do. Roles, teams, voice and persistence remain game-wide. A mode with `players.max: 1` runs locally and needs no server. See [publish.md](./publish.md#caisualjson) for every field.\n\n## Required game images\n\nEnglish (`en`) is required in `languages`; three distinct files inside `client/` with no text inside are also required: cover 1536x1024 (3:2), card 1024x1024 and icon 1024x1024, each PNG, JPEG or WebP and at most 2 MB. See [Manifest](https://caisual.com/docs/manifest#required-game-images).\n";
|
|
1107
|
+
var kit_default = "# Caisual game kit\n\nMultiplayer budget: **100 kB/s per recipient and 2 MB/s per room**, before compression, over rolling 5-second windows. At 20 updates/s, budget **5 kB per update**. Keep visual trails and animation on the client. Game input remains limited to 30 messages/s per connection.\n\nWarnings start at 80% of either budget. These are platform budgets, not measured phone capacity. We count UTF-8 bytes of every application message actually sent to each recipient, including snapshots, changes and replies. Room traffic is their sum. Voice audio and transport headers are separate. Recipient and room peaks can come from different windows.\n\n`caisual dev` prints the budget and warns when measured traffic reaches it. Static `caisual check` does not prove network performance. Before publication, Caisual runs the uploaded server in an isolated room for every mode with resolved `players.max > 1`, fills it to its declared maximum and exercises 20 seconds of simulated time without game input. A measured excess refuses publication. A probe that cannot start or complete does not pass. No creator-written network test is required. A passing probe does not cover every action or long match.\n\nReal matches are measured with the same counter. Your account shows each version's worst 5-second rates and its publication probe separately. Any excess is a warning. Three consecutive measurements above either budget, at least 5 seconds apart in the same room, block new rooms for that version. Existing rooms keep running and accepting permitted joins. Publish a corrected version to open new rooms again. Monitoring never slows the simulation, drops state updates or suspends a match. There is no operations-per-tick limit. Quiet periods reset the consecutive count; room process restarts begin a new observation period, while saved version peaks and blocks remain.\n\nYour account also shows game opens and new online rooms per game over the last 7 and 30 UTC days, including today. The platform records these counts automatically.\n\nThe kit gives a published game a stable player identity, cloud saves, a daily challenge seed, multiplayer rooms with server-owned state, and the player's friends.\n\nThe kit is a single JavaScript module with no dependencies. It never touches the page and never draws anything: the game fills the window and draws its own menu, lobby, results and HUD.\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?v=0.25.1';\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, language }`. `id` is stable for the player across sessions and across every version of the game. `name` is the account username, or a stable `Guest-XXXX` name derived from the player id. The four-character suffix uses `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, excluding I, O, 0 and 1; it helps distinguish guests but is not a unique identifier. `guest` is `true` for players without an account. `language` selects game strings. On first sign-in to an account without a player identity, the browser guest is adopted with its existing id and saves. An account that already has a player identity uses that identity instead; guest data is not merged.\n- When not connected, `c.player` has `id: \"local\"`, `name: \"Guest\"`, `guest: true` and a `language`. If the host answered, its language information is kept; without a handshake, `language` is the normalized `navigator.language`, or `en`.\n\nDo not store the ticket or reimplement the handshake. The kit handles identity, renewal, and retries.\n\nAnyone who can open the game can use its player services and multiplayer. This includes guests who have the link to a game awaiting review.\n\n## Game language and strings\n\n`c.player.language` is the game's language, chosen by the site. Use it for game strings and formatting.\n\nThe kit resolves the player's explicit portal language choice, otherwise `navigator.languages` in order, against `manifest.languages`. For each preference it tries the exact tag and then its parent tags; if none of the preferences match, it uses the game's first declared language. The result is always a normalized declared tag. For example, `ja-JP` with `languages: [\"en\", \"ja\"]` selects `ja`. The site itself speaks English, Italian, Spanish, French, German, Portuguese and Japanese; a game may declare any language.\n\nA localized portal URL counts as a language choice. The language selector remembers explicit choices, including English; without either, the browser's ordered preferences apply. The handshake sends `language`, `languagePreferences` and `gameLanguages`. The kit resolves the game language, including when player services fail after a successful handshake.\n\nWithout a handshake, no declared language list is available: `language` is the raw preference from `navigator.language`, normalized as a BCP 47 tag, or `en` if invalid or unavailable. In `caisual dev`, `?lang=ja` selects `ja` when the manifest declares it. Without `?lang=`, dev uses `navigator.languages` in order.\n\nPut all game UI strings in flat JSON dictionaries named `client/i18n/<lang>.json`. Use canonical BCP 47 filenames, for example `en.json`, `it.json`, `pt.json`, `pt-BR.json`. Every value is a string; keys are identical across dictionaries. Text can contain named placeholders such as `{n}`.\n\nDeclare supported languages in `caisual.json`, always including `en`. English is required alongside the game's own languages; the first entry is the default and may be another language. This complete manifest supports a local game:\n\n```json\n{\n \"manifest\": 1,\n \"cover\": \"cover.png\",\n \"card\": \"card.png\",\n \"icon\": \"icon.png\",\n \"id\": \"three-lights\",\n \"name\": \"Three Lights\",\n \"platform\": \"both\",\n \"languages\": [\"en\", \"it\"],\n \"modes\": [{ \"id\": \"solo\" }]\n}\n```\n\n`client/i18n/en.json`:\n\n```json\n{ \"score\": \"Lights: {n} / 3\", \"light\": \"Light up\", \"done\": \"Complete\" }\n```\n\n`client/i18n/it.json`:\n\n```json\n{ \"score\": \"Luci: {n} / 3\", \"light\": \"Accendi\", \"done\": \"Tutte accese!\" }\n```\n\nLoad the dictionary once during setup. The returned function is synchronous and can be used in every draw call:\n\n```html\n<!doctype html>\n<html>\n<head><meta charset=\"utf-8\"><title>Three Lights</title></head>\n<body style=\"margin:0;min-height:100dvh;display:grid;place-content:center\">\n <p id=\"score\"></p>\n <button id=\"light\" disabled></button>\n <script type=\"module\">\n import { caisual } from '/__caisual/kit/v1.js?v=0.25.1';\n const c = await caisual.connect();\n const t = await c.text();\n document.documentElement.lang = c.player.language;\n const score = document.querySelector('#score');\n const light = document.querySelector('#light');\n let n = 0;\n function draw() {\n score.textContent = n === 3 ? t('done') : t('score', { n });\n light.textContent = t('light');\n light.disabled = n === 3;\n }\n light.onclick = () => { n += 1; draw(); };\n draw();\n </script>\n</body>\n</html>\n```\n\n`c.text(): Promise<Text>` makes one request to the game's own origin, tied to the version currently open. Caisual and `caisual dev` read the matching files and merge them per key: `pt-BR` then `pt` then the manifest's default language. Longer tags fall back through their parent tags, such as `zh-Hant-TW`, `zh-Hant`, `zh`. The default file is tried once. If no file contains a key, `t` returns that key. Empty strings are valid translations.\n\nConcurrent and later `c.text()` calls share the same promise and translator for that connection. There are no dependencies, eager downloads, or per-call network requests. Missing files, invalid dictionaries and network failures do not prevent startup. If the Caisual text service is unavailable, for example on a plain static host outside Caisual, the translator returns keys; it does not probe other URLs. Use `caisual dev` to preview the complete convention.\n\n`t('score', { n: 3 })` replaces named placeholders with strings or numbers. An omitted placeholder stays unchanged, such as `{n}`. The result is plain text, with no HTML processing, plural rules or automatic translation. Set `textContent` or draw it on the canvas; do not insert it as HTML. A new document gets the host's current language and a fresh translator.\n\n`description` accepts a string or a language-to-text object, and resolves from the page language in the catalogue, profiles, invitations and metadata. `description` is an optional one-line subtitle, at most 80 characters after trimming whitespace in every language , for example `{ \"en\": \"Grow huge. Guard your tail. Devour light in a cosmic arena.\" }`. Each translation must be non-empty and use a key declared in `languages`; an absent field or a plain empty string omits the subtitle. `name` and `tags` keep their existing forms. See [manifest languages and validation](./publish.md#game-translations) for CLI checks.\n\n## The game draws everything\n\nCaisual draws nothing over the game. The game gets the whole window and builds its own menu, lobby, invitation, result and \"play again\" from the calls below. There is no platform overlay, no menu, no pill, no reserved rectangles, no keyboard shortcut and no end-of-match screen. `env(safe-area-inset-*)` inside the game document is the real safe area.\n\n`caisual init` writes that minimal menu in `client/menu.js`: solo or online, create room, copy invite, join with a code, the player list with ready, start, and play again. It is about a hundred lines with no dependencies. Copy it, recolour it, or delete it and draw the same actions in your own style.\n\n```js\nconst c = await caisual.connect();\n\n// Solo: the state belongs to the game.\nstartLocalRun();\n\n// Online: the state belongs to the server.\nconst room = await c.room.create({ mode: 'duel' });\nroom.onPlayers((players) => drawLobby(players));\nroom.onStatus((status, result) => {\n if (status === 'playing') hideMenu();\n if (status === 'finished') drawResult(result); // then room.restart() for a rematch\n});\nroom.ready(true);\n```\n\nNothing has to be announced at startup: there is no handshake call, no session object and no capability flag. Draw your menu when the assets are ready. `c.connected` is `false` when the game runs outside caisual.com: rooms and friends are unavailable, everything else works on local data.\n\n### Full screen\n\nThe game fills the window. `html`, `body` and the game surface are 100% of the viewport: no maximum width, no header, no footer, no editorial frame, and no document scrolling at 1366x768 or 390x844, safe areas included. Only the HUD, the menu and compact controls sit over the scene.\n\nAim for the playable field to cover at least 70% of the visible area on desktop and 60% on mobile, counting only what shows or controls the game. A board with a fixed aspect ratio cannot always reach that: a square board on a 1366x768 window tops out near 56% before any HUD. That is the declared geometric exception: the board must then fill at least 90% of the largest rectangle that fits the area left free, and the HUD must have a stated ceiling, typically 48 to 64 pixels on desktop and about 160 pixels of controls on a phone.\n\n## Friends and party\n\n`c.crew` mirrors the player's Caisual friends inside the game, so the game can draw its own friends list and its own invitations. The platform owns the relationships; the game reads them and asks for the few actions it needs.\n\n```js\nc.crew.available; // false in a copy of the game running outside caisual.com\nc.crew.connected; // the friends channel is live\nc.crew.you; // { id, name } or null\nc.crew.friends; // [{ id, name, online, game: { slug, name, iconUrl } | null, room: { code } | null }]\nc.crew.party; // { id, leader, members: [...] } or null\nc.crew.invites; // [{ party, from: { id, name }, at }]\n\nconst stop = c.crew.onChange((crew) => drawFriends(crew));\n\nc.crew.createParty();\nc.crew.invite('player-id');\nc.crew.accept('party-id');\nc.crew.decline('party-id');\nc.crew.kick('player-id');\nc.crew.leave();\n\nconst room = await c.crew.join('player-id'); // enter the friend's room, in this game\nc.crew.follow('player-id'); // the site opens the friend's game, even another one\n```\n\n`onChange` repeats the current value immediately and returns a function that removes the listener. `join()` rejects with `no_room` when that player is not in a room, `other_game` when the friend is playing something else, which is what `follow()` is for, and `friend_not_found` for an unknown id. `follow()` hands navigation to the site, so the page changes. Outside caisual.com the lists stay empty, the actions do nothing, and `join()` rejects with `offline`.\n\nThe kit reports the player's current room to the site by itself, so friends can also join from the site with one click.\n\n## Daily challenge\n\n`c.daily` describes the day selected when the connection opened. `day`, `seed` and `expiresAt` stay fixed for that connection, including across UTC midnight. `expiresAt` is the next UTC midnight in milliseconds on the server clock.\n\n```js\nc.daily.day;\nc.daily.seed;\nc.daily.expiresAt;\nconst random = c.daily.rng();\nconst stop = c.daily.onChange(({ day, seed, expiresAt }) => {\n offerNextDailyRun({ day, seed, expiresAt });\n});\n```\n\n`onChange` reports a new `{ day, seed, expiresAt }` when the current UTC day changes. It returns an unsubscribe function and does not immediately replay the initial value. A suspended browser or a connection failure can delay the notification; the kit retries and reports the latest day when it can. The event does not mutate `c.daily` or reseed either generator. `rng()` always creates a fresh generator from the connection's original seed, and `random()` keeps advancing the original shared generator. Use the event's context explicitly for a new daily run, or open a new document. Repeated `connect()` calls return the same connection.\n\n`day` is a UTC date such as `\"2026-09-04\"`; `seed` is an unsigned 32-bit integer shared by all players of that game on that day. Both generators produce values in [0, 1). `c.time.now()` is in milliseconds aligned with the portal clock. Without a connection, daily data uses the local clock and hostname, with the same listener and generator behavior.\n\nOn the server, `room.daily` is `{ day, seed, expiresAt }`, fixed at **room creation**, persisted across sleep and rematches. Its seed matches a client connection opened for that game on the creation day. A client connected yesterday can therefore have a different `c.daily` from a room created today: send the room's daily context through game state when rendering its course. To switch a persistent or rematched room to a new daily course, create a new room.\n\n`caisual dev --day YYYY-MM-DD` fixes the simulated day and seed for new connections and rooms. Clocks stay real: `expiresAt` is the next **real** UTC midnight at connection or room creation, so comparing it with `c.time.now()` or `room.time.now()` remains valid even for a simulated date. Restored rooms keep their original daily context. Restart dev and reload to change the flag; create a new room for the newly selected day.\n\n## Saves\n\nEach player has up to 64 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## 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\n`device.isolated` measures the browser's actual `crossOriginIsolated` state. Games embedded in the portal report `false`; shared memory and threaded WebAssembly are unavailable there. This runtime probe does not enable isolation.\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### Two front ends, one game\n\nKeep one `client/index.html`, one game ID and one server. With `platform: \"both\"`, choose separate front ends in that entry without navigating or adding another iframe:\n```js\nimport { caisual } from '/__caisual/kit/v1.js?v=0.25.1';\nconst c = await caisual.connect();\nlet preference = null;\ntry { preference = localStorage.getItem('layout'); } catch {}\nconst touch = preference === 'touch' || (preference !== 'desktop' && (c.device.mobile || matchMedia('(pointer: coarse)').matches));\nconst screen = touch ? await import('./touch/main.js') : await import('./desktop/main.js');\nscreen.mount({ c, root: document.querySelector('#app') });\n```\nOffer a manual layout choice, persist it when storage is available, and keep rules and room connections shared. Both front ends use relative asset paths inside `client/`.\n\n## Game version changes\n\nNew games use the current version. Existing rooms retain their version for their whole life, including invitations, typed codes and friends. Matchmaking never mixes versions; an accepted reservation can finish on its original version. Saves remain per game, with data compatibility handled by the creator. See [Versions and rollback](./publish.md#versions-and-rollback).\n\nA room create or match operation rejects with `version_outdated` and `currentVersion` when the loaded game is no longer current. A join or reconnect rejects with `version_mismatch` and `roomVersion` when the room uses another version.\n\nSubscribe with `c.room.onError(listener)`, which returns an unsubscribe function. The error has `code`, `message`, and the applicable version number. The operation also rejects with that error. `c.room.reload()` reloads the page on the current game after `version_outdated`, or on the last mismatched room after `version_mismatch`. Show a button calling it after either error: it is the only way out of both.\n\n`caisual dev` always uses game version 1 and does not simulate version changes.\n\n## Rooms\n\nA room brings players into the same running game. Single player runs in the browser and never touches the server; a room exists only for two or more players. Creating and joining require a published `server.js` and a mode with `players.max > 1`. A local mode rejects room operations with `mode_local`.\n\nAn optional [MatchResult](#recognized-match-results) in `room.end` gives the game a ready shape for winners and standings, while `room.result` keeps the original JSON.\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.tickRate;\nroom.latency;\nroom.invite(); // { code: \"ABC234\", url: \"https://caisual.com/r/ABC234\" }\n```\n\nA room you create always has a lobby. Matchmaking rooms never have one.\nRead `room.origin` (`player` or `matchmaking`) to distinguish them. During play, a player-created room only admits returning members. Matchmaking admits new players up to `players.max`.\n\nPass a mode id from the manifest to `create({ mode })`, or `null` to use the root configuration. Optional `players` on that mode replaces the root range. Joining keeps the configuration and origin of the room being joined. `join()` uses `c.room.invited`; without an invitation, pass the six-character code explicitly. `invite()` returns the code and the link to copy.\n\n### Friends in a room\n\nThe kit reports the player's current room to the site by itself, so friends can see where the player is and join. See [Friends and party](#friends-and-party) for the data and the calls.\n\n### Matchmaking\n\nDeclare `\"matchmaking\": true` on a mode with resolved `players.max > 1`.\n\n```js\nconst room = await c.room.match({ mode: 'arena' });\n```\n\nYou enter immediately, even alone. There is no search screen or lobby. Roles and teams are assigned by the server. Below `players.min`, `room.status` is `waiting`: draw a playable practice area with a short notice above the scene. At the minimum, a three-second countdown starts. New players can join during countdown and play without resetting it.\n\nA normal round ends in `finished` and restarts automatically at `room.metadata.rematch.deadline`, eight seconds after the result. Compare the deadline with `room.serverTime()`; see [Rematch in the same room](#rematch-in-the-same-room). `ready()` and `restart()` are ignored. Lobby role and team calls fail with `matchmaking_room`; gameplay `requestRole()` remains available when the server supports it. Make character and equipment choices during the first seconds of play with a timer.\n\nPass an optional `signal` to cancel before assignment (`cancelled`). Errors are `invalid_request`, `mode_local`, `no_server`, `rate_limited`, `offline`, `version_outdated` and `room_full`. See [Matchmaking](/docs/matchmaking) for examples and the full waiting rules.\n\nRoom status is one of:\n\n- `waiting`: a matchmaking room is below `players.min`. Draw a playable practice scene.\n\n- `lobby`: players are joining and choosing their setup.\n- `countdown`: play begins at the announced server time, three seconds after the start condition is met.\n- `playing`: the game server is running the match.\n- `finished`: the match is over and the room is waiting for a rematch, with sockets open and `room.result` available.\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 }` when the player was kicked, `{ closed: 4004 }` when the room ended, `{ closed: 4005 }` when the published version closed, or `{ closed: 4006 }` when the same player opened the room in another tab.\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\n\nroom.ready(true);\nroom.setRole('captain');\nroom.setTeam(1);\n```\n\n`ready`, role and team are the lobby actions for player-created rooms: draw the roster from `room.players` and call them from your own lobby. **Nobody hosts and nobody presses start.** As soon as every connected player is ready and the player, role and team minimums from the manifest are met, the room begins a three-second countdown on its own. If someone joins during the countdown, which they may, or takes back their readiness, or a minimum stops being met, the room returns to the lobby. A role or team change in the lobby clears that player's ready state. Every room member is a player. If all declared roles are full, entry fails with `room_full` before adding a member, even below `players.max`. Roles must be declared in the manifest; assigning an undeclared role fails with `invalid_role`.\n\n### Rematch in the same room\n\nMatchmaking rooms restart automatically eight seconds after a normal round ends with at least one player. `restart()` and `ready()` are ignored. Reset state in `onRestart`; the next phase is `waiting` below the minimum, otherwise `countdown`. See [Matchmaking](/docs/matchmaking).\n\nA room empty for five minutes always becomes `ended`, even during `finished`, without a rematch.\n\n\nIn player-created rooms, the server opts in per match with `room.end(result, { rematch: true })`. The room becomes `finished`, keeps its code, members, state and open connections, and exposes the result through `room.result` and `onStatus('finished', result, at)`. Voice stays connected. `room.end(result)` or `{ rematch: false }` still ends the room permanently with status `ended` and close code 4004.\n\nDuring `finished`, `room.metadata.rematch` is `{ keepSetup, deadline }`, already available inside `onStatus('finished', result, at)`. `deadline` is server time in milliseconds, on the same clock as `at` and `countdownAt`; compare it with `room.serverTime()`. In a matchmaking room, the next round starts automatically at `deadline`, eight seconds after the result. In a player-created room, the room closes at `deadline`, after two minutes, if not everyone has accepted and no rematch has started. Once the rematch starts, `room.metadata.rematch` becomes `null`.\n\nFor matchmaking, draw the remaining time on each render:\n\n```js\nconst rematch = room.metadata.rematch;\nif (room.status === 'finished' && room.origin === 'matchmaking' && rematch) {\n const seconds = Math.max(0, Math.ceil((rematch.deadline - room.serverTime()) / 1000));\n draw(`next round in ${seconds} s`);\n}\n```\n\nWith `rematch: true` in a multiplayer room, each connected player calls `room.restart()` once to accept the rematch. In `finished`, `room.players[].ready` means rematch readiness. The rematch starts by itself as soon as every connected player has accepted and the mode's `players.min` is met, including when a departure leaves that condition satisfied. Repeated calls do nothing. Calling outside `finished` fails with `rematch_unavailable`.\n\nDraw \"Play again\" with the readiness count. No member is removed for declining.\n\nAt the start, the kit clears the result to `null` and all readiness flags, then calls optional `onRestart(room)` with status `lobby`. **The kit does not reset `room.state`.** Reset match data in `onRestart`, keeping series scores or other data as needed. Players choose their setup and get ready again before the normal countdown and `onStart`. Clients receive the new state and an `onStatus` transition with a null result. The room identity, seed and tick sequence are retained, so the same room object stays valid. Listen to `room.onState` and `room.onStatus`.\n\n### Fast rematches\n\nThe existing `rematch: true` flow above is unchanged for multiplayer rooms. To shorten it, use:\n\n```js\nroom.end(result, { rematch: { keepSetup: true } });\n```\n\n`keepSetup` defaults to `false`. It restores the previous readiness flags, keeps roles and teams, and skips the lobby: `onRestart` runs with status `countdown`, followed by the usual three-second countdown and `onStart`. The result clears before `onRestart`. Readiness during `finished` is still consent for the next match, separate from the previous setup. Player, role and team minimums are rechecked during the countdown; if they fail, the room returns to the lobby so the setup can be repaired.\n\nMembers who have not accepted remain in the room and join the next phase; they are not removed. Without `keepSetup`, the next phase is the usual lobby.\n\n\nThe waiting rules are:\n\n- All pending `room.schedule` handlers are cancelled when the match finishes, including handlers already due in the same batch. Scheduling during `finished` has no effect. Schedule new work in `onRestart` or `onStart`. Tick callbacks stop immediately; game input during the wait is discarded, and queued continuous input is cleared on the client.\n- `onEnd` runs once for the completed match, with status `finished` and its result. A subsequent timeout only closes the room and does not call `onEnd` again.\n- Disconnecting clears that member's readiness. Disconnected players do not count toward readiness or the minimum, so a departure can be what starts the rematch. The usual 60-second reconnection grace applies; persistent members keep their seats after it. Rejoining requires a new readiness call. Connection and departure callbacks continue during the wait.\n- New members may join by invitation during the wait, up to the resolved `players.max`, and start unready. Player-created rooms reopen admission while `finished`. Disconnected members still occupy seats until removed. Roles and teams retain their existing capacity rules.\n- The room closes with 4004 exactly two minutes after entering `finished` if no restart is confirmed, retaining the last result. Readiness, joins and pings do not extend this deadline. It also applies to persistent rooms and survives sleep or restoration; it does not depend on active ticks.\n\n`finished` is a status, not a terminal connection state: the sockets stay open. Handle it explicitly in the game's status listener, and draw the result and the rematch action there.\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 for both tick-based and event-only servers. Full state is sent on entry, reconnection or resync when an update does not match the current tick; normal updates, including every hundredth tick, remain diffs. `room.serverTime()` returns milliseconds aligned with the room clock and is kept current by a ping every five seconds.\n\n`room.tickRate` reports the frequency configured by the game. Zero means event-only. `room.latency` is the smoothed round-trip time in milliseconds, or `null` before the first pong and after a dropped connection until the next pong. Each pong uses 20% of the new RTT and 80% of the previous estimate, with the first sample used directly. Read the property when drawing network status; there is no `onLatency` listener.\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. `room.send` calls while reconnecting throw an error with `code: \"offline\"`.\n\nUse `room.input(value)` for continuous controls, including calls from every animation frame:\n\n```js\nroom.input({ type: 'move', x: axisX, y: axisY });\nroom.onError(({ code }) => {\n if (code === 'rate_limited') showInputWarning();\n});\n```\n\n`input` copies and keeps only the latest JSON value in one slot. It coalesces updates and sends at most 30 times per second, or at the effective `room.tickRate` when that is lower and positive. With `tickRate: 0`, it still sends at most 30/s. It also waits for budget used by `send`. Values with the same JSON serialization are not resent on the same connection. Combine independent controls into that one value; there is no channel option. On the server it is an ordinary message passed unchanged to `onMessage`, exactly like `send`, with no extra envelope.\n\nDuring reconnection, `input` accepts updates without throwing `offline`. After the new welcome it sends only the latest value, even if it was sent on the previous connection. It never replays intermediate values or old commands. Use `send` for individual actions such as firing or confirming a turn; `send` still throws `offline` during reconnection. Invalid JSON input can throw `invalid_request`. Input stops after leaving, disconnecting intentionally or ending the room.\n\nGame messages are limited to 64 KB per frame in either direction and 30 per second per connection. Incoming service frames also have a 64 KB limit; state synchronization carries the separately limited room state. Excess messages are dropped; `room.onError` receives `rate_limited` at most once per second across both budgets. Protocol service messages, including ping, lobby actions, state requests and voice signaling, have a separate 30/s budget with the same drop policy. More than 150 attempts in each of three consecutive one-second windows in either budget closes the connection with 4008 `rate_limited`; the kit does not reconnect automatically after this abuse closure. Abuse windows start with the first message on the connection; a normal or empty window resets the sequence. Oversized game frames close with 4009 `message_too_large`, reported through `room.onError`; malformed frames use 4009 `bad_message`. Neither closure is retried automatically.\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\n`room.disconnect()` is the other departure: it stops the transport, the retries and voice without sending a leave, so the server keeps the seat under its own persistence and grace rules. It is not reversible on the same object; returning means entering again from the code, which is how a \"leave for now\" action works.\n\nA room also exposes `room.mode`, `room.countdownAt`, `room.connection`, `room.metadata`, and the `onMetadata` and `onConnection` listeners. `connection` is one of `connecting`, `connected`, `reconnecting`, `disconnected`, `ended`, `closed`, or `replaced`, where `replaced` means the same player opened the room in another tab. These listeners do not repeat the current value: read the getter first.\n\n`room.onError(listener)` reports technical protocol errors of the room as `{ code, message }`; it is not the place where a game reads its own result.\n\n`await room.requestRole('scout')` asks the server for a role change during a match. It works only while the room is playing, only for a role declared in the manifest, and only when `server.js` defines `onRoleRequest(room, player, role)`; the server approves by calling `room.setRole`. Without that callback nothing changes. It is not a shortcut for changing roles from the browser.\n\nRoom creation, joining, and matchmaking reject with an `Error` carrying a stable `code`. Common codes are `invalid_request`, `mode_local`, `no_server`, `cancelled`, `room_not_found`, `room_full`, `room_playing`, `room_ended`, `rate_limited`, `invalid_ticket`, `internal_error`, and `offline`. `mode_local` means \"Single-player modes run in the browser and have no room.\" `no_server` means the published game has no multiplayer server. When `c.connected` is `false`, `create`, `join`, and `match` reject with `offline`.\n\n- `invalid_role`: a requested role id is malformed or is not declared in the manifest. Request a declared role id.\n- `role_change_unavailable`: the room is disconnected, is not playing, or `server.js` has no `onRoleRequest`. Wait for a connected playing state and provide that callback before offering the action.\n- `role_change_refused`: `onRoleRequest` returned without assigning the requested role. Leave the current role in place, or have the server approve with `room.setRole`.\n- `version_closed`: the room connection ended because its published version closed. Reopen the current game version and enter a current room.\n\nEvery listener call on a room returns a function that removes that listener: `onState`, `onPlayers`, `onStatus`, `onMessage`, `onMetadata`, `onConnection`, and `onError`.\n\n### Responsive action games\n\n1. Start with `npx @caisual/cli init --arcade my-arena`, a complete English/Italian canvas game with shared rules and tests.\n2. Accumulate `deltaSeconds` on the server and advance shared physics at a fixed 1/60 second step.\n3. Keep positions, collision or range checks, cooldowns and scores authoritative in `server.js`.\n4. Use `room.input()` for continuous controls and `room.send()` for discrete actions such as the starter's pulse.\n5. Number commands in the game and publish each player's last **applied** `ack` in `room.state`; transport sequence numbers are separate.\n6. Because `input()` coalesces values, send a bounded batch of unacknowledged commands; deduplicate on the server and consume at most one per simulation step.\n7. Predict your own entity with the shared step, replace it with each authoritative snapshot, then replay only commands after `ack`; ease corrections in the drawing only.\n8. Buffer remote samples by the `onState` timestamp and render behind `room.serverTime()`, accounting for RTT in `room.latency` and the effective `room.tickRate`.\n9. Clear pending controls on reconnection or a new round; keep the HUD inside the safe areas, and end with `standings` plus a `keepSetup` rematch.\n10. Run the generated browser fixture and `/__caisual/players?n=2` with `dev --latency 120 --jitter 40 --loss 2`; see [Testing with a browser](/docs/local-development#testing-with-a-browser).\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.\n\nThe game draws the voice controls, and must offer an explicit one: `join()` has to 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.\n\nThe room server authorizes every voice track by team and gain. Listening that is no longer allowed is refused or closed.\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 2 to change only local playback: 1 is normal and values above 1 amplify it.\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`, `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, // required, an integer from 0 to 60; 0 runs only in response to events\n onCreate(room) {},\n onStart(room) {},\n onJoin(room, player) {},\n onConnection(room, player, connected) {},\n onLeave(room, player, reason) {}, // \"left\", \"timeout\", or \"kicked\"\n onRoleRequest(room, player, role) {}, // approve with room.setRole\n onMessage(room, player, message) {},\n onTick(room, deltaSeconds) {},\n onEnd(room) {},\n onRestart(room) {},\n});\n```\n\n`tickRate` is the only required field: `defineGame` throws a `TypeError` when it is missing or is not an integer from 0 to 60. All callbacks are optional. A player is `{ id, name, guest, role, team, connected }`.\n\n### Callback order\n\n- `onCreate` runs once when the room is first created, before any player joins.\n- `onJoin` runs when a player first enters the room, not when that same member reconnects. The countdown completes before `onStart`, for both room origins.\n- `onStart` runs when the room changes to `playing`. The three-second countdown starts at the connected player minimum in matchmaking, or when all player-created room members are ready and setup minimums are met.\n- `onTick` runs for each active game tick when `tickRate` is greater than zero. `onMessage` runs for accepted client game messages, and `onRoleRequest` runs for an in-match role request when that callback exists. These events are processed serially, so their relative order is the order in which the room processes them.\n- `onConnection(room, player, connected)` runs with `false` when an existing member loses their connection and with `true` when that disconnected member returns. Both `player.connected` and `room.players` are already updated. It does not run for the first entry, a socket replacement while the member is still connected, or a permanent removal. Restoring a room reconciles actual connections: members saved as connected whose sockets are gone receive `false`, and their later return receives `true`. Surviving sockets receive no extra callback.\n- `onLeave` runs only when a player is removed with reason `left`, `timeout`, or `kicked`. A dropped connection calls `onConnection` during the grace period and does not call `onLeave`.\n- `onEnd` runs after the callback that requested `room.end`, with the final result and status `ended` or `finished`. Automatic room endings also use it, except closure of an already `finished` match, which must not run it twice.\n- `onRestart` runs when a rematch starts, after clearing the result and selecting the next status. Readiness is reset by default or restored with `keepSetup`. Player-created rooms prepare `lobby`, or `countdown` with `keepSetup`. Matchmaking prepares `waiting` at the deadline exposed to clients as `room.metadata.rematch.deadline`, eight seconds after the result, then starts the countdown if the minimum is met. It is optional; `room.state` is preserved unless the game changes it.\n\nThere is no `onResume` callback. A sleeping room restores its saved state without calling one. When a scheduled time arrives, the room invokes the method named by `room.schedule`.\n\nFor a turn-based game, store the active player's id and pause that turn when the player disconnects. This also works with `tickRate: 0`, because callback state changes are published immediately:\n\n```js\nonConnection(room, player, connected) {\n if (room.state.turnPlayerId === player.id) {\n room.state.turnPaused = !connected;\n }\n},\nonMessage(room, player, message) {\n if (room.state.turnPaused || player.id !== room.state.turnPlayerId) return;\n applyTurn(room, player, message);\n},\n```\n\nIf turns have deadlines, save the remaining time when pausing and calculate a new deadline on return. Scheduled handlers must check whether the turn is still paused or current. Decide separately in `onLeave` how to handle a permanent departure. Secret redelivery remains a client responsibility through `room.onConnection`; see [Hidden information](#hidden-information).\n\nThe room object provides:\n\n```js\nroom.id;\nroom.seed;\nroom.mode;\nroom.status;\nroom.tick;\nroom.tickRate;\nroom.result;\nroom.state;\nroom.players;\n\nroom.broadcast(message);\nroom.send(playerOrId, message);\nroom.kick(playerOrId);\nroom.setRole(playerOrId, role);\nroom.setTeam(playerOrId, team);\nroom.end(result);\nroom.end(result, { rematch: true });\n\nawait room.save('round', value);\nawait room.load('round');\nroom.schedule(milliseconds, 'methodName', payload);\n\nroom.daily.day;\nroom.daily.seed;\nroom.daily.expiresAt;\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 512 KB when serialized. `broadcast` sends a JSON message to everyone; `send` targets one player. `end` records a JSON result and closes the room unless rematch is enabled with `true` or an options object. See [Rematch in the same room](#rematch-in-the-same-room) for readiness, callback order, timer cancellation and the waiting deadline. Room saves use keys with the same format as player save keys and values up to 256 KB. `schedule` names a method on the definition so it can run even after a quiet room resumes.\n\n### Recognized match results\n\n`room.end(result)` still accepts any JSON. The optional `MatchResult` type is exported by the contracts and by `@caisual/kit` and `@caisual/kit/server`:\n\n```ts\ntype MatchResult = {\n standings: Array<{ playerId: string; score?: number; rank?: number }>;\n winners?: string[];\n draw?: boolean;\n unit?: 'points' | 'time' | 'distance' | string;\n data?: JsonValue;\n} & Record<string, JsonValue>;\n```\n\nOrder `standings` from first place onward. Scores must be finite numbers; ranks are positive safe integers. `draw: true` takes precedence; otherwise `winners` identifies the winners. Without `winners`, the first row wins, together with rows sharing its explicit rank. Equal scores alone do not imply a draw. An explicit empty `winners` list means nobody won.\n\nThis shape is a convention, not a screen: the game reads `room.result` and draws its own result. `time` and `distance` in `unit` do not convert values or imply a measurement scale. **`room.result` keeps the original JSON without normalization**, including `data` and any other game fields. Results are public to every room member, so keep secrets elsewhere.\n\n```js\nroom.end({\n standings: [{ playerId: winner.id, score: 12, rank: 1 }, { playerId: other.id, score: 9, rank: 2 }],\n winners: [winner.id], unit: 'points', data: { rounds: 3 },\n}, { rematch: true });\n```\n\n### Hidden information\n\nEverything in `room.state` reaches every player in the room. Never store cards in hand, secret roles, fog of war, or any other private value there.\n\nKeep secrets in room saves through `room.save` and `room.load`, which are server-only, or in module-level variables in `server.js`, keyed by room when needed. Deliver a secret to one player with `room.send(player, { type: 'hand', cards })`. `onJoin` runs only on the player's first entry, not on reconnection, so the client requests its secrets for the current connection and every later reconnection:\n\n```js\nif (room.connection === 'connected') room.send({ type: 'hand?' });\nroom.onConnection((state) => {\n if (state === 'connected') room.send({ type: 'hand?' });\n});\n```\n\nThe server answers from `onMessage` with `room.send(player, { type: 'hand', cards })`.\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 fixed at room creation and shared by rooms created for that game on the same 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### WebAssembly on the server\n\nUse WebAssembly only to bring an existing engine, such as physics, pathfinding or a Rust simulation. For new game logic, start with JavaScript.\n\n```js\nimport { defineGame } from '@caisual/kit/server';\nimport engine from './physics/add.wasm';\n\nconst engines = new WeakMap();\nfunction instance(room) {\n if (!engines.has(room)) engines.set(room, new WebAssembly.Instance(engine, {}));\n return engines.get(room);\n}\n\nexport default defineGame({\n tickRate: 0,\n onCreate(room) {\n room.state = { sum: instance(room).exports.add(19, 23) };\n },\n onMessage(room) {\n room.state.sum = instance(room).exports.add(room.state.sum, 1);\n },\n});\n```\n\nA default import such as `import engine from './physics/add.wasm'` returns an already compiled `WebAssembly.Module`. Instantiate it in `onCreate` or on first use with `new WebAssembly.Instance(engine, imports)`. Paths must start with `./`, stay inside the game folder and contain no `..` segments. Named, namespace and dynamic imports of `.wasm` are not supported. Shared memory and threads are not supported.\n\nThe room server accepts at most **8 `.wasm` files, 8,000,000 bytes per file and 16,000,000 bytes in total**, in addition to the 4,000,000-byte `server.js` limit. The CLI discovers them from the bundle and uploads them privately alongside the server, checking size and SHA-256. There is no manifest change; `requires.wasm` describes the browser client only. `caisual check` and publish enforce these limits, and `caisual dev` compiles the same files locally. Restart dev after changing a binary.\n\nBudget for compilation when the room wakes: a large binary makes resumption slower. The platform may reuse compiled code for the same game version, but reuse is not guaranteed. Instances and their memory are temporary, so recreate an instance on first use after a wake and restore any engine state from room JSON state or room saves. `onCreate` does not run again after a wake. Never put a module, instance or binary memory in `room.state`.\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### Room durability\n\nWhile the tick loop runs, the platform saves room state, timers and input sequences every five seconds. Joins, departures, changes in room status, results and voice changes trigger an immediate save. The platform saves the latest state before stopping the loop or going to sleep. With ticks off, including `tickRate: 0` rooms, changes are saved before the event batch is delivered. Explicit `room.save` writes are immediate in every room.\n\nIf the room process crashes, up to five seconds of play can roll back. The server sends connected clients a full snapshot of the restored state, which may have an earlier tick. Clients continue sending inputs with their current sequence numbers.\n\n### CPU budget\n\nCloudflare gives each invocation of the game server **500 ms of CPU time** and zero subrequests. An invocation can include a batch of inputs and a tick. The limit is more than twenty times the highest CPU time measured in the existing game tests. If the game reaches the CPU limit, the platform sends a `cpu_budget` error to players, ends the room with `{ error: 'cpu_budget' }`, and logs the game and version. [Cloudflare resource limits](https://developers.cloudflare.com/dynamic-workers/usage/limits/)\n\nIn `caisual dev`, Node measures the elapsed time of `onTick`, including time spent awaiting inside it. The developer gets a warning on the first tick in a series that exceeds the configured tick interval. `deltaSeconds` is the configured interval in seconds.\n\n`room.result` is `null` during a match, contains its result in `finished` or `ended` and inside `onEnd`, and returns to `null` before `onRestart`.\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(result)` without rematch, when its two-minute rematch wait expires, after 30 days without player input, entry, or a state change with `{ error: 'expired' }`, or after five minutes without any members. To offer a \"come back\" action, store `room.code` with `c.save.set()` and call `c.room.join(code)` later. 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: 64 keys per player per game, 256 KB per value.\n- Room state: 512 KB of plain JSON.\n- Game messages: 64 KB each and 30/s per connection; excess messages are dropped with at most one `rate_limited` error per second. Service messages have a separate 30/s budget. More than 150 attempts/s in either budget for three consecutive one-second windows closes with 4008. Oversized frames close with 4009 `message_too_large`.\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 signaling also uses the separate service-message budget; audio traffic does not consume either message budget.\n- Room save values: 256 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 same handshake as the site, so `c.connected` is `true` and the game receives a local guest identity. `?lang=` chooses the language preference, resolved against the manifest: `?lang=ja` gives `c.player.language === \"ja\"` when declared. Friends are empty locally, so `c.crew.friends` is `[]`; everything else, including saves, daily data, invitations and rooms, works on local data. Opening the portal URL in more browser tabs creates more local players, which makes multiplayer testing possible without publishing.\n\nUse `npx @caisual/cli dev --day 2026-09-04` to pin the UTC day used by client and room daily seeds. The flag accepts only a real date in `YYYY-MM-DD` format; without it, dev uses today's UTC date. Real clocks and room timers keep running normally. Saves, identities and rooms are shared across these dates. Existing rooms retain their creation context; new rooms follow the selected day. `expiresAt` follows the real clock even with `--day`. A changed flag takes effect after restarting dev and reloading the game.\n\nOpen the printed `/__caisual/players?n=4` URL for 1 to 8 independent guest frames. Use the game's own menu to create a room in one frame and join its code in the others. Each frame has **Drop** (1 to 60 seconds, default 3) to interrupt that guest's room connection. Phone frames are 390 x 844; the desktop preset is 960 x 640. Add `&lang=it` to test Italian.\n\n`dev --latency 120 --jitter 40 --loss 2` delays room WebSocket messages in both directions. Latency and jitter are integer milliseconds from 0 to 60000; loss is a percentage from 0 to 100 and may be fractional. Jitter and loss require `--latency`, which may be zero. Jitter varies delay uniformly within plus/minus the supplied value, clamped at zero, and preserves message order. Loss discards whole application messages, including protocol messages, to exercise recovery; it is not a model of TCP packet retransmission. HTTP, matchmaking and audio are unaffected. Drop closes the guest's room sockets and prevents successful reconnects for the selected duration; the kit's retry schedule can make the return later.\n\nClient files are read on each request: reload the portal or frame after editing, or rebuild into `client/` first if using a bundler. There is no automatic browser reload. Restart dev after changing `caisual.json`, `server.js`, or any server import (including shared client physics). Rooms restore from `.caisual-dev/`; changing the shape of their state may require creating a fresh room. A busy port error suggests a command with a currently available port.\n\nEvery `init` variant generates Node test and optional Playwright browser scripts. Playwright is a development dependency of the generated game, never of the CLI. See [Local dev](/docs/local-development#testing-with-a-browser) for installation and the full browser workflow.\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?v=0.25.1`, when publishing on Caisual. That URL exists only in `caisual dev` and in the published game.\n\nIf the game has `server.js`, room state is handled locally and stored under `.caisual-dev/` in the game folder. Single-player modes reject room operations with `mode_local`. Multiplayer modes require `server.js`.\n\nTo run from any other static server, install `@caisual/kit` from npm and import it with a bundler as `import { caisual } from '@caisual/kit'`. In that build standalone mode applies: `c.connected` is `false`, saves use local storage, 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\nSingle player runs in the browser and never touches the server; a room exists only for two or more players. A mode is local when its resolved `players.max` is 1. Modes with `players.max > 1` require `server.js`. The manifest carries no text for the platform to draw: the names the player reads live in the game's own dictionaries. A mode enables instant matchmaking with `\"matchmaking\": true`.\n\n```json\n{\n \"players\": { \"min\": 2, \"max\": 4 },\n \"modes\": [\n { \"id\": \"practice\", \"players\": { \"min\": 1, \"max\": 1 } },\n { \"id\": \"duel\",\n \"matchmaking\": true }\n ]\n}\n```\n\nNo manifest field is required for identity, saves or the daily challenge. A mode may override `players: { min, max }`; otherwise it inherits the root range. `mode: null` uses the root range. Use `matchmaking: true` for instant online entry. Player-created rooms always have a lobby; matchmaking rooms never do. Roles, teams, voice and persistence remain game-wide. A mode with `players.max: 1` runs locally and needs no server. See [publish.md](./publish.md#caisualjson) for every field.\n\n## Required game images\n\nEnglish (`en`) is required in `languages`; three distinct files inside `client/` with no text inside are also required: cover 1536x1024 (3:2), card 1024x1024 and icon 1024x1024, each PNG, JPEG or WebP and at most 2 MB. See [Manifest](https://caisual.com/docs/manifest#required-game-images).\n";
|
|
1145
1108
|
|
|
1146
1109
|
// src/dev.ts
|
|
1147
|
-
import { createHash as
|
|
1110
|
+
import { createHash as createHash2, createHmac, randomBytes, randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
|
|
1148
1111
|
import { promises as fs3 } from "node:fs";
|
|
1149
1112
|
import { createServer } from "node:http";
|
|
1150
1113
|
import { basename, dirname as dirname2, extname, join as join3, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
|
|
@@ -1154,8 +1117,8 @@ import { randomUUID } from "node:crypto";
|
|
|
1154
1117
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
1155
1118
|
import { dirname } from "node:path";
|
|
1156
1119
|
import { performance } from "node:perf_hooks";
|
|
1157
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
1158
1120
|
import { EventEmitter } from "node:events";
|
|
1121
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
1159
1122
|
var NOMI_RISERVATI2 = [
|
|
1160
1123
|
"www",
|
|
1161
1124
|
"api",
|
|
@@ -1548,6 +1511,7 @@ function seedStanza(roomId) {
|
|
|
1548
1511
|
return hashSeed(`caisual:room:${roomId}`);
|
|
1549
1512
|
}
|
|
1550
1513
|
var CHIAVE_NUCLEO = "nucleo";
|
|
1514
|
+
var VERSIONE_STATO = 2;
|
|
1551
1515
|
var PREFISSO_SAVE = "save:";
|
|
1552
1516
|
var LIMITE_FRAME = MASSIMO_BYTE_FRAME_STANZA2;
|
|
1553
1517
|
var LIMITE_STATO = 512 * 1024;
|
|
@@ -1556,6 +1520,7 @@ var GRAZIA_MS = 6e4;
|
|
|
1556
1520
|
var STANZA_VUOTA_MS = 5 * 6e4;
|
|
1557
1521
|
var ATTESA_RIVINCITA_MS = 2 * 6e4;
|
|
1558
1522
|
var COUNTDOWN_MS = 3e3;
|
|
1523
|
+
var INTERVALLO_SALVATAGGIO_MS = 5e3;
|
|
1559
1524
|
var RIPOSO_TICK_MS = 3e4;
|
|
1560
1525
|
var INATTIVITA_MS = 10 * 6e4;
|
|
1561
1526
|
var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
|
|
@@ -1607,9 +1572,9 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1607
1572
|
this.fineRichiesta = null;
|
|
1608
1573
|
this.applicandoAzioni = false;
|
|
1609
1574
|
this.ultimoStatoOsservato = "";
|
|
1610
|
-
this.
|
|
1611
|
-
this.voceDaPersistire = false;
|
|
1575
|
+
this.salvataggioImmediato = false;
|
|
1612
1576
|
const nucleo = this;
|
|
1577
|
+
this.tickRate = definizione.tickRate;
|
|
1613
1578
|
const daily = {
|
|
1614
1579
|
get day() {
|
|
1615
1580
|
return nucleo.richiediDati().daily.day;
|
|
@@ -1638,7 +1603,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1638
1603
|
return nucleo.richiediDati().tick;
|
|
1639
1604
|
},
|
|
1640
1605
|
get tickRate() {
|
|
1641
|
-
return nucleo.
|
|
1606
|
+
return nucleo.tickRate;
|
|
1642
1607
|
},
|
|
1643
1608
|
get result() {
|
|
1644
1609
|
return nucleo.richiediDati().result;
|
|
@@ -1705,22 +1670,13 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1705
1670
|
const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
|
|
1706
1671
|
const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
|
|
1707
1672
|
if (salvato !== void 0) {
|
|
1673
|
+
if (salvato.versione !== VERSIONE_STATO) throw new Error("The saved room format is unsupported. Create a new room.");
|
|
1708
1674
|
if (modalitaLocale2(manifest, salvato.mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE2), { code: "mode_local" });
|
|
1709
1675
|
nucleo.dati = salvato;
|
|
1710
|
-
nucleo.tickRateSincronizzato = salvato.tickRate;
|
|
1711
|
-
let daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0 || salvato.origin === void 0;
|
|
1712
|
-
salvato.origin ??= "player";
|
|
1713
|
-
if (salvato.origin === "matchmaking" && salvato.status === "lobby") {
|
|
1714
|
-
salvato.status = "waiting";
|
|
1715
|
-
daAggiornare = true;
|
|
1716
|
-
}
|
|
1717
|
-
salvato.daily ??= nucleo.contestoGiornaliero();
|
|
1718
|
-
salvato.ultimoInputAt ??= adattatore.ora();
|
|
1719
|
-
salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
|
|
1720
1676
|
nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
|
|
1721
1677
|
await nucleo.riconciliaConnessioni();
|
|
1722
1678
|
if (salvato.origin === "matchmaking") nucleo.rivalutaAvvio();
|
|
1723
|
-
if (
|
|
1679
|
+
if (salvato.status === "playing" && nucleo.tickRate > 0) nucleo.inviaSnapshotTutti();
|
|
1724
1680
|
}
|
|
1725
1681
|
await nucleo.aggiornaProgrammazione();
|
|
1726
1682
|
return nucleo;
|
|
@@ -1745,14 +1701,13 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1745
1701
|
if (modalitaLocale2(this.manifest, mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE2), { code: "mode_local" });
|
|
1746
1702
|
const ora = this.adattatore.ora();
|
|
1747
1703
|
this.dati = {
|
|
1748
|
-
versione:
|
|
1704
|
+
versione: VERSIONE_STATO,
|
|
1749
1705
|
origin,
|
|
1750
1706
|
daily: this.contestoGiornaliero(ora),
|
|
1751
1707
|
id,
|
|
1752
1708
|
mode,
|
|
1753
1709
|
status: origin === "matchmaking" ? "waiting" : "lobby",
|
|
1754
1710
|
tick: 0,
|
|
1755
|
-
tickRate: this.definizione.tickRate,
|
|
1756
1711
|
ultimoInputAt: ora,
|
|
1757
1712
|
ultimoCambioStatoAt: ora,
|
|
1758
1713
|
state: {},
|
|
@@ -1767,8 +1722,6 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1767
1722
|
cancellaDopoFlush: false,
|
|
1768
1723
|
tickSincronizzato: 0,
|
|
1769
1724
|
statoSincronizzato: {},
|
|
1770
|
-
durateCpu: [],
|
|
1771
|
-
cpuOltreCento: 0,
|
|
1772
1725
|
voceGuadagni: {}
|
|
1773
1726
|
};
|
|
1774
1727
|
await this.chiama(this.definizione.onCreate, this.room);
|
|
@@ -1909,7 +1862,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1909
1862
|
this.inviaGiocatori();
|
|
1910
1863
|
this.rivalutaAvvio();
|
|
1911
1864
|
}
|
|
1912
|
-
await this.persistiEProgramma();
|
|
1865
|
+
await this.persistiEProgramma(true);
|
|
1913
1866
|
return { ok: true };
|
|
1914
1867
|
}
|
|
1915
1868
|
async disconnetti(connessione) {
|
|
@@ -1927,7 +1880,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
1927
1880
|
await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
|
|
1928
1881
|
await this.concludiEvento();
|
|
1929
1882
|
this.inviaGiocatori();
|
|
1930
|
-
await this.persistiEProgramma();
|
|
1883
|
+
await this.persistiEProgramma(true);
|
|
1931
1884
|
}
|
|
1932
1885
|
async ricevi(connessione, frame, limiteVerificato = false) {
|
|
1933
1886
|
if (this.dati === null || this.dati.status === "ended") return;
|
|
@@ -2065,7 +2018,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2065
2018
|
await this.messaggioErrato(player);
|
|
2066
2019
|
}
|
|
2067
2020
|
async eseguiTick() {
|
|
2068
|
-
if (this.dati === null || this.dati.status !== "playing" || this.
|
|
2021
|
+
if (this.dati === null || this.dati.status !== "playing" || this.tickRate === 0) return;
|
|
2069
2022
|
if (await this.terminaSeInattiva()) return;
|
|
2070
2023
|
if (!this.serveTick()) {
|
|
2071
2024
|
await this.persistiEProgramma();
|
|
@@ -2073,14 +2026,11 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2073
2026
|
}
|
|
2074
2027
|
const dati = this.dati;
|
|
2075
2028
|
dati.tick++;
|
|
2076
|
-
const inizio = this.adattatore.misuraCpu();
|
|
2077
2029
|
await this.chiama(
|
|
2078
2030
|
this.definizione.onTick,
|
|
2079
2031
|
this.room,
|
|
2080
|
-
1 /
|
|
2032
|
+
1 / this.tickRate
|
|
2081
2033
|
);
|
|
2082
|
-
const durata = Math.max(0, this.adattatore.misuraCpu() - inizio);
|
|
2083
|
-
this.registraCpu(durata);
|
|
2084
2034
|
await this.applicaAzioni();
|
|
2085
2035
|
if (dati.status === "ended") return;
|
|
2086
2036
|
this.inviaGuadagniCambiati();
|
|
@@ -2088,13 +2038,14 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2088
2038
|
if (stato === null || this.stanzaTerminata()) return;
|
|
2089
2039
|
dati.state = stato.valore;
|
|
2090
2040
|
this.inviaDiff();
|
|
2091
|
-
|
|
2092
|
-
await this.aggiornaProgrammazione();
|
|
2041
|
+
await this.persistiEProgramma();
|
|
2093
2042
|
}
|
|
2094
2043
|
async sveglia() {
|
|
2095
2044
|
if (this.dati === null || this.dati.status === "ended") return;
|
|
2045
|
+
if (await this.terminaSeVuota()) return;
|
|
2096
2046
|
if (await this.terminaSeInattiva()) return;
|
|
2097
2047
|
const ora = this.adattatore.ora();
|
|
2048
|
+
const statoPrima = this.dati.status;
|
|
2098
2049
|
const scaduti = this.dati.giocatori.filter(
|
|
2099
2050
|
(player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
|
|
2100
2051
|
);
|
|
@@ -2128,13 +2079,10 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2128
2079
|
}
|
|
2129
2080
|
}
|
|
2130
2081
|
await this.concludiEvento();
|
|
2131
|
-
|
|
2132
|
-
this.dati.cancellaDopoFlush = true;
|
|
2133
|
-
await this.terminaInterna(null);
|
|
2134
|
-
}
|
|
2082
|
+
await this.terminaSeVuota();
|
|
2135
2083
|
if (scaduti.length > 0) this.inviaGiocatori();
|
|
2136
2084
|
await this.concludiEvento();
|
|
2137
|
-
await this.persistiEProgramma();
|
|
2085
|
+
await this.persistiEProgramma(scaduti.length > 0 || this.dati.status !== statoPrima);
|
|
2138
2086
|
}
|
|
2139
2087
|
async preparaFlush() {
|
|
2140
2088
|
const dati = this.richiediDati();
|
|
@@ -2194,7 +2142,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2194
2142
|
}
|
|
2195
2143
|
await this.concludiEvento();
|
|
2196
2144
|
this.inviaGiocatori();
|
|
2197
|
-
await this.persistiEProgramma();
|
|
2145
|
+
await this.persistiEProgramma(true);
|
|
2198
2146
|
}
|
|
2199
2147
|
}
|
|
2200
2148
|
ruoloAutomatico() {
|
|
@@ -2249,6 +2197,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2249
2197
|
if (player.team === null) player.team = this.squadraAutomatica();
|
|
2250
2198
|
if (this.richiediDati().status === "lobby") player.ready = false;
|
|
2251
2199
|
if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
|
|
2200
|
+
this.salvataggioImmediato = true;
|
|
2252
2201
|
this.rivediVoce();
|
|
2253
2202
|
}
|
|
2254
2203
|
this.inviaGiocatori();
|
|
@@ -2262,7 +2211,10 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2262
2211
|
const squadraPrecedente = player.team;
|
|
2263
2212
|
player.team = team;
|
|
2264
2213
|
if (this.richiediDati().status === "lobby") player.ready = false;
|
|
2265
|
-
if (player.team !== squadraPrecedente)
|
|
2214
|
+
if (player.team !== squadraPrecedente) {
|
|
2215
|
+
this.salvataggioImmediato = true;
|
|
2216
|
+
this.rivediVoce();
|
|
2217
|
+
}
|
|
2266
2218
|
this.inviaGiocatori();
|
|
2267
2219
|
this.rivalutaAvvio();
|
|
2268
2220
|
return null;
|
|
@@ -2384,6 +2336,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2384
2336
|
const indice = dati.giocatori.findIndex((item) => item.id === player.id);
|
|
2385
2337
|
if (indice < 0) return;
|
|
2386
2338
|
dati.giocatori.splice(indice, 1);
|
|
2339
|
+
this.salvataggioImmediato = true;
|
|
2387
2340
|
if (player.connessione !== null) this.frequenza.delete(player.connessione);
|
|
2388
2341
|
this.rivediVoce();
|
|
2389
2342
|
this.pulisciGuadagni(player.id);
|
|
@@ -2535,15 +2488,13 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2535
2488
|
rematch: this.rivincitaProtocollo(),
|
|
2536
2489
|
mode: dati.mode,
|
|
2537
2490
|
tick: dati.tick,
|
|
2538
|
-
tickRate:
|
|
2491
|
+
tickRate: this.tickRate,
|
|
2539
2492
|
serverTime: this.adattatore.ora(),
|
|
2540
2493
|
countdownAt: dati.countdownAt,
|
|
2541
2494
|
configuration: {
|
|
2542
2495
|
players: { ...this.configurazione.players },
|
|
2543
2496
|
persistent: this.manifest.persistent === true,
|
|
2544
|
-
requestRole: this.definizione.onRoleRequest !== void 0
|
|
2545
|
-
// Campo tenuto per i giochi pubblicati prima della 0.23, che lo leggono per disegnare la sala d'attesa.
|
|
2546
|
-
lobby: dati.origin === "player"
|
|
2497
|
+
requestRole: this.definizione.onRoleRequest !== void 0
|
|
2547
2498
|
}
|
|
2548
2499
|
};
|
|
2549
2500
|
}
|
|
@@ -2564,12 +2515,11 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2564
2515
|
inviaDiff() {
|
|
2565
2516
|
const dati = this.richiediDati();
|
|
2566
2517
|
const patch = creaDiff(dati.statoSincronizzato, dati.state);
|
|
2567
|
-
if (patch.length === 0
|
|
2568
|
-
this.tickRateSincronizzato = dati.tickRate;
|
|
2518
|
+
if (patch.length === 0) return;
|
|
2569
2519
|
this.broadcast({
|
|
2570
2520
|
t: "state",
|
|
2571
2521
|
tick: dati.tick,
|
|
2572
|
-
tickRate:
|
|
2522
|
+
tickRate: this.tickRate,
|
|
2573
2523
|
base: dati.tickSincronizzato,
|
|
2574
2524
|
serverTime: this.adattatore.ora(),
|
|
2575
2525
|
patch
|
|
@@ -2584,10 +2534,9 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2584
2534
|
dati.state = stato.valore;
|
|
2585
2535
|
dati.statoSincronizzato = copiaJson(stato.valore);
|
|
2586
2536
|
dati.tickSincronizzato = dati.tick;
|
|
2587
|
-
this.tickRateSincronizzato = dati.tickRate;
|
|
2588
2537
|
this.broadcast({
|
|
2589
2538
|
t: "snapshot",
|
|
2590
|
-
tickRate:
|
|
2539
|
+
tickRate: this.tickRate,
|
|
2591
2540
|
tick: dati.tick,
|
|
2592
2541
|
serverTime: this.adattatore.ora(),
|
|
2593
2542
|
state: stato.valore
|
|
@@ -2635,7 +2584,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2635
2584
|
if (stato === null || this.stanzaTerminata()) return;
|
|
2636
2585
|
const precedente = JSON.stringify(this.dati.statoSincronizzato);
|
|
2637
2586
|
this.dati.state = stato.valore;
|
|
2638
|
-
if ((this.
|
|
2587
|
+
if ((this.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
|
|
2639
2588
|
this.dati.tick++;
|
|
2640
2589
|
this.inviaDiff();
|
|
2641
2590
|
}
|
|
@@ -2672,7 +2621,7 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2672
2621
|
const precedente = dati.voceGuadagni[playerId]?.[altroId] ?? 1;
|
|
2673
2622
|
if (precedente === valore) return;
|
|
2674
2623
|
if (precedente > 0 && valore === 0) this.rivediVoce();
|
|
2675
|
-
this.
|
|
2624
|
+
this.salvataggioImmediato = true;
|
|
2676
2625
|
if (valore === 1) {
|
|
2677
2626
|
const riga = dati.voceGuadagni[playerId];
|
|
2678
2627
|
if (riga !== void 0) {
|
|
@@ -2705,15 +2654,12 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2705
2654
|
pulisciGuadagni(playerId) {
|
|
2706
2655
|
const guadagni = this.richiediDati().voceGuadagni;
|
|
2707
2656
|
if (guadagni === void 0) return;
|
|
2708
|
-
let cambiato = Object.hasOwn(guadagni, playerId);
|
|
2709
2657
|
delete guadagni[playerId];
|
|
2710
2658
|
this.voceGuadagniCambiati.delete(playerId);
|
|
2711
2659
|
for (const [altroId, riga] of Object.entries(guadagni)) {
|
|
2712
|
-
cambiato = Object.hasOwn(riga, playerId) || cambiato;
|
|
2713
2660
|
delete riga[playerId];
|
|
2714
2661
|
if (Object.keys(riga).length === 0) delete guadagni[altroId];
|
|
2715
2662
|
}
|
|
2716
|
-
if (cambiato) this.voceDaPersistire = true;
|
|
2717
2663
|
}
|
|
2718
2664
|
async terminaPerStato(code) {
|
|
2719
2665
|
const dati = this.richiediDati();
|
|
@@ -2724,7 +2670,8 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2724
2670
|
const dati = this.richiediDati();
|
|
2725
2671
|
if (dati.status === "ended") return;
|
|
2726
2672
|
const giaFinita = dati.status === "finished";
|
|
2727
|
-
if (dati.
|
|
2673
|
+
if (dati.giocatori.length === 0) rematch = false;
|
|
2674
|
+
else if (dati.origin === "matchmaking" && record(result)?.error === void 0) rematch = true;
|
|
2728
2675
|
dati.status = rematch ? "finished" : "ended";
|
|
2729
2676
|
dati.rivincita = rematch ? { keepSetup: typeof rematch === "object" && rematch.keepSetup === true } : null;
|
|
2730
2677
|
dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
|
|
@@ -2767,41 +2714,34 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2767
2714
|
}
|
|
2768
2715
|
await this.persistiEProgramma();
|
|
2769
2716
|
}
|
|
2770
|
-
|
|
2771
|
-
const dati = this.
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
dati
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
dati.durateCpu = [];
|
|
2784
|
-
this.broadcast({
|
|
2785
|
-
t: "error",
|
|
2786
|
-
code: "tick_rate_reduced",
|
|
2787
|
-
message: `Tick rate reduced to ${dati.tickRate} because the game exceeded its CPU budget.`
|
|
2788
|
-
});
|
|
2717
|
+
async persistiEProgramma(immediato = false) {
|
|
2718
|
+
const dati = this.dati;
|
|
2719
|
+
const ora = this.adattatore.ora();
|
|
2720
|
+
const tick = this.serveTick(ora);
|
|
2721
|
+
if (dati !== null && (!tick || immediato || this.salvataggioImmediato || ora >= (dati.prossimoSalvataggioAt ?? 0))) {
|
|
2722
|
+
const scadenzaPrima = dati.prossimoSalvataggioAt;
|
|
2723
|
+
dati.prossimoSalvataggioAt = ora + INTERVALLO_SALVATAGGIO_MS;
|
|
2724
|
+
try {
|
|
2725
|
+
await this.adattatore.storage.put(CHIAVE_NUCLEO, dati);
|
|
2726
|
+
} catch (errore) {
|
|
2727
|
+
dati.prossimoSalvataggioAt = scadenzaPrima;
|
|
2728
|
+
this.salvataggioImmediato = true;
|
|
2729
|
+
throw errore;
|
|
2789
2730
|
}
|
|
2731
|
+
this.salvataggioImmediato = false;
|
|
2790
2732
|
}
|
|
2733
|
+
await this.aggiornaProgrammazione(tick);
|
|
2791
2734
|
}
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
this.voceDaPersistire = false;
|
|
2796
|
-
}
|
|
2797
|
-
}
|
|
2798
|
-
async persistiEProgramma() {
|
|
2799
|
-
await this.persisti();
|
|
2800
|
-
await this.aggiornaProgrammazione();
|
|
2735
|
+
serveTick(ora = this.adattatore.ora()) {
|
|
2736
|
+
const dati = this.dati;
|
|
2737
|
+
return dati !== null && dati.status === "playing" && this.tickRate > 0 && dati.giocatori.some((player) => player.connected) && ora - Math.max(dati.ultimoInputAt, dati.ultimoCambioStatoAt) < RIPOSO_TICK_MS;
|
|
2801
2738
|
}
|
|
2802
|
-
|
|
2739
|
+
async terminaSeVuota() {
|
|
2803
2740
|
const dati = this.dati;
|
|
2804
|
-
|
|
2741
|
+
if (dati === null || dati.status === "ended" || dati.giocatori.length > 0 || dati.vuotaDa === null || dati.vuotaDa + STANZA_VUOTA_MS > this.adattatore.ora()) return false;
|
|
2742
|
+
dati.cancellaDopoFlush = true;
|
|
2743
|
+
await this.terminaInterna(null);
|
|
2744
|
+
return true;
|
|
2805
2745
|
}
|
|
2806
2746
|
async terminaSeInattiva() {
|
|
2807
2747
|
if (this.dati?.status === "finished") {
|
|
@@ -2822,15 +2762,13 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2822
2762
|
await this.terminaInterna({ error: "idle" });
|
|
2823
2763
|
return true;
|
|
2824
2764
|
}
|
|
2825
|
-
async aggiornaProgrammazione() {
|
|
2765
|
+
async aggiornaProgrammazione(tick = this.serveTick()) {
|
|
2826
2766
|
if (this.dati === null || this.dati.status === "ended") {
|
|
2827
2767
|
this.adattatore.programmaTick(null);
|
|
2828
2768
|
await this.adattatore.programmaSveglia(null);
|
|
2829
2769
|
return;
|
|
2830
2770
|
}
|
|
2831
|
-
this.adattatore.programmaTick(
|
|
2832
|
-
this.serveTick() ? 1e3 / this.dati.tickRate : null
|
|
2833
|
-
);
|
|
2771
|
+
this.adattatore.programmaTick(tick ? 1e3 / this.tickRate : null);
|
|
2834
2772
|
const prossime = [];
|
|
2835
2773
|
if (this.dati.status === "finished") prossime.push(this.dati.rivincitaFinoA ?? this.adattatore.ora());
|
|
2836
2774
|
if (this.manifest.persistent === true) {
|
|
@@ -2854,192 +2792,59 @@ var NucleoStanza = class _NucleoStanza {
|
|
|
2854
2792
|
await this.adattatore.programmaSveglia(prossime.length === 0 ? null : Math.min(...prossime));
|
|
2855
2793
|
}
|
|
2856
2794
|
};
|
|
2857
|
-
var GUID_WEBSOCKET = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
2858
|
-
var MASSIMO_MESSAGGIO = 1e6;
|
|
2859
|
-
function contieneToken(value, token) {
|
|
2860
|
-
return value?.split(",").some((parte) => parte.trim().toLowerCase() === token) === true;
|
|
2861
|
-
}
|
|
2862
|
-
function chiaveValida(value) {
|
|
2863
|
-
if (value === void 0 || !/^[A-Za-z0-9+/]{22}==$/.test(value)) return false;
|
|
2864
|
-
return Buffer.from(value, "base64").byteLength === 16;
|
|
2865
|
-
}
|
|
2866
|
-
function creaFrame(opcode, payload) {
|
|
2867
|
-
const primo = Buffer.from([128 | opcode]);
|
|
2868
|
-
if (payload.byteLength < 126) {
|
|
2869
|
-
return Buffer.concat([primo, Buffer.from([payload.byteLength]), payload]);
|
|
2870
|
-
}
|
|
2871
|
-
if (payload.byteLength <= 65535) {
|
|
2872
|
-
const header2 = Buffer.allocUnsafe(3);
|
|
2873
|
-
header2[0] = 126;
|
|
2874
|
-
header2.writeUInt16BE(payload.byteLength, 1);
|
|
2875
|
-
return Buffer.concat([primo, header2, payload]);
|
|
2876
|
-
}
|
|
2877
|
-
const header = Buffer.allocUnsafe(9);
|
|
2878
|
-
header[0] = 127;
|
|
2879
|
-
header.writeBigUInt64BE(BigInt(payload.byteLength), 1);
|
|
2880
|
-
return Buffer.concat([primo, header, payload]);
|
|
2881
|
-
}
|
|
2882
|
-
function testoUtf8(payload) {
|
|
2883
|
-
try {
|
|
2884
|
-
return new TextDecoder("utf-8", { fatal: true }).decode(payload);
|
|
2885
|
-
} catch {
|
|
2886
|
-
return null;
|
|
2887
|
-
}
|
|
2888
|
-
}
|
|
2889
2795
|
var NodeWebSocket = class extends EventEmitter {
|
|
2890
|
-
constructor(socket
|
|
2796
|
+
constructor(socket) {
|
|
2891
2797
|
super();
|
|
2892
2798
|
this.socket = socket;
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
this.frammentando = false;
|
|
2898
|
-
this.chiusuraInviata = false;
|
|
2899
|
-
this.terminato = false;
|
|
2900
|
-
socket.on("data", (chunk) => this.aggiungi(chunk));
|
|
2901
|
-
socket.on("end", () => this.termina());
|
|
2902
|
-
socket.on("close", () => this.termina());
|
|
2903
|
-
socket.on("error", () => this.termina());
|
|
2904
|
-
if (head.byteLength > 0) queueMicrotask(() => this.aggiungi(head));
|
|
2905
|
-
}
|
|
2906
|
-
send(message) {
|
|
2907
|
-
if (this.chiusuraInviata || this.terminato) return;
|
|
2908
|
-
this.socket.write(creaFrame(1, Buffer.from(message, "utf8")));
|
|
2909
|
-
}
|
|
2910
|
-
close(code = 1e3, reason = "") {
|
|
2911
|
-
if (this.chiusuraInviata || this.terminato) return;
|
|
2912
|
-
const motivo = Buffer.from(reason, "utf8");
|
|
2913
|
-
if (motivo.byteLength > 123) throw new RangeError("WebSocket close reasons must be at most 123 bytes.");
|
|
2914
|
-
const payload = Buffer.allocUnsafe(2 + motivo.byteLength);
|
|
2915
|
-
payload.writeUInt16BE(code, 0);
|
|
2916
|
-
motivo.copy(payload, 2);
|
|
2917
|
-
this.chiusuraInviata = true;
|
|
2918
|
-
this.socket.write(creaFrame(8, payload), () => this.socket.end());
|
|
2919
|
-
}
|
|
2920
|
-
termina() {
|
|
2921
|
-
if (this.terminato) return;
|
|
2922
|
-
this.terminato = true;
|
|
2923
|
-
this.emit("close");
|
|
2924
|
-
}
|
|
2925
|
-
erroreProtocollo(code, reason) {
|
|
2926
|
-
this.close(code, reason);
|
|
2927
|
-
}
|
|
2928
|
-
aggiungi(chunk) {
|
|
2929
|
-
if (this.terminato) return;
|
|
2930
|
-
this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
|
|
2931
|
-
this.leggiFrame();
|
|
2932
|
-
}
|
|
2933
|
-
leggiFrame() {
|
|
2934
|
-
while (!this.terminato && this.buffer.byteLength >= 2) {
|
|
2935
|
-
const primo = this.buffer[0] ?? 0;
|
|
2936
|
-
const secondo = this.buffer[1] ?? 0;
|
|
2937
|
-
const fin = (primo & 128) !== 0;
|
|
2938
|
-
const opcode = primo & 15;
|
|
2939
|
-
const controllo = opcode >= 8;
|
|
2940
|
-
if ((primo & 112) !== 0 || ![0, 1, 8, 9, 10].includes(opcode)) {
|
|
2941
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
2942
|
-
return;
|
|
2943
|
-
}
|
|
2944
|
-
if ((secondo & 128) === 0 || controllo && !fin) {
|
|
2945
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
2799
|
+
socket.on("message", (data, binary) => {
|
|
2800
|
+
if (socket.readyState !== WebSocket.OPEN) return;
|
|
2801
|
+
if (binary) {
|
|
2802
|
+
socket.close(1003, "text_only");
|
|
2946
2803
|
return;
|
|
2947
2804
|
}
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
lunghezza = this.buffer.readUInt16BE(2);
|
|
2953
|
-
offset = 4;
|
|
2954
|
-
} else if (lunghezza === 127) {
|
|
2955
|
-
if (this.buffer.byteLength < 10) return;
|
|
2956
|
-
const grande = this.buffer.readBigUInt64BE(2);
|
|
2957
|
-
if (grande > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
2958
|
-
this.erroreProtocollo(1009, "message_too_large");
|
|
2959
|
-
return;
|
|
2960
|
-
}
|
|
2961
|
-
lunghezza = Number(grande);
|
|
2962
|
-
offset = 10;
|
|
2963
|
-
}
|
|
2964
|
-
if (controllo && lunghezza > 125) {
|
|
2965
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
2966
|
-
return;
|
|
2967
|
-
}
|
|
2968
|
-
if (this.buffer.byteLength < offset + 4 + lunghezza) return;
|
|
2969
|
-
const maschera = this.buffer.subarray(offset, offset + 4);
|
|
2970
|
-
const payload = Buffer.from(this.buffer.subarray(offset + 4, offset + 4 + lunghezza));
|
|
2971
|
-
this.buffer = this.buffer.subarray(offset + 4 + lunghezza);
|
|
2972
|
-
for (let indice = 0; indice < payload.byteLength; indice += 1) {
|
|
2973
|
-
payload[indice] = (payload[indice] ?? 0) ^ (maschera[indice % 4] ?? 0);
|
|
2974
|
-
}
|
|
2975
|
-
if (controllo) {
|
|
2976
|
-
this.gestisciControllo(opcode, payload);
|
|
2977
|
-
continue;
|
|
2978
|
-
}
|
|
2979
|
-
this.gestisciDati(opcode, fin, payload);
|
|
2980
|
-
}
|
|
2805
|
+
this.emit("message", data.toString());
|
|
2806
|
+
});
|
|
2807
|
+
socket.on("close", () => this.emit("close"));
|
|
2808
|
+
socket.on("error", () => void 0);
|
|
2981
2809
|
}
|
|
2982
|
-
|
|
2983
|
-
if (
|
|
2984
|
-
if (!this.chiusuraInviata) this.socket.write(creaFrame(10, payload));
|
|
2985
|
-
return;
|
|
2986
|
-
}
|
|
2987
|
-
if (opcode === 10) return;
|
|
2988
|
-
if (payload.byteLength === 1) {
|
|
2989
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
2990
|
-
return;
|
|
2991
|
-
}
|
|
2992
|
-
if (!this.chiusuraInviata) {
|
|
2993
|
-
this.chiusuraInviata = true;
|
|
2994
|
-
this.socket.write(creaFrame(8, payload), () => this.socket.end());
|
|
2995
|
-
} else {
|
|
2996
|
-
this.socket.end();
|
|
2997
|
-
}
|
|
2810
|
+
send(message) {
|
|
2811
|
+
if (this.socket.readyState === WebSocket.OPEN) this.socket.send(message);
|
|
2998
2812
|
}
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
3002
|
-
return;
|
|
3003
|
-
}
|
|
3004
|
-
if (opcode === 0 && !this.frammentando) {
|
|
3005
|
-
this.erroreProtocollo(1002, "protocol_error");
|
|
3006
|
-
return;
|
|
3007
|
-
}
|
|
3008
|
-
if (opcode === 1 && !fin) this.frammentando = true;
|
|
3009
|
-
this.frammenti.push(payload);
|
|
3010
|
-
this.byteFrammenti += payload.byteLength;
|
|
3011
|
-
if (this.byteFrammenti > this.massimoMessaggio) {
|
|
3012
|
-
this.erroreProtocollo(1009, "message_too_large");
|
|
3013
|
-
return;
|
|
3014
|
-
}
|
|
3015
|
-
if (!fin) return;
|
|
3016
|
-
const completo = this.frammenti.length === 1 ? this.frammenti[0] ?? Buffer.alloc(0) : Buffer.concat(this.frammenti, this.byteFrammenti);
|
|
3017
|
-
this.frammenti = [];
|
|
3018
|
-
this.byteFrammenti = 0;
|
|
3019
|
-
this.frammentando = false;
|
|
3020
|
-
const testo = testoUtf8(completo);
|
|
3021
|
-
if (testo === null) {
|
|
3022
|
-
this.erroreProtocollo(1007, "invalid_utf8");
|
|
3023
|
-
return;
|
|
3024
|
-
}
|
|
3025
|
-
this.emit("message", testo);
|
|
2813
|
+
close(code = 1e3, reason = "") {
|
|
2814
|
+
this.socket.close(code, reason);
|
|
3026
2815
|
}
|
|
3027
2816
|
};
|
|
3028
2817
|
function acceptNodeWebSocket(request, socket, head = Buffer.alloc(0)) {
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
2818
|
+
return new Promise((resolve4, reject) => {
|
|
2819
|
+
const server = new WebSocketServer({
|
|
2820
|
+
noServer: true,
|
|
2821
|
+
clientTracking: false,
|
|
2822
|
+
maxPayload: 1e6,
|
|
2823
|
+
perMessageDeflate: false,
|
|
2824
|
+
skipUTF8Validation: false
|
|
2825
|
+
});
|
|
2826
|
+
const aborted = () => reject(new Error("The WebSocket upgrade was interrupted."));
|
|
2827
|
+
socket.once("error", aborted);
|
|
2828
|
+
socket.once("close", aborted);
|
|
2829
|
+
const cleanup = () => {
|
|
2830
|
+
socket.off("error", aborted);
|
|
2831
|
+
socket.off("close", aborted);
|
|
2832
|
+
};
|
|
2833
|
+
server.once("wsClientError", (error) => {
|
|
2834
|
+
cleanup();
|
|
2835
|
+
socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
|
|
2836
|
+
reject(error);
|
|
2837
|
+
});
|
|
2838
|
+
try {
|
|
2839
|
+
server.handleUpgrade(request, socket, head, (websocket) => {
|
|
2840
|
+
cleanup();
|
|
2841
|
+
resolve4(new NodeWebSocket(websocket));
|
|
2842
|
+
});
|
|
2843
|
+
} catch (error) {
|
|
2844
|
+
cleanup();
|
|
2845
|
+
reject(error);
|
|
2846
|
+
}
|
|
2847
|
+
});
|
|
3043
2848
|
}
|
|
3044
2849
|
function acceptNodeWebSocket2(request, socket, head = Buffer.alloc(0)) {
|
|
3045
2850
|
return acceptNodeWebSocket(request, socket, head);
|
|
@@ -3170,9 +2975,6 @@ var AdattatoreNode = class {
|
|
|
3170
2975
|
giorno(ora) {
|
|
3171
2976
|
return this.dailyDay ?? giornoUtc(ora);
|
|
3172
2977
|
}
|
|
3173
|
-
misuraCpu() {
|
|
3174
|
-
return performance.now();
|
|
3175
|
-
}
|
|
3176
2978
|
rivediVoce() {
|
|
3177
2979
|
}
|
|
3178
2980
|
programmaTick(intervalloMs) {
|
|
@@ -3542,11 +3344,31 @@ var StanzaNode = class {
|
|
|
3542
3344
|
this.adattatore.invia(connessione, { t: "voice", op, r, error: { code, message } });
|
|
3543
3345
|
}
|
|
3544
3346
|
};
|
|
3347
|
+
function conAvvisoTick(definizione, manifest) {
|
|
3348
|
+
const onTick = definizione?.onTick;
|
|
3349
|
+
if (onTick === void 0 || definizione.tickRate === 0) return definizione;
|
|
3350
|
+
const intervallo = 1e3 / definizione.tickRate;
|
|
3351
|
+
let oltre = false;
|
|
3352
|
+
const tickMisurato = async (room, deltaSeconds) => {
|
|
3353
|
+
const inizio = performance.now();
|
|
3354
|
+
try {
|
|
3355
|
+
await onTick(room, deltaSeconds);
|
|
3356
|
+
} finally {
|
|
3357
|
+
const durata = performance.now() - inizio;
|
|
3358
|
+
const sfora = durata > intervallo;
|
|
3359
|
+
if (sfora && !oltre) {
|
|
3360
|
+
console.warn(`Il tick di ${manifest.id} ha richiesto ${durata.toFixed(1)} ms (intervallo ${intervallo.toFixed(1)} ms).`);
|
|
3361
|
+
}
|
|
3362
|
+
oltre = sfora;
|
|
3363
|
+
}
|
|
3364
|
+
};
|
|
3365
|
+
return Object.create(definizione, { onTick: { value: tickMisurato } });
|
|
3366
|
+
}
|
|
3545
3367
|
async function createNodeRoom(definition, manifest, options = {}) {
|
|
3546
3368
|
if (options.dailyDay !== void 0 && !validDay2(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
|
|
3547
3369
|
const storage = await ArchivioNode.apri(options.storageFile ?? null);
|
|
3548
3370
|
const adattatore = new AdattatoreNode(storage, options.dailyDay);
|
|
3549
|
-
const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
|
|
3371
|
+
const nucleo = await NucleoStanza.apri(conAvvisoTick(definition, manifest), manifest, adattatore);
|
|
3550
3372
|
return new StanzaNode(nucleo, adattatore, manifest);
|
|
3551
3373
|
}
|
|
3552
3374
|
|
|
@@ -3625,7 +3447,7 @@ function add() {
|
|
|
3625
3447
|
section.dataset.player = String(slot); title.textContent = 'Player ' + slot;
|
|
3626
3448
|
const drop = document.createElement('button');
|
|
3627
3449
|
drop.textContent = 'Drop';
|
|
3628
|
-
frame.title = title.textContent; frame.allow = 'autoplay; fullscreen; microphone; gamepad; pointer-lock';
|
|
3450
|
+
frame.title = title.textContent; frame.allow = 'autoplay; fullscreen; microphone; gamepad; pointer-lock; clipboard-write; web-share';
|
|
3629
3451
|
const query = new URLSearchParams({ devPlayer: id, lang: params.get('lang') || 'en' });
|
|
3630
3452
|
frame.src = '/?' + query;
|
|
3631
3453
|
drop.onclick = async () => {
|
|
@@ -3801,7 +3623,7 @@ function utcDay(now = Date.now()) {
|
|
|
3801
3623
|
return new Date(now).toISOString().slice(0, 10);
|
|
3802
3624
|
}
|
|
3803
3625
|
function dailySeed(game, day) {
|
|
3804
|
-
return
|
|
3626
|
+
return createHash2("sha256").update(`caisual:${game}:${day}`).digest().readUInt32BE(0);
|
|
3805
3627
|
}
|
|
3806
3628
|
function randomUniform(alphabet, length) {
|
|
3807
3629
|
const limit = Math.floor(256 / alphabet.length) * alphabet.length;
|
|
@@ -3979,13 +3801,11 @@ async function readGame(root) {
|
|
|
3979
3801
|
} catch {
|
|
3980
3802
|
throw new Error("caisual.json: file not found, unreadable, or invalid JSON.");
|
|
3981
3803
|
}
|
|
3982
|
-
const result =
|
|
3804
|
+
const result = validaManifest(parsed);
|
|
3983
3805
|
if (!result.ok) {
|
|
3984
3806
|
throw new Error(`caisual.json is not valid:
|
|
3985
3807
|
${result.errori.map((error) => `- ${error}`).join("\n")}`);
|
|
3986
3808
|
}
|
|
3987
|
-
for (const warning of avvisiManifest(parsed)) process.stderr.write(`Warning: ${warning}
|
|
3988
|
-
`);
|
|
3989
3809
|
const clientRoot = await fs3.realpath(join3(root, "client")).catch(() => null);
|
|
3990
3810
|
if (clientRoot === null) throw new Error("client/: folder not found.");
|
|
3991
3811
|
const stat = await fs3.stat(clientRoot);
|
|
@@ -4088,7 +3908,7 @@ var DevService = class {
|
|
|
4088
3908
|
this.secret = secret;
|
|
4089
3909
|
}
|
|
4090
3910
|
async loadRoomIndex() {
|
|
4091
|
-
const value = await leggiJsonFacoltativo(this.statePath("rooms.json"));
|
|
3911
|
+
const value = await leggiJsonFacoltativo(this.statePath("rooms-v2.json"));
|
|
4092
3912
|
if (value === null) return;
|
|
4093
3913
|
const file = object(value);
|
|
4094
3914
|
if (file?.version !== VERSIONE_STATO_DEV || !Array.isArray(file.rooms)) {
|
|
@@ -4146,7 +3966,7 @@ var DevService = class {
|
|
|
4146
3966
|
persistRoomIndex() {
|
|
4147
3967
|
return this.serializePersistence(async () => {
|
|
4148
3968
|
const rooms = [...this.roomIndex.values()].sort((left, right) => left.roomId.localeCompare(right.roomId));
|
|
4149
|
-
await scriviJsonAtomico(this.statePath("rooms.json"), {
|
|
3969
|
+
await scriviJsonAtomico(this.statePath("rooms-v2.json"), {
|
|
4150
3970
|
version: VERSIONE_STATO_DEV,
|
|
4151
3971
|
rooms
|
|
4152
3972
|
});
|
|
@@ -4222,7 +4042,7 @@ var DevService = class {
|
|
|
4222
4042
|
return;
|
|
4223
4043
|
}
|
|
4224
4044
|
if ((this.droppedUntil.get(identity.id) ?? 0) > Date.now()) {
|
|
4225
|
-
const websocket = acceptNodeWebSocket2(request, socket, head);
|
|
4045
|
+
const websocket = await acceptNodeWebSocket2(request, socket, head);
|
|
4226
4046
|
websocket.close(1012, "dev_drop");
|
|
4227
4047
|
return;
|
|
4228
4048
|
}
|
|
@@ -4234,15 +4054,15 @@ var DevService = class {
|
|
|
4234
4054
|
return;
|
|
4235
4055
|
}
|
|
4236
4056
|
try {
|
|
4237
|
-
const websocket = this.roomSocket(request, socket, head, identity.id);
|
|
4057
|
+
const websocket = await this.roomSocket(request, socket, head, identity.id);
|
|
4238
4058
|
const result = await localRoom.room.connect(websocket, identity);
|
|
4239
4059
|
if (result.ok) localRoom.pendingMatch.delete(identity.id);
|
|
4240
4060
|
} catch {
|
|
4241
4061
|
if (!socket.destroyed) this.rejectUpgrade(socket, 400, "invalid_request", "The WebSocket request is invalid.");
|
|
4242
4062
|
}
|
|
4243
4063
|
}
|
|
4244
|
-
roomSocket(request, socket, head, playerId) {
|
|
4245
|
-
const websocket = simulateNetwork(acceptNodeWebSocket2(request, socket, head), this.network);
|
|
4064
|
+
async roomSocket(request, socket, head, playerId) {
|
|
4065
|
+
const websocket = simulateNetwork(await acceptNodeWebSocket2(request, socket, head), this.network);
|
|
4246
4066
|
const sockets = this.playerSockets.get(playerId) ?? /* @__PURE__ */ new Set();
|
|
4247
4067
|
sockets.add(websocket);
|
|
4248
4068
|
this.playerSockets.set(playerId, sockets);
|
|
@@ -4270,7 +4090,7 @@ var DevService = class {
|
|
|
4270
4090
|
}
|
|
4271
4091
|
let websocket;
|
|
4272
4092
|
try {
|
|
4273
|
-
websocket = acceptNodeWebSocket2(request, socket, head);
|
|
4093
|
+
websocket = await acceptNodeWebSocket2(request, socket, head);
|
|
4274
4094
|
} catch {
|
|
4275
4095
|
if (!socket.destroyed) {
|
|
4276
4096
|
this.rejectUpgrade(socket, 400, "invalid_request", "The WebSocket request is invalid.");
|
|
@@ -4389,7 +4209,7 @@ var DevService = class {
|
|
|
4389
4209
|
response.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
4390
4210
|
response.setHeader("Cache-Control", "no-store");
|
|
4391
4211
|
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
4392
|
-
response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.24.0\nvar xe=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],nt=new Set(xe);function y(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function Re(n,e="en"){let t=[],i=y(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(y(e)??e),[...new Set(t)]}function Q(n,e=[]){let t=e.map(y).filter(r=>r!==null),i=n.map(y).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let o of Re(r,r))if(t.includes(o))return o;return t.includes("en")?"en":t[0]}function ee(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function ke(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function te(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Pe(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let a=e?.deviceMemory,s=typeof a=="number"?a*1024:NaN;Number.isFinite(s)&&(t=s)}catch{t=null}let i=null;try{let a=e?.hardwareConcurrency;typeof a=="number"&&Number.isFinite(a)&&(i=a)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let o=!1;try{o=n.crossOriginIsolated===!0}catch{o=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:o,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function ie(n,e=1500){let t=n??globalThis,i=Pe(t),r=Promise.resolve().then(()=>{try{let c=t.document?.createElement("canvas");if(c===void 0)return;let l=c.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(l!==null){i.webgl2=!0,i.gpu="hardware",te(l);return}let m=c.getContext("webgl2");m!==null&&(i.webgl2=!0,i.gpu="software",te(m))}catch{i.webgl2=!1,i.gpu="none"}}),o=Promise.resolve().then(async()=>{let c;try{let l=t.navigator?.gpu;if(l===void 0)return;let m=await l.requestAdapter();if(m===null)return;c=await m.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{c?.destroy?.()}catch{}}}),a=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),s=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),u;return await Promise.race([Promise.all([r,o,a,s]),new Promise(c=>{u=setTimeout(c,Math.max(0,e))})]),u!==void 0&&clearTimeout(u),{...i,tier:ke(i)}}function G(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var N=Object.freeze({recipientBytesPerSecond:1e5,roomBytesPerSecond:2e6,warningRatio:.8,windowMs:5e3,blockingWindows:3}),It=`Multiplayer budget: ${N.recipientBytesPerSecond/1e3} kB/s per recipient, ${N.roomBytesPerSecond/1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${N.recipientBytesPerSecond/2e4} kB per update. Keep visual trails and animation on the client. Warnings start at 80%. Publication measures your server automatically; repeated excess in real matches blocks new rooms only. Game input: 30 messages/s per connection.`;function ne(n,e,t="/"){let i,r=t.match(/^\\/rt\\/[^/]+\\/[1-9][0-9]*\\//)?.[0]??"/";return()=>i??(i=(async()=>{let o={};try{let a=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(a.ok){let s=await a.json();ee(s)&&(o=s)}}catch{}return(a,s={})=>Object.hasOwn(o,a)?o[a].replace(/\\{([^{}]+)\\}/g,(c,l)=>Object.hasOwn(s,l)?String(s[l]):c):a})())}function d(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function h(){return d("offline","Caisual services are unavailable.")}function M(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Te(n){let e={};try{e=await n.json()}catch{}return d(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function I(n,e,t,i){async function r(o,a,s,u){let c=new Headers({Authorization:`Bearer ${s}`}),l;if(u!==void 0){c.set("Content-Type","application/json");try{l=JSON.stringify(u)}catch{throw d("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+o,n),{method:a,headers:c,body:l,credentials:"omit"})}catch{throw h()}}return async function(a,s,u,c=!1){let l;try{l=c?await i.rinnova():await i.ottieni()}catch{throw h()}let m=await r(a,s,l,u);if(m.status===401){try{l=await i.rinnova()}catch{throw h()}m=await r(a,s,l,u)}if(!m.ok)throw await Te(m);try{return await m.json()}catch{throw d("internal_error","The service returned an invalid response.")}}}function re(n,e,t){let i=I(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,o)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:o}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(o){if(M(o)==="not_found")return null;throw o}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves}}}function b(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}var z={connected:!1,you:null,friends:[],party:null,invites:[]};function oe(n){let e=b(n);if(!e||typeof e.id!="string"||typeof e.name!="string")return null;let t=b(e.game),i=b(e.room);return{id:e.id,name:e.name,online:e.online===!0,game:t&&typeof t.slug=="string"?{slug:t.slug,name:typeof t.name=="string"?t.name:t.slug,iconUrl:typeof t.iconUrl=="string"?t.iconUrl:""}:null,room:i&&typeof i.code=="string"?{code:i.code}:null}}function Ie(n){let e=b(n);if(!e||typeof e.id!="string"||typeof e.leader!="string")return null;let t=Array.isArray(e.members)?e.members.map(i=>oe(i)).filter(i=>i!==null):[];return{id:e.id,leader:e.leader,members:t}}function ze(n){let e=b(n),t=b(e?.from);return!e||typeof e.party!="string"||!t||typeof t.id!="string"?null:{party:e.party,from:{id:t.id,name:typeof t.name=="string"?t.name:t.id},at:typeof e.at=="number"?e.at:0}}function _e(n){let e=b(n);if(!e)return z;let t=b(e.you);return{connected:e.connected===!0,you:t&&typeof t.id=="string"?{id:t.id,name:typeof t.name=="string"?t.name:""}:null,friends:Array.isArray(e.friends)?e.friends.map(i=>oe(i)).filter(i=>i!==null):[],party:Ie(e.party),invites:Array.isArray(e.invites)?e.invites.map(i=>ze(i)).filter(i=>i!==null):[]}}function se(){return{available:!1,get connected(){return!1},get you(){return null},get friends(){return[]},get party(){return null},get invites(){return[]},onChange(n){return n({...z}),()=>{}},createParty(){},invite(){},accept(){},decline(){},kick(){},leave(){},follow(){},join(){return Promise.reject(d("offline","Friends are unavailable in this copy of the game."))}}}function ae(n,e,t){let i={...z},r=new Set,o=s=>{try{n.postMessage({type:"caisual:crew",...s})}catch{}};n.addEventListener("message",s=>{let u=b(s.data);if(u?.type==="caisual:crew-state"){i=u.state===null?{...z}:_e(u.state);for(let c of r)try{c({...i})}catch{}}}),o({op:"subscribe"});let a=s=>{let u=i.friends.find(c=>c.id===s)??i.party?.members.find(c=>c.id===s);if(!u)throw d("friend_not_found","This player is not in your friends list.");return u};return{available:!0,get connected(){return i.connected},get you(){return i.you===null?null:{...i.you}},get friends(){return i.friends.map(s=>({...s}))},get party(){return i.party===null?null:{...i.party,members:i.party.members.map(s=>({...s}))}},get invites(){return i.invites.map(s=>({...s}))},onChange(s){return r.add(s),s({...i}),()=>{r.delete(s)}},createParty(){o({op:"party",action:"create"})},invite(s){o({op:"party",action:"invite",player:s})},accept(s){o({op:"party",action:"accept",party:s})},decline(s){o({op:"party",action:"decline",party:s})},kick(s){o({op:"party",action:"kick",player:s})},leave(){o({op:"party",action:"leave"})},follow(s){let u=a(s);if(!u.room||!u.game)throw d("no_room","This player is not in a room.");o({op:"follow",slug:u.game.slug,code:u.room.code})},join(s){let u=a(s);return u.room?e!==null&&u.game!==null&&u.game.slug!==e?Promise.reject(d("other_game","This player is playing another game. Use follow instead.")):t.join(u.room.code):Promise.reject(d("no_room","This player is not in a room."))}}}function P(n){return(Math.floor(n/864e5)+1)*864e5}function _(n,e,t){let i=new Set,r={...n},o,a=!1;function s(){!i.size||o!==void 0||a||(o=setTimeout(u,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),o.unref?.())}async function u(){o=void 0,a=!0;try{let c=await t(),l=c.day!==r.day;if(r={...c},l)for(let m of[...i])try{m({...c})}catch{}}catch{}finally{a=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),s()}}return{...n,random:ce(n.seed),rng:()=>ce(n.seed),onChange(c){return i.add(c),s(),()=>{i.delete(c),!i.size&&o!==void 0&&(clearTimeout(o),o=void 0)}}}}function j(n){return new Date(n).toISOString().slice(0,10)}async function B(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function ce(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function E(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function le(n,e){return E(n)?.type===e}function Ee(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function ue(n,e,t=3e3){return new Promise(i=>{let r=!1,o=globalThis.crypto.randomUUID(),a=l=>{r||(r=!0,n.removeEventListener("message",u),n.clearTimeout(c),i(l))},s=()=>{n.parent.postMessage({type:"caisual:ready",instance:o},e)},u=l=>{if(l.origin!==e||l.source!==n.parent)return;if(le(l.data,"caisual:ready?")){s();return}if(!le(l.data,"caisual:hello"))return;let m=E(l.data),f=l.ports[0];if(typeof m?.ticket!="string"||!G(m.n)||f===void 0)return;f.start();let g=v=>Array.isArray(v)?v.map(y).filter(C=>C!==null):void 0;a({...y(m.language)?{language:y(m.language)}:{},languagePreferences:g(m.languagePreferences),gameLanguages:g(m.gameLanguages),ticket:m.ticket,n:m.n,live:Ee(m.live),invite:typeof m.invite=="string"?m.invite:null,porta:f})};n.addEventListener("message",u);let c=n.setTimeout(()=>a(null),t);s()})}function Ve(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=E(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function Oe(n,e,t,i){return new Promise((r,o)=>{let a=!1,s=l=>{a||(a=!0,n.removeEventListener("message",u),e.clearTimeout(c),l===null?o(new Error("Ticket refresh timed out.")):r(l))},u=l=>{let m=E(l.data),f=m?.aud===void 0?"portal":m.aud;m?.type==="caisual:ticket"&&f===i&&typeof m.ticket=="string"&&s(m.ticket)};n.addEventListener("message",u);let c=e.setTimeout(()=>s(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{s(null)}})}function J(n,e,t,i,r=3e3,o="portal"){let a=n,s=null,u=()=>{if(s!==null)return s;let l=Oe(e,t,r,o).then(m=>(a=m,m)).finally(()=>{s===l&&(s=null)});return s=l,l};return{async ottieni(){if(a===null)return u();let c=Ve(a);return c!==null&&c-i()<3e4?u():a},rinnova:u}}var q=.02,de=300,De=200,me=3e3,$e=1e4,Le=[1e3,2e3,4e3];function fe(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Ge(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var V=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Ge(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=e.mic??!0;this.verificaIngresso(),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(d("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw d("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=fe(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(d(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,fe(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(d("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(d("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}verificaIngresso(){if(!this.contesto.connessa())throw d("offline","The room is not connected.");if(this.modeCorrente==="none")throw d("voice_disabled","Voice is disabled for this room.");if(this.dipendenze===null)throw d("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let o;try{o=await t.getUserMedia({audio:!0})}catch(s){throw this.permessoNegato(s)?d("permission_denied","Microphone permission was denied."):d("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(s){for(let u of o.getTracks())u.stop();throw s}let a=o.getAudioTracks()[0];if(a===void 0)throw d("voice_error","The microphone has no audio track.");this.stream=o,this.tracciaMic=a,a.enabled=!this.mutedCorrente,this.preparaAnalizzatore(o)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw d("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw d("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let o of this.gains.keys())this.aggiornaZero(o);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=o=>{let a=o.transceiver.mid,s=a===null?void 0:this.midGiocatori.get(a);s!==void 0&&this.collegaTraccia(s,o.track,o.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let o=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),a=await i.createOffer();await i.setLocalDescription(a),this.controllaGenerazione(t);let s=o.mid,u=i.localDescription?.sdp;if(s===null||u===void 0)throw d("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:u,mid:s})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw d("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw d("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw d("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,o)=>{let a=()=>{e.removeEventListener("connectionstatechange",s),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},s=()=>{t!==this.generazione?(a(),o(d("offline","Voice was stopped."))):e.connectionState==="connected"?(a(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(a(),o(d("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",s),this.cancellaAttesaConnessione=()=>{a(),o(d("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{a(),o(d("voice_error","The voice connection timed out."))},$e)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(c=>[c.id,c])),r=[];for(let[c,l]of this.sfuAttive){let m=i.get(c);m!==void 0&&m.session===l.session&&m.track===l.track||(r.push(l),this.riproduzioni.has(c)||l.receiver?.track.stop(),this.sfuAttive.delete(c),this.midGiocatori.delete(l.mid),this.scollegaTraccia(c))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(c=>c.mid)});let o=[...i.values()].filter(c=>!this.sfuAttive.has(c.id));if(o.length===0)return;let a;try{a=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:o.map(c=>({session:c.session,track:c.track}))})}catch(c){if(M(c)!=="not_allowed")throw c;for(let l of o)this.negati.add(l.id);return}if(a.op!=="subscribe")throw d("voice_error","The voice service returned an invalid response.");for(let c of a.tracks){let l=o.find(m=>m.session===c.session&&m.track===c.track);c.error==="not_allowed"&&l!==void 0&&this.negati.add(l.id),!(c?.mid===null||c?.mid===void 0||c.error!==null||l===void 0)&&(this.midGiocatori.set(c.mid,l.id),this.sfuAttive.set(l.id,{session:l.session,track:l.track,mid:c.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:a.sdp});let s=await t.createAnswer();await t.setLocalDescription(s);let u=t.localDescription?.sdp;if(u===void 0)throw d("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:u}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=o=>{o.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:o.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=o=>{r.receiver=o.receiver,this.collegaTraccia(t,o.track,o.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(a=>a.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let o=t;try{if(o.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(o.candidate);return}if(o.kind!=="offer"&&o.kind!=="answer"||typeof o.sdp!="string")return;let a=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),s=o.kind==="offer"&&!a;if(r.ignoreOffer=!r.polite&&s,r.ignoreOffer)return;if(r.settingRemoteAnswer=o.kind==="answer",await r.pc.setRemoteDescription({type:o.kind,sdp:o.sdp}),r.settingRemoteAnswer=!1,o.kind==="offer"){let u=await r.pc.createAnswer();await r.pc.setLocalDescription(u);let c=r.pc.localDescription?.sdp;c!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:c})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(M(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>!(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic||this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team))}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<me})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),o=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,me-r));this.timerZero.set(e,o)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),o=r.creaMediaStream([t]),a=this.richiediAudioContext().createMediaStreamSource(o),s=this.richiediAudioContext().createGain();a.connect(s),s.connect(this.richiediAudioContext().destination);let u=null;try{u=this.richiediAudioContext().createAnalyser(),u.fftSize=256,a.connect(u)}catch{u=null}let c=r.creaAudioElement();c.srcObject=o,c.muted=!0,c.playsInline=!0,c.play().catch(()=>{}),this.riproduzioni.set(e,{source:a,gain:s,analyser:u,audio:c,track:t,receiver:i});let l=this.sfuAttive.get(e);l!==void 0&&(l.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),De)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>q),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=de;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let o of this.copiaPeers()){let a=this.riproduzioni.get(o.id);this.livelloAnalizzatore(a?.analyser??null)>q?this.ultimoAudio.set(o.id,e.ora()):(a?.analyser===null||a?.analyser===void 0)&&(a?.receiver?.getSynchronizationSources?.()??[]).some(c=>(c.audioLevel??0)>q)&&this.ultimoAudio.set(o.id,e.ora());let s=!o.muted&&e.ora()-(this.ultimoAudio.get(o.id)??0)<=de;(this.speakingPeers.get(o.id)??!1)!==s&&(this.speakingPeers.set(o.id,s),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,o)=>r+o*o,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>r.id===e?[]:this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team?[]:[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}])}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(d("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Le[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(d("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(o){this.richieste.delete(t),r(o)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw d("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw d("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw d("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw d("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="offline"||t==="voice_error"?e:d("voice_error","Voice could not be started.")}return d("voice_error","Voice could not be started.")}};var S=1,he=[1e3,2e3,4e3,8e3],Ne=6e4,je=5e3,Be=2e4,Je=500,qe=2e3,Ue=new Set([4003,4004,4005,4006,4008,4009]);function x(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function pe(n){let e=x(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function Fe(n){let e=x(n);return e!==null&&typeof e.url=="string"}function w(n){return JSON.parse(JSON.stringify(n))}function We(n,e){let t=w(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=w(i.value);continue}let r=t,o=i.path;for(let s=0;s<o.length-1;s++){let u=o[s];if(Array.isArray(r)){if(typeof u!="number"||u>=r.length)return{ok:!1};r=r[u]}else{let c=x(r);if(c===null||typeof u!="string"||!Object.hasOwn(c,u))return{ok:!1};r=c[u]}}let a=o.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof a!="number"||a>=r.length)return{ok:!1};r[a]=w(i.value)}else{let s=x(r);if(s===null||typeof a!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(s,a))return{ok:!1};delete s[a]}else Object.defineProperty(s,a,{configurable:!0,enumerable:!0,value:w(i.value),writable:!0})}}return{ok:!0,state:t}}function He(n){let e=I(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,s,u)=>{try{return await e(o,a,{...x(s),n:n.n},u)}catch(c){if(c instanceof Error&&"code"in c&&["version_outdated","version_mismatch"].includes(String(c.code))){let l=x(s),m=typeof l?.code=="string"?l.code.toUpperCase().replace(/[\\s-]/g,""):void 0,f=typeof l?.roomId=="string"?l.roomId:void 0;n.onVersionError?.(c,c.code==="version_mismatch"?{code:m,roomId:f}:void 0)}throw c}};async function i(o,a,s=!1){let u=await t(o,"POST",a,s);if(!pe(u))throw d("internal_error","The room service returned an invalid response.");return u}async function r(o){let a=await t("/match","POST",{mode:o.mode});if(!Fe(a))throw d("internal_error","The match service returned an invalid response.");return a}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var U=class{constructor(e,t,i,r,o,a){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=o;this.segnalaStanza=a;this.meta={mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.resultCorrente=null;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.origine="player";this.promessaPronta=new Promise((s,u)=>{this.risolviPronta=s,this.rifiutaPronta=u}),this.voice=new V({invia:s=>this.invia(s),connessa:()=>this.socket?.readyState===S&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),this.apri(i)}get origin(){return this.origine}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.origine=e.origin??"player",this.metadataChanged({mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(d("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(d("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(d("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let o=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(d("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:o});try{this.invia({t:"request-role",r:t,role:e})}catch(a){this.dipendenze.clearTimeout(o),this.roleRequests.delete(t),r(a)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(d("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(d("cancelled","The room was disconnected.")))}get role(){return this.giocatoriCorrenti.find(e=>e.id===this.youCorrente)?.role??null}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get code(){return this.codice}get result(){return this.resultCorrente}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-29),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw d("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==S||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(30,this.tickRateCorrente):30);this.inviiGioco=this.inviiGioco.filter(a=>e-a<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,o=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==S||this.terminata||this.lasciata)return;let a=this.dipendenze.ora();if(a<this.ultimoInvioGioco+i||this.inviiGioco.filter(u=>a-u<1e3).length>=30){this.programmaInput();return}let s=this.ultimoInput;try{this.send(JSON.parse(s)),this.inputInviato=s}catch{}},Math.max(0,Math.ceil(Math.max(o,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.origin==="player"&&this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}restart(){if(this.origin!=="matchmaking"){if(this.statusCorrente!=="finished")throw d("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}}leave(){this.lasciata||(this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===S&&this.invia({t:"leave"}),this.termina(1e3))}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==S)throw d("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw d("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==S||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?je:Be;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===S)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=x(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="players")this.riceviGiocatori(t.players);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,w(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(d(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=w(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},qe)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e){this.giocatoriCorrenti=e.map(t=>({...t})),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){this.statusCorrente=e.status,this.resultCorrente=w(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=We(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=w(e),this.statoPubblico=w(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==S)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(Ue.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,he.length-1),t=he[e];if(this.tempoRiconnessione+t>Ne){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let a=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(d(a,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},Je))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function O(n=null){return{invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw h()},async join(){throw h()},async match(){throw h()}}}function ge(n,e){let t,i=new Set,r=He({...n,onVersionError(l,m){t=m;for(let f of i)try{f(l)}catch{}}}),o=!1,a=null,s=l=>{let m=l?.code??null;o&&m===a||(o=!0,a=m,n.segnalaStanza?.(l))},u=async l=>{let m=new U(l.roomId,l.code,l.url,n,r,s);return await m.pronta(),m},c=(l,m)=>new Promise((f,g)=>{let v,C=!1,W=()=>{v.removeEventListener("message",Y),v.removeEventListener("close",Z),v.removeEventListener("error",K),m.signal?.removeEventListener("abort",L)},H=()=>{try{v.close(1e3)}catch{}},R=(T,p)=>{C||(C=!0,W(),p&&H(),g(T))};function L(){R(d("cancelled","The match request was cancelled."),!0)}function Z(){R(h(),!1)}function K(){R(h(),!0)}function Y(T){let p=null;try{p=typeof T.data=="string"?x(JSON.parse(T.data)):null}catch{}if(p===null||typeof p.t!="string"){R(d("internal_error","The match service sent an invalid message."),!0);return}if(p.t==="matched"){if(!pe(p)){R(d("internal_error","The match service sent an invalid message."),!0);return}C=!0,W(),H(),f(p);return}if(p.t==="error"){R(d(typeof p.code=="string"?p.code:"internal_error",typeof p.message=="string"?p.message:"The match service could not complete the request."),!0);return}p.t!=="pong"&&R(d("internal_error","The match service sent an invalid message."),!0)}try{v=n.apriSocket(l)}catch{g(h());return}v.addEventListener("message",Y),v.addEventListener("close",Z),v.addEventListener("error",K),m.signal?.addEventListener("abort",L,{once:!0}),m.signal?.aborted===!0&&L()});return{invited:e,reload(){n.reload?.(t)},onError(l){return i.add(l),()=>{i.delete(l)}},async create(l){return u(await r.create(l.mode))},async join(l){let m=l??e;if(m==null||m.length===0)throw d("invalid_request","A room invitation code is required.");return u(await r.joinCode(m))},async match(l){let m=()=>l.signal?.aborted===!0;if(m())throw d("cancelled","The match request was cancelled.");try{let f=await r.match(l);if(m())throw d("cancelled","The match request was cancelled.");return await u(await c(f.url,l))}catch(f){let g=f instanceof Error&&"code"in f?String(f.code):"";throw["invalid_request","mode_local","no_server","rate_limited","offline","version_outdated","room_full","cancelled"].includes(g)?f:h()}}}}var k="caisual:save:",Ze=/^[a-z0-9][a-z0-9_-]{0,31}$/;function F(n){if(!Ze.test(n))throw d("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function ve(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function ye(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(k)&&e.push(i.slice(k.length))}return e}function Ke(n,e){let t=()=>{if(n===null)throw h();return n};return{async set(i,r){F(i);let o=t(),a=JSON.stringify({value:r}),s=new TextEncoder().encode(a).byteLength;if(s>262144)throw d("payload_too_large","The save is larger than 262144 bytes.");if(o.getItem(k+i)===null&&ye(o).length>=64)throw d("save_limit","A game can store at most 64 save keys.");let u={value:r,bytes:s,updatedAt:e()};return o.setItem(k+i,JSON.stringify(u)),{key:i,bytes:s,updatedAt:u.updatedAt}},async get(i){return F(i),ve(t().getItem(k+i))?.value??null},async remove(i){F(i),t().removeItem(k+i)},async list(){let i=t();return ye(i).flatMap(r=>{let o=ve(i.getItem(k+r));return o===null?[]:[{key:r,bytes:o.bytes,updatedAt:o.updatedAt}]}).sort((r,o)=>r.key.localeCompare(o.key))}}}async function D(n,e=null){let t=n.ora(),i=j(t),r=await B(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:_({day:i,seed:r,expiresAt:P(t)},n.ora,async()=>{let o=n.ora(),a=j(o);return{day:a,seed:await B(n.hostname,a,n.subtle),expiresAt:P(o)}}),time:{now:n.ora},save:Ke(n.archivio,n.ora),room:O(e)}}function Ye(n){let e=n?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function Xe(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Qe(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:Xe(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>ie()}}async function et(n){let e=Ye(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return $(await D(n),void 0,n,null);let i=await ue(n.finestra,e,n.timeoutHandshake);if(i===null)return $(await D(n),void 0,n,null);let r=J(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),o=re(e,n.fetcher,r),a=n.ora(),s;try{s=await o.me()}catch{let f=await D(n,i.invite);return $(f,i,n,null)}let u=n.ora(),c=s.serverTime-(a+u)/2,l=i.live===null?O(i.invite):ge({appOrigin:e,n:i.n,reload:f=>i.porta.postMessage({type:"caisual:reload",target:f}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:J(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(f){if(n.apriSocket!==void 0)return n.apriSocket(f);if(typeof WebSocket>"u")throw h();return new WebSocket(f)},ora:n.ora,setTimeout:(f,g)=>globalThis.setTimeout(f,g),clearTimeout:f=>globalThis.clearTimeout(f),setInterval:(f,g)=>globalThis.setInterval(f,g),clearInterval:f=>globalThis.clearInterval(f),voce:n.voce,segnalaStanza(f){try{i.porta.postMessage({type:"caisual:room",room:f})}catch{}}},i.invite),m={connected:!0,player:s.player,daily:_({day:s.day,seed:s.seed,expiresAt:s.expiresAt??P(s.serverTime)},()=>n.ora()+c,async()=>{let f=await o.me();return{day:f.day,seed:f.seed,expiresAt:f.expiresAt??P(f.serverTime)}}),time:{now:()=>n.ora()+c},save:{set:(f,g)=>o.saveSet(f,g),get:f=>o.saveGet(f),remove:f=>o.saveRemove(f),list:()=>o.saveList()},room:l};return $(m,i,n,s.game.slug)}function $(n,e,t,i){let r=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=Q(r,e?.gameLanguages);return{...n,player:{...n.player,language:o},text:ne(t?.fetcher??globalThis.fetch,o,t?.pathname),crew:e?ae(e.porta,i,n.room):se()}}function be(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function tt(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>be()),new Promise(t=>{e=globalThis.setTimeout(()=>t(be()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function we(n=Qe()){let e=null;return{connect(){return e??(e=Promise.all([et(n),tt(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Se=we();globalThis.caisual=Se;var Li=Se;export{Se as caisual,Li as default};\n');
|
|
4212
|
+
response.end(request.method === "HEAD" ? void 0 : '// Caisual game kit v0.25.1\nvar Me=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],dt=new Set(Me);function b(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function Te(n,e="en"){let t=[],i=b(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(b(e)??e),[...new Set(t)]}function ie(n,e=[]){let t=e.map(b).filter(r=>r!==null),i=n.map(b).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let o of Te(r,r))if(t.includes(o))return o;return t.includes("en")?"en":t[0]}function ne(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function Ie(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function re(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function ze(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let a=e?.deviceMemory,s=typeof a=="number"?a*1024:NaN;Number.isFinite(s)&&(t=s)}catch{t=null}let i=null;try{let a=e?.hardwareConcurrency;typeof a=="number"&&Number.isFinite(a)&&(i=a)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let o=!1;try{o=n.crossOriginIsolated===!0}catch{o=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:o,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function oe(n,e=1500){let t=n??globalThis,i=ze(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let c=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(c!==null){i.webgl2=!0,i.gpu="hardware",re(c);return}let u=m.getContext("webgl2");u!==null&&(i.webgl2=!0,i.gpu="software",re(u))}catch{i.webgl2=!1,i.gpu="none"}}),o=Promise.resolve().then(async()=>{let m;try{let c=t.navigator?.gpu;if(c===void 0)return;let u=await c.requestAdapter();if(u===null)return;m=await u.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),a=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),s=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),l;return await Promise.race([Promise.all([r,o,a,s]),new Promise(m=>{l=setTimeout(m,Math.max(0,e))})]),l!==void 0&&clearTimeout(l),{...i,tier:Ie(i)}}function j(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var B=Object.freeze({recipientBytesPerSecond:1e5,roomBytesPerSecond:2e6,warningRatio:.8,windowMs:5e3,blockingWindows:3}),Gt=`Multiplayer budget: ${B.recipientBytesPerSecond/1e3} kB/s per recipient, ${B.roomBytesPerSecond/1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${B.recipientBytesPerSecond/2e4} kB per update. Keep visual trails and animation on the client. Warnings start at 80%. Publication measures your server automatically; repeated excess in real matches blocks new rooms only. Game input: 30 messages/s per connection.`;function se(n,e,t="/"){let i,r=t.match(/^\\/rt\\/[^/]+\\/[1-9][0-9]*\\//)?.[0]??"/";return()=>i??(i=(async()=>{let o={};try{let a=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(a.ok){let s=await a.json();ne(s)&&(o=s)}}catch{}return(a,s={})=>Object.hasOwn(o,a)?o[a].replace(/\\{([^{}]+)\\}/g,(m,c)=>Object.hasOwn(s,c)?String(s[c]):m):a})())}function d(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function h(){return d("offline","Caisual services are unavailable.")}function T(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Oe(n){let e={};try{e=await n.json()}catch{}return d(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function _(n,e,t,i){async function r(o,a,s,l){let m=new Headers({Authorization:`Bearer ${s}`}),c;if(l!==void 0){m.set("Content-Type","application/json");try{c=JSON.stringify(l)}catch{throw d("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+o,n),{method:a,headers:m,body:c,credentials:"omit"})}catch{throw h()}}return async function(a,s,l,m=!1){let c;try{c=m?await i.rinnova():await i.ottieni()}catch{throw h()}let u=await r(a,s,c,l);if(u.status===401){try{c=await i.rinnova()}catch{throw h()}u=await r(a,s,c,l)}if(!u.ok)throw await Oe(u);try{return await u.json()}catch{throw d("internal_error","The service returned an invalid response.")}}}function ae(n,e,t){let i=_(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,o)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:o}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(o){if(T(o)==="not_found")return null;throw o}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves}}}function w(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}var E={connected:!1,you:null,friends:[],party:null,invites:[]};function ce(n){let e=w(n);if(!e||typeof e.id!="string"||typeof e.name!="string")return null;let t=w(e.game),i=w(e.room);return{id:e.id,name:e.name,online:e.online===!0,game:t&&typeof t.slug=="string"?{slug:t.slug,name:typeof t.name=="string"?t.name:t.slug,iconUrl:typeof t.iconUrl=="string"?t.iconUrl:""}:null,room:i&&typeof i.code=="string"?{code:i.code}:null}}function De(n){let e=w(n);if(!e||typeof e.id!="string"||typeof e.leader!="string")return null;let t=Array.isArray(e.members)?e.members.map(i=>ce(i)).filter(i=>i!==null):[];return{id:e.id,leader:e.leader,members:t}}function $e(n){let e=w(n),t=w(e?.from);return!e||typeof e.party!="string"||!t||typeof t.id!="string"?null:{party:e.party,from:{id:t.id,name:typeof t.name=="string"?t.name:t.id},at:typeof e.at=="number"?e.at:0}}function Ge(n){let e=w(n);if(!e)return E;let t=w(e.you);return{connected:e.connected===!0,you:t&&typeof t.id=="string"?{id:t.id,name:typeof t.name=="string"?t.name:""}:null,friends:Array.isArray(e.friends)?e.friends.map(i=>ce(i)).filter(i=>i!==null):[],party:De(e.party),invites:Array.isArray(e.invites)?e.invites.map(i=>$e(i)).filter(i=>i!==null):[]}}function le(){return{available:!1,get connected(){return!1},get you(){return null},get friends(){return[]},get party(){return null},get invites(){return[]},onChange(n){return n({...E}),()=>{}},createParty(){},invite(){},accept(){},decline(){},kick(){},leave(){},follow(){},join(){return Promise.reject(d("offline","Friends are unavailable in this copy of the game."))}}}function ue(n,e,t){let i={...E},r=new Set,o=s=>{try{n.postMessage({type:"caisual:crew",...s})}catch{}};n.addEventListener("message",s=>{let l=w(s.data);if(l?.type==="caisual:crew-state"){i=l.state===null?{...E}:Ge(l.state);for(let m of r)try{m({...i})}catch{}}}),o({op:"subscribe"});let a=s=>{let l=i.friends.find(m=>m.id===s)??i.party?.members.find(m=>m.id===s);if(!l)throw d("friend_not_found","This player is not in your friends list.");return l};return{available:!0,get connected(){return i.connected},get you(){return i.you===null?null:{...i.you}},get friends(){return i.friends.map(s=>({...s}))},get party(){return i.party===null?null:{...i.party,members:i.party.members.map(s=>({...s}))}},get invites(){return i.invites.map(s=>({...s}))},onChange(s){return r.add(s),s({...i}),()=>{r.delete(s)}},createParty(){o({op:"party",action:"create"})},invite(s){o({op:"party",action:"invite",player:s})},accept(s){o({op:"party",action:"accept",party:s})},decline(s){o({op:"party",action:"decline",party:s})},kick(s){o({op:"party",action:"kick",player:s})},leave(){o({op:"party",action:"leave"})},follow(s){let l=a(s);if(!l.room||!l.game)throw d("no_room","This player is not in a room.");o({op:"follow",slug:l.game.slug,code:l.room.code})},join(s){let l=a(s);return l.room?e!==null&&l.game!==null&&l.game.slug!==e?Promise.reject(d("other_game","This player is playing another game. Use follow instead.")):t.join(l.room.code):Promise.reject(d("no_room","This player is not in a room."))}}}function A(n){return(Math.floor(n/864e5)+1)*864e5}function V(n,e,t){let i=new Set,r={...n},o,a=!1;function s(){!i.size||o!==void 0||a||(o=setTimeout(l,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),o.unref?.())}async function l(){o=void 0,a=!0;try{let m=await t(),c=m.day!==r.day;if(r={...m},c)for(let u of[...i])try{u({...m})}catch{}}catch{}finally{a=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),s()}}return{...n,random:de(n.seed),rng:()=>de(n.seed),onChange(m){return i.add(m),s(),()=>{i.delete(m),!i.size&&o!==void 0&&(clearTimeout(o),o=void 0)}}}}function J(n){return new Date(n).toISOString().slice(0,10)}async function q(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function de(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function O(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function me(n,e){return O(n)?.type===e}function Ne(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function fe(n,e,t=3e3){return new Promise(i=>{let r=!1,o=globalThis.crypto.randomUUID(),a=c=>{r||(r=!0,n.removeEventListener("message",l),n.clearTimeout(m),i(c))},s=()=>{n.parent.postMessage({type:"caisual:ready",instance:o},e)},l=c=>{if(c.origin!==e||c.source!==n.parent)return;if(me(c.data,"caisual:ready?")){s();return}if(!me(c.data,"caisual:hello"))return;let u=O(c.data),f=c.ports[0];if(typeof u?.ticket!="string"||!j(u.n)||f===void 0)return;f.start();let v=y=>Array.isArray(y)?y.map(b).filter(M=>M!==null):void 0;a({...b(u.language)?{language:b(u.language)}:{},languagePreferences:v(u.languagePreferences),gameLanguages:v(u.gameLanguages),ticket:u.ticket,n:u.n,live:Ne(u.live),invite:typeof u.invite=="string"?u.invite:null,porta:f})};n.addEventListener("message",l);let m=n.setTimeout(()=>a(null),t);s()})}function Le(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=O(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function je(n,e,t,i){return new Promise((r,o)=>{let a=!1,s=c=>{a||(a=!0,n.removeEventListener("message",l),e.clearTimeout(m),c===null?o(new Error("Ticket refresh timed out.")):r(c))},l=c=>{let u=O(c.data);u?.type==="caisual:ticket"&&u.aud===i&&typeof u.ticket=="string"&&s(u.ticket)};n.addEventListener("message",l);let m=e.setTimeout(()=>s(null),t);try{n.postMessage({type:"caisual:ticket",aud:i})}catch{s(null)}})}function U(n,e,t,i,r=3e3,o="portal"){let a=n,s=null,l=()=>{if(s!==null)return s;let c=je(e,t,r,o).then(u=>(a=u,u)).finally(()=>{s===c&&(s=null)});return s=c,c};return{async ottieni(){if(a===null)return l();let m=Le(a);return m!==null&&m-i()<3e4?l():a},rinnova:l}}var F=.02,he=300,Be=200,pe=3e3,Je=1e4,qe=[1e3,2e3,4e3],Ue=[300,600,1e3,1500,2e3,3e3,4e3],Fe=2;function ge(n,e=1){return Number.isNaN(n)?1:Math.min(e,Math.max(0,n))}function We(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var D=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.timerAbbonamento=null;this.tentativoAbbonamento=0;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??We(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=e.mic??!0;this.verificaIngresso(),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(d("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw d("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=ge(t,Fe);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(d(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,ge(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(d("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(d("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}verificaIngresso(){if(!this.contesto.connessa())throw d("offline","The room is not connected.");if(this.modeCorrente==="none")throw d("voice_disabled","Voice is disabled for this room.");if(this.dipendenze===null)throw d("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let o;try{o=await t.getUserMedia({audio:!0})}catch(s){throw this.permessoNegato(s)?d("permission_denied","Microphone permission was denied."):d("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(s){for(let l of o.getTracks())l.stop();throw s}let a=o.getAudioTracks()[0];if(a===void 0)throw d("voice_error","The microphone has no audio track.");this.stream=o,this.tracciaMic=a,a.enabled=!this.mutedCorrente,this.preparaAnalizzatore(o)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw d("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw d("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let o of this.gains.keys())this.aggiornaZero(o);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=o=>{let a=o.transceiver.mid,s=a===null?void 0:this.midGiocatori.get(a);s!==void 0&&this.collegaTraccia(s,o.track,o.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let o=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),a=await i.createOffer();await i.setLocalDescription(a),this.controllaGenerazione(t);let s=o.mid,l=i.localDescription?.sdp;if(s===null||l===void 0)throw d("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:l,mid:s})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw d("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw d("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0,await this.richiedi({t:"voice",op:"publish",mic:!0});return}if(r.sdp!==null)throw d("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,o)=>{let a=()=>{e.removeEventListener("connectionstatechange",s),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},s=()=>{t!==this.generazione?(a(),o(d("offline","Voice was stopped."))):e.connectionState==="connected"?(a(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(a(),o(d("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",s),this.cancellaAttesaConnessione=()=>{a(),o(d("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{a(),o(d("voice_error","The voice connection timed out."))},Je)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(c=>[c.id,c])),r=[];for(let[c,u]of this.sfuAttive){let f=i.get(c);f!==void 0&&f.session===u.session&&f.track===u.track||(r.push(u),this.riproduzioni.has(c)||u.receiver?.track.stop(),this.sfuAttive.delete(c),this.midGiocatori.delete(u.mid),this.scollegaTraccia(c))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(c=>c.mid)});let o=[...i.values()].filter(c=>!this.sfuAttive.has(c.id));if(o.length===0)return;let a;try{a=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:o.map(c=>({session:c.session,track:c.track}))})}catch(c){let u=T(c);if(u==="voice_error"&&this.peerSfu===t&&this.riprovaAbbonamento())return;if(u!=="not_allowed")throw c;for(let f of o)this.negati.add(f.id);return}if(a.op!=="subscribe")throw d("voice_error","The voice service returned an invalid response.");let s=!1;for(let c of a.tracks){let u=o.find(f=>f.session===c.session&&f.track===c.track);c.error==="not_allowed"&&u!==void 0?this.negati.add(u.id):c.error!==null&&(s=!0),!(c?.mid===null||c?.mid===void 0||c.error!==null||u===void 0)&&(this.midGiocatori.set(c.mid,u.id),this.sfuAttive.set(u.id,{session:u.session,track:u.track,mid:c.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:a.sdp});let l=await t.createAnswer();await t.setLocalDescription(l);let m=t.localDescription?.sdp;if(m===void 0)throw d("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:m}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0),s?this.riprovaAbbonamento():this.tentativoAbbonamento=0}riprovaAbbonamento(){let e=Ue[this.tentativoAbbonamento];return e===void 0?!1:(this.tentativoAbbonamento++,this.timerAbbonamento===null&&(this.timerAbbonamento=this.richiediDipendenze().setTimeout(()=>{this.timerAbbonamento=null,this.accodaRiconciliazione()},e)),!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=o=>{o.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:o.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=o=>{r.receiver=o.receiver,this.collegaTraccia(t,o.track,o.receiver)},this.osservaCaduta(i),this.micDesiderato?r.polite?i.addTrack(this.richiediMic()):i.addTransceiver(this.richiediMic(),{direction:"sendrecv"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(a=>a.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let o=t;try{if(o.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(o.candidate);return}if(o.kind!=="offer"&&o.kind!=="answer"||typeof o.sdp!="string")return;let a=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),s=o.kind==="offer"&&!a;if(r.ignoreOffer=!r.polite&&s,r.ignoreOffer)return;if(r.settingRemoteAnswer=o.kind==="answer",await r.pc.setRemoteDescription({type:o.kind,sdp:o.sdp}),r.settingRemoteAnswer=!1,o.kind==="offer"){let l=await r.pc.createAnswer();await r.pc.setLocalDescription(l);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(T(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>!(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic||this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team))}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<pe})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),o=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,pe-r));this.timerZero.set(e,o)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),o=r.creaMediaStream([t]),a=this.richiediAudioContext().createMediaStreamSource(o),s=this.richiediAudioContext().createGain();a.connect(s),s.connect(this.richiediAudioContext().destination);let l=null;try{l=this.richiediAudioContext().createAnalyser(),l.fftSize=256,a.connect(l)}catch{l=null}let m=r.creaAudioElement();m.srcObject=o,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:a,gain:s,analyser:l,audio:m,track:t,receiver:i});let c=this.sfuAttive.get(e);c!==void 0&&(c.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Be)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>F),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=he;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let o of this.copiaPeers()){let a=this.riproduzioni.get(o.id);this.livelloAnalizzatore(a?.analyser??null)>F?this.ultimoAudio.set(o.id,e.ora()):(a?.analyser===null||a?.analyser===void 0)&&(a?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>F)&&this.ultimoAudio.set(o.id,e.ora());let s=!o.muted&&e.ora()-(this.ultimoAudio.get(o.id)??0)<=he;(this.speakingPeers.get(o.id)??!1)!==s&&(this.speakingPeers.set(o.id,s),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,o)=>r+o*o,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>r.id===e?[]:this.modeCorrente==="team"&&t.find(a=>a.id===r.id)?.team!==i?.team?[]:[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}])}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(d("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=qe[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione),this.timerAbbonamento!==null&&e.clearTimeout(this.timerAbbonamento);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerAbbonamento=null,this.tentativoAbbonamento=0,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(d("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(o){this.richieste.delete(t),r(o)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw d("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw d("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw d("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw d("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="offline"||t==="voice_error"?e:d("voice_error","Voice could not be started.")}return d("voice_error","Voice could not be started.")}};var x=1,ve=[1e3,2e3,4e3,8e3],He=6e4,Ze=5e3,Ke=2e4,Ye=500,Xe=new Set([4003,4004,4005,4006,4008,4009]);function g(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}var ye=new Set(["waiting","lobby","countdown","playing","finished","ended"]),C=n=>typeof n=="number"&&Number.isFinite(n),P=n=>C(n)&&Number.isSafeInteger(n)&&n>=0,be=n=>n===null||C(n);function we(n){let e=g(n);return n===null||e!==null&&typeof e.keepSetup=="boolean"&&C(e.deadline)}function W(n){return P(n.tick)&&C(n.serverTime)&&P(n.tickRate)&&n.tickRate<=60}function Qe(n){if(n.t==="welcome"){let e=g(n.room),t=g(e?.configuration),i=g(t?.players);return e!==null&&typeof e.id=="string"&&(e.origin==="player"||e.origin==="matchmaking")&&typeof e.status=="string"&&ye.has(e.status)&&(e.mode===null||typeof e.mode=="string")&&C(e.seed)&&W(e)&&Object.hasOwn(e,"result")&&be(e.countdownAt)&&we(e.rematch)&&t!==null&&typeof t.persistent=="boolean"&&typeof t.requestRole=="boolean"&&i!==null&&P(i.min)&&i.min>=1&&P(i.max)&&i.max>=i.min&&typeof n.you=="string"&&Array.isArray(n.players)&&n.players.every(r=>g(r)!==null)&&Object.hasOwn(n,"state")}return n.t==="status"?typeof n.status=="string"&&ye.has(n.status)&&C(n.at)&&Object.hasOwn(n,"result")&&be(n.countdownAt)&&we(n.rematch):n.t==="snapshot"?W(n)&&Object.hasOwn(n,"state"):n.t==="state"?W(n)&&P(n.base)&&Array.isArray(n.patch)&&n.patch.every(e=>{let t=g(e);return t!==null&&(t.op==="del"||t.op==="set"&&Object.hasOwn(t,"value"))&&Array.isArray(t.path)&&t.path.every(i=>typeof i=="string"||P(i))}):!0}function Se(n){let e=g(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function et(n){let e=g(n);return e!==null&&typeof e.url=="string"}function S(n){return JSON.parse(JSON.stringify(n))}function tt(n,e){let t=S(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=S(i.value);continue}let r=t,o=i.path;for(let s=0;s<o.length-1;s++){let l=o[s];if(Array.isArray(r)){if(typeof l!="number"||l>=r.length)return{ok:!1};r=r[l]}else{let m=g(r);if(m===null||typeof l!="string"||!Object.hasOwn(m,l))return{ok:!1};r=m[l]}}let a=o.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof a!="number"||a>=r.length)return{ok:!1};r[a]=S(i.value)}else{let s=g(r);if(s===null||typeof a!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(s,a))return{ok:!1};delete s[a]}else Object.defineProperty(s,a,{configurable:!0,enumerable:!0,value:S(i.value),writable:!0})}}return{ok:!0,state:t}}function it(n){let e=_(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,s,l)=>{try{return await e(o,a,{...g(s),n:n.n},l)}catch(m){if(m instanceof Error&&"code"in m&&["version_outdated","version_mismatch"].includes(String(m.code))){let c=g(s),u=typeof c?.code=="string"?c.code.toUpperCase().replace(/[\\s-]/g,""):void 0,f=typeof c?.roomId=="string"?c.roomId:void 0;n.onVersionError?.(m,m.code==="version_mismatch"?{code:u,roomId:f}:void 0)}throw m}};async function i(o,a,s=!1){let l=await t(o,"POST",a,s);if(!Se(l))throw d("internal_error","The room service returned an invalid response.");return l}async function r(o){let a=await t("/match","POST",{mode:o.mode});if(!et(a))throw d("internal_error","The match service returned an invalid response.");return a}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var H=class{constructor(e,t,i,r,o,a){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=o;this.segnalaStanza=a;this.meta={mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.resultCorrente=null;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.origine="player";this.promessaPronta=new Promise((s,l)=>{this.risolviPronta=s,this.rifiutaPronta=l}),this.voice=new D({invia:s=>this.invia(s),connessa:()=>this.socket?.readyState===x&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),this.apri(i)}get origin(){return this.origine}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.origine=e.origin,this.metadataChanged({mode:e.mode,countdownAt:e.countdownAt,rematch:e.rematch,configuration:e.configuration,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(d("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(d("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(d("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let o=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(d("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:o});try{this.invia({t:"request-role",r:t,role:e})}catch(a){this.dipendenze.clearTimeout(o),this.roleRequests.delete(t),r(a)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(d("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(d("cancelled","The room was disconnected.")))}get role(){return this.giocatoriCorrenti.find(e=>e.id===this.youCorrente)?.role??null}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get code(){return this.codice}get result(){return this.resultCorrente}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-29),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw d("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==x||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(30,this.tickRateCorrente):30);this.inviiGioco=this.inviiGioco.filter(a=>e-a<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,o=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==x||this.terminata||this.lasciata)return;let a=this.dipendenze.ora();if(a<this.ultimoInvioGioco+i||this.inviiGioco.filter(l=>a-l<1e3).length>=30){this.programmaInput();return}let s=this.ultimoInput;try{this.send(JSON.parse(s)),this.inputInviato=s}catch{}},Math.max(0,Math.ceil(Math.max(o,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.origin==="player"&&this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}restart(){if(this.origin!=="matchmaking"){if(this.statusCorrente!=="finished")throw d("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}}leave(){this.lasciata||(this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===x&&this.invia({t:"leave"}),this.termina(1e3))}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==x)throw d("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw d("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==x||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Ze:Ke;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===x)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=g(i);if(r===null||typeof r.t!="string"||!Qe(r))return;t=r}catch{return}try{if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="players")this.riceviGiocatori(t.players);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,S(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(d(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=S(t.result),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime,!1),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.initialMetadata(t),this.notifica(this.ascoltatoriStato,this.statoPubblico,t.tick,t.serverTime),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e){this.giocatoriCorrenti=e.map(t=>({...t})),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){this.statusCorrente=e.status,this.resultCorrente=S(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch,countdownAt:e.countdownAt,...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=tt(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime)}aggiornaStato(e,t,i,r=!0){this.statoSincronizzato=S(e),this.statoPubblico=S(e),this.tickCorrente=t,r&&this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==x)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(Xe.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,ve.length-1),t=ve[e];if(this.tempoRiconnessione+t>He){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found","cpu_budget"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let a=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(d(a,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.prontaRisolta=!0,!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},Ye))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function $(n=null){return{invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw h()},async join(){throw h()},async match(){throw h()}}}function xe(n,e){let t,i=new Set,r=it({...n,onVersionError(c,u){t=u;for(let f of i)try{f(c)}catch{}}}),o=!1,a=null,s=c=>{let u=c?.code??null;o&&u===a||(o=!0,a=u,n.segnalaStanza?.(c))},l=async c=>{let u=new H(c.roomId,c.code,c.url,n,r,s);return await u.pronta(),u},m=(c,u)=>new Promise((f,v)=>{let y,M=!1,K=()=>{y.removeEventListener("message",ee),y.removeEventListener("close",X),y.removeEventListener("error",Q),u.signal?.removeEventListener("abort",L)},Y=()=>{try{y.close(1e3)}catch{}},R=(z,p)=>{M||(M=!0,K(),p&&Y(),v(z))};function L(){R(d("cancelled","The match request was cancelled."),!0)}function X(){R(h(),!1)}function Q(){R(h(),!0)}function ee(z){let p=null;try{p=typeof z.data=="string"?g(JSON.parse(z.data)):null}catch{}if(p===null||typeof p.t!="string"){R(d("internal_error","The match service sent an invalid message."),!0);return}if(p.t==="matched"){if(!Se(p)){R(d("internal_error","The match service sent an invalid message."),!0);return}M=!0,K(),Y(),f(p);return}if(p.t==="error"){R(d(typeof p.code=="string"?p.code:"internal_error",typeof p.message=="string"?p.message:"The match service could not complete the request."),!0);return}p.t!=="pong"&&R(d("internal_error","The match service sent an invalid message."),!0)}try{y=n.apriSocket(c)}catch{v(h());return}y.addEventListener("message",ee),y.addEventListener("close",X),y.addEventListener("error",Q),u.signal?.addEventListener("abort",L,{once:!0}),u.signal?.aborted===!0&&L()});return{invited:e,reload(){n.reload?.(t)},onError(c){return i.add(c),()=>{i.delete(c)}},async create(c){return l(await r.create(c.mode))},async join(c){let u=c??e;if(u==null||u.length===0)throw d("invalid_request","A room invitation code is required.");return l(await r.joinCode(u))},async match(c){let u=()=>c.signal?.aborted===!0;if(u())throw d("cancelled","The match request was cancelled.");try{let f=await r.match(c);if(u())throw d("cancelled","The match request was cancelled.");return await l(await m(f.url,c))}catch(f){let v=f instanceof Error&&"code"in f?String(f.code):"";throw["invalid_request","mode_local","no_server","rate_limited","offline","version_outdated","room_full","cancelled"].includes(v)?f:h()}}}}var k="caisual:save:",nt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function Z(n){if(!nt.test(n))throw d("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function Re(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function ke(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(k)&&e.push(i.slice(k.length))}return e}function rt(n,e){let t=()=>{if(n===null)throw h();return n};return{async set(i,r){Z(i);let o=t(),a=JSON.stringify({value:r}),s=new TextEncoder().encode(a).byteLength;if(s>262144)throw d("payload_too_large","The save is larger than 262144 bytes.");if(o.getItem(k+i)===null&&ke(o).length>=64)throw d("save_limit","A game can store at most 64 save keys.");let l={value:r,bytes:s,updatedAt:e()};return o.setItem(k+i,JSON.stringify(l)),{key:i,bytes:s,updatedAt:l.updatedAt}},async get(i){return Z(i),Re(t().getItem(k+i))?.value??null},async remove(i){Z(i),t().removeItem(k+i)},async list(){let i=t();return ke(i).flatMap(r=>{let o=Re(i.getItem(k+r));return o===null?[]:[{key:r,bytes:o.bytes,updatedAt:o.updatedAt}]}).sort((r,o)=>r.key.localeCompare(o.key))}}}async function G(n,e=null){let t=n.ora(),i=J(t),r=await q(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:V({day:i,seed:r,expiresAt:A(t)},n.ora,async()=>{let o=n.ora(),a=J(o);return{day:a,seed:await q(n.hostname,a,n.subtle),expiresAt:A(o)}}),time:{now:n.ora},save:rt(n.archivio,n.ora),room:$(e)}}function ot(n){let e=n?.querySelector(\'meta[name="caisual-app"]\')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function st(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function at(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:st(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>oe()}}async function ct(n){let e=ot(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return N(await G(n),void 0,n,null);let i=await fe(n.finestra,e,n.timeoutHandshake);if(i===null)return N(await G(n),void 0,n,null);let r=U(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),o=ae(e,n.fetcher,r),a=n.ora(),s;try{s=await o.me()}catch{let f=await G(n,i.invite);return N(f,i,n,null)}let l=n.ora(),m=s.serverTime-(a+l)/2,c=i.live===null?$(i.invite):xe({appOrigin:e,n:i.n,reload:f=>i.porta.postMessage({type:"caisual:reload",target:f}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:U(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(f){if(n.apriSocket!==void 0)return n.apriSocket(f);if(typeof WebSocket>"u")throw h();return new WebSocket(f)},ora:n.ora,setTimeout:(f,v)=>globalThis.setTimeout(f,v),clearTimeout:f=>globalThis.clearTimeout(f),setInterval:(f,v)=>globalThis.setInterval(f,v),clearInterval:f=>globalThis.clearInterval(f),voce:n.voce,segnalaStanza(f){try{i.porta.postMessage({type:"caisual:room",room:f})}catch{}}},i.invite),u={connected:!0,player:s.player,daily:V({day:s.day,seed:s.seed,expiresAt:s.expiresAt??A(s.serverTime)},()=>n.ora()+m,async()=>{let f=await o.me();return{day:f.day,seed:f.seed,expiresAt:f.expiresAt??A(f.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(f,v)=>o.saveSet(f,v),get:f=>o.saveGet(f),remove:f=>o.saveRemove(f),list:()=>o.saveList()},room:c};return N(u,i,n,s.game.slug)}function N(n,e,t,i){let r=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=ie(r,e?.gameLanguages);return{...n,player:{...n.player,language:o},text:se(t?.fetcher??globalThis.fetch,o,t?.pathname),crew:e?ue(e.porta,i,n.room):le()}}function Ae(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function lt(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>Ae()),new Promise(t=>{e=globalThis.setTimeout(()=>t(Ae()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function Pe(n=at()){let e=null;return{connect(){return e??(e=Promise.all([ct(n),lt(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Ce=Pe();globalThis.caisual=Ce;var Fi=Ce;export{Ce as caisual,Fi as default};\n');
|
|
4393
4213
|
return;
|
|
4394
4214
|
}
|
|
4395
4215
|
const textMatch = url.pathname.match(/^\/__caisual\/text\/([^/]+)\.json$/);
|
|
@@ -4450,11 +4270,12 @@ function record(valore) {
|
|
|
4450
4270
|
}
|
|
4451
4271
|
var CODICE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/;
|
|
4452
4272
|
function eMessaggioReady(value) {
|
|
4453
|
-
|
|
4273
|
+
const data = record(value);
|
|
4274
|
+
return data?.type === "caisual:ready" && typeof data.instance === "string" && data.instance.length > 0 && data.instance.length <= 128;
|
|
4454
4275
|
}
|
|
4455
4276
|
function eRichiestaBiglietto(value) {
|
|
4456
4277
|
const data = record(value);
|
|
4457
|
-
return data?.type === "caisual:ticket" && (data.aud ===
|
|
4278
|
+
return data?.type === "caisual:ticket" && (data.aud === "portal" || data.aud === "live");
|
|
4458
4279
|
}
|
|
4459
4280
|
function stanzaDaMessaggio(value) {
|
|
4460
4281
|
const data = record(value);
|
|
@@ -4465,7 +4286,7 @@ function stanzaDaMessaggio(value) {
|
|
|
4465
4286
|
}
|
|
4466
4287
|
function creaPonteOspite(input) {
|
|
4467
4288
|
let port = null, instance = null;
|
|
4468
|
-
let disposed = false
|
|
4289
|
+
let disposed = false;
|
|
4469
4290
|
let polling = null, pollingEnd = null;
|
|
4470
4291
|
let fermaCrew = null;
|
|
4471
4292
|
const stopPolling = () => {
|
|
@@ -4483,16 +4304,19 @@ function creaPonteOspite(input) {
|
|
|
4483
4304
|
askReady();
|
|
4484
4305
|
};
|
|
4485
4306
|
const loaded = () => {
|
|
4486
|
-
legacyReady = true;
|
|
4487
4307
|
poll();
|
|
4488
4308
|
};
|
|
4489
4309
|
const listen = (event) => {
|
|
4490
|
-
if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow
|
|
4310
|
+
if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow) return;
|
|
4491
4311
|
const data = record(event.data);
|
|
4492
|
-
|
|
4493
|
-
|
|
4312
|
+
if (data?.type === "caisual:opened") {
|
|
4313
|
+
input.onApertura?.();
|
|
4314
|
+
return;
|
|
4315
|
+
}
|
|
4316
|
+
if (!eMessaggioReady(data)) return;
|
|
4317
|
+
const nextInstance = data.instance;
|
|
4318
|
+
if (port && nextInstance === instance) return;
|
|
4494
4319
|
stopPolling();
|
|
4495
|
-
legacyReady = false;
|
|
4496
4320
|
instance = nextInstance;
|
|
4497
4321
|
fermaCrew?.();
|
|
4498
4322
|
fermaCrew = null;
|
|
@@ -4636,6 +4460,8 @@ export {
|
|
|
4636
4460
|
"fullscreen",
|
|
4637
4461
|
"autoplay",
|
|
4638
4462
|
"pointer-lock",
|
|
4463
|
+
"clipboard-write",
|
|
4464
|
+
"web-share",
|
|
4639
4465
|
...this.manifest.input.includes("gamepad") ? ["gamepad"] : [],
|
|
4640
4466
|
...voceAttiva ? ["microphone"] : []
|
|
4641
4467
|
].join("; "),
|
|
@@ -4685,7 +4511,7 @@ export {
|
|
|
4685
4511
|
}
|
|
4686
4512
|
let player = this.playersBySession.get(sessionId);
|
|
4687
4513
|
if (player === void 0) {
|
|
4688
|
-
const id = `dev_${
|
|
4514
|
+
const id = `dev_${createHash2("sha256").update(sessionId).digest("hex").slice(0, 24)}`;
|
|
4689
4515
|
player = {
|
|
4690
4516
|
sessionId,
|
|
4691
4517
|
id,
|
|
@@ -4880,7 +4706,7 @@ export {
|
|
|
4880
4706
|
}
|
|
4881
4707
|
async startMatch(request, response, ticket, origin) {
|
|
4882
4708
|
const body = object(await readBody(request));
|
|
4883
|
-
if (body === null || !Object.hasOwn(body, "mode") || Object.keys(body).some((field) => field !== "mode" && field !== "
|
|
4709
|
+
if (body === null || !Object.hasOwn(body, "mode") || Object.keys(body).some((field) => field !== "mode" && field !== "n")) {
|
|
4884
4710
|
throw new DevHttpError(400, "invalid_request", "The match request must contain a valid mode and n.");
|
|
4885
4711
|
}
|
|
4886
4712
|
if (body.n !== void 0 && body.n !== ticket.n) throw new DevHttpError(400, "invalid_request", "n must match the local game version.");
|
|
@@ -4922,7 +4748,7 @@ export {
|
|
|
4922
4748
|
this.definition,
|
|
4923
4749
|
this.roomManifest(),
|
|
4924
4750
|
{
|
|
4925
|
-
storageFile: join3(this.root, ".caisual-dev", "rooms", `${roomId}.json`),
|
|
4751
|
+
storageFile: join3(this.root, ".caisual-dev", "rooms-v2", `${roomId}.json`),
|
|
4926
4752
|
dailyDay: this.day
|
|
4927
4753
|
}
|
|
4928
4754
|
);
|
|
@@ -4979,7 +4805,7 @@ export {
|
|
|
4979
4805
|
this.definition,
|
|
4980
4806
|
this.roomManifest(),
|
|
4981
4807
|
{
|
|
4982
|
-
storageFile: join3(this.root, ".caisual-dev", "rooms", `${record2.roomId}.json`),
|
|
4808
|
+
storageFile: join3(this.root, ".caisual-dev", "rooms-v2", `${record2.roomId}.json`),
|
|
4983
4809
|
dailyDay: this.day
|
|
4984
4810
|
}
|
|
4985
4811
|
);
|
|
@@ -5142,7 +4968,7 @@ async function runDev(options) {
|
|
|
5142
4968
|
`);
|
|
5143
4969
|
process.stdout.write("Reload to see client edits. Restart dev after editing caisual.json, server.js or its imports.\n");
|
|
5144
4970
|
process.stdout.write("ctrl+c to stop\n");
|
|
5145
|
-
void verificaAggiornamenti({ versione: "0.
|
|
4971
|
+
void verificaAggiornamenti({ versione: "0.25.1", fetch, scrivi: (riga) => process.stderr.write(riga), env: process.env });
|
|
5146
4972
|
await new Promise((resolveStop) => {
|
|
5147
4973
|
const stop = () => resolveStop();
|
|
5148
4974
|
process.once("SIGINT", stop);
|
|
@@ -5201,7 +5027,7 @@ function templateIndex(multiplayer) {
|
|
|
5201
5027
|
<canvas tabindex="0"></canvas>
|
|
5202
5028
|
<p id="status" role="status" aria-live="polite"></p>
|
|
5203
5029
|
<script type="module">
|
|
5204
|
-
import { caisual } from '/__caisual/kit/v1.js';
|
|
5030
|
+
import { caisual } from '/__caisual/kit/v1.js?v=0.25.1';
|
|
5205
5031
|
import { createMenu } from './menu.js';
|
|
5206
5032
|
const c = await caisual.connect();
|
|
5207
5033
|
const t = await c.text();
|
|
@@ -5287,7 +5113,7 @@ export default defineGame({
|
|
|
5287
5113
|
var index_html_default = '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Beacon arena</title>\n<style>\n:root{--safe-top:env(safe-area-inset-top,0px);--safe-right:env(safe-area-inset-right,0px);--safe-bottom:env(safe-area-inset-bottom,0px);--safe-left:env(safe-area-inset-left,0px)}\nhtml,body{margin:0;width:100%;height:100%;overflow:hidden;background:#000000;color:#ffffff;font:15px system-ui}canvas{display:block;width:100%;height:100dvh;touch-action:none;outline:none}\n#hud{position:absolute;top:calc(var(--safe-top) + 12px);left:calc(var(--safe-left) + 12px);width:180px;max-width:calc(100% - var(--safe-left) - var(--safe-right) - 24px);box-sizing:border-box;padding:10px 12px;border:1px solid #808080;background:#000000}#hud[hidden]{display:none}#hud strong,#hud span{display:block}#hud span{font-size:12px;margin:4px 0;color:#ffffff}button{font:inherit;border:0;background:#ffffff;color:#000000;padding:7px 16px;touch-action:none}button:disabled{opacity:.5}\n</style></head><body><canvas tabindex="0"></canvas><div id="hud" hidden><strong id="score"></strong><span id="hint"></span><button id="pulse"></button></div><script type="module" src="./game.js"></script></body></html>\n';
|
|
5288
5114
|
|
|
5289
5115
|
// src/arcade/game.js.txt
|
|
5290
|
-
var game_js_default = "import { caisual } from '/__caisual/kit/v1.js';\nimport { createMenu } from './menu.js';\nimport { RULES, entity, stepEntity, reconcile, beacon, interpolate } from './physics.js';\nconst c = await caisual.connect(), t = await c.text();\ndocument.documentElement.lang = c.player.language; document.title = t('title');\nconst canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), hud = document.querySelector('#hud');\nconst score = document.querySelector('#score'), hint = document.querySelector('#hint'), button = document.querySelector('#pulse');\ncanvas.setAttribute('aria-label', t('controls')); button.textContent = t('pulse'); hint.textContent = t('hint');\nlet room = null, state = null;\nlet stops = [], pending = [], samples = [], predicted = null, seq = 0, actionSeq = 0, action = null, round = null;\nlet accumulator = 0, lastFrame = performance.now(), lastSend = 0, lastPulse = -Infinity, visual = null, offset = { x: 0, y: 0 };\nlet rendered = [];\nlet keys = new Set(), pointer = null, layout = { x: 0, y: 0, scale: 1 }, width = innerWidth, height = innerHeight;\nconst active = () => room !== null && ['waiting', 'playing'].includes(room.status) && room.connection === 'connected';\nfunction clearControls() { keys.clear(); pointer = null; }\nfunction read(next, tick, at = room.serverTime()) {\n if (!next?.entities) return;\n const newRound = next.round !== round;\n state = next;\n if (newRound) { round = next.round; pending = []; samples = []; predicted = visual = null; offset = { x: 0, y: 0 }; seq = actionSeq = 0; action = null; accumulator = 0; clearControls(); }\n const mine = state.entities[room.you];\n if (mine) {\n seq = Math.max(seq, mine.ack); actionSeq = Math.max(actionSeq, mine.actionAck);\n if (action && mine.actionAck >= action.seq) action = null;\n const before = predicted;\n ({ predicted, pending } = reconcile(mine, pending));\n // La correzione cambia subito la simulazione; solo il disegno assorbe lo scarto in pochi fotogrammi.\n if (before && !newRound) { offset.x += before.x - predicted.x; offset.y += before.y - predicted.y; }\n }\n samples.push({ at, entities: structuredClone(next.entities) });\n samples = samples.filter(sample => at - sample.at < 2500).slice(-120);\n}\nfunction attach(next) {\n stops.forEach(stop => stop()); stops = []; room = next;\n state = null; round = null; pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n read(room.state);\n if (room.status === 'waiting') predicted = entity(room.you, 0);\n stops.push(room.onState(read), room.onConnection(() => {\n pending = []; action = null; accumulator = 0; offset = { x: 0, y: 0 }; clearControls();\n const mine = room.state?.entities?.[room.you];\n if (mine) { predicted = { ...mine }; seq = mine.ack; }\n // Un valore neutro sostituisce anche l'ultimo input conservato dal kit durante la riconnessione.\n if (room) room.input({ type: 'move', round, commands: [] });\n }), room.onStatus(() => { clearControls(); if (room.status === 'waiting') predicted = entity(room.you, 0); }));\n}\nfunction detach() {\n stops.forEach(stop => stop()); stops = []; room = null; state = null; round = null;\n pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n}\nfunction resize() {\n width = innerWidth; height = innerHeight;\n const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n // Il campo occupa tutta la finestra: il margine serve solo a non finire sotto la tacca.\n const style = getComputedStyle(document.documentElement);\n const inset = side => parseFloat(style.getPropertyValue('--safe-' + side)) || 0;\n const availableWidth = width - inset('left') - inset('right'), availableHeight = height - inset('top') - inset('bottom');\n const scale = Math.max(.05, Math.min((availableWidth - 24) / RULES.width, (availableHeight - 24) / RULES.height));\n layout = { scale, x: inset('left') + (availableWidth - RULES.width * scale) / 2, y: inset('top') + (availableHeight - RULES.height * scale) / 2 };\n}\nfunction control() {\n if (!active()) return { x: 0, y: 0 };\n if (pointer && predicted) {\n const dx = pointer.x - predicted.x, dy = pointer.y - predicted.y, length = Math.hypot(dx, dy);\n return length < 8 ? { x: 0, y: 0 } : { x: dx / Math.max(36, length), y: dy / Math.max(36, length) };\n }\n return { x: Number(keys.has('ArrowRight') || keys.has('KeyD')) - Number(keys.has('ArrowLeft') || keys.has('KeyA')),\n y: Number(keys.has('ArrowDown') || keys.has('KeyS')) - Number(keys.has('ArrowUp') || keys.has('KeyW')) };\n}\nfunction pulse() {\n const now = performance.now();\n if (!active() || now - lastPulse < 650 || action) return;\n if (room.status === 'waiting') { lastPulse = now; return; }\n action = { type: 'pulse', round, seq: ++actionSeq }; lastPulse = now;\n try { room.send(action); } catch { action = null; }\n}\nbutton.addEventListener('pointerdown', event => { event.preventDefault(); pulse(); });\nbutton.addEventListener('click', pulse);\ncanvas.addEventListener('pointerdown', event => { if (!active()) return; canvas.focus(); canvas.setPointerCapture(event.pointerId); pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointermove', event => { if (pointer) pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointerup', () => { pointer = null; }); canvas.addEventListener('pointercancel', clearControls);\naddEventListener('keydown', event => { if (!active() || event.target.closest?.('input,select,textarea')) return; if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','KeyW','KeyA','KeyS','KeyD','Space'].includes(event.code)) { event.preventDefault(); keys.add(event.code); if (event.code === 'Space' && !event.repeat) pulse(); } });\naddEventListener('keyup', event => keys.delete(event.code)); addEventListener('blur', clearControls); document.addEventListener('visibilitychange', clearControls);\naddEventListener('resize', resize); resize();\n// Menu, lobby e risultato li disegna il gioco: la piattaforma da' solo le funzioni.\ncreateMenu({\n c, t, online: true, solo: false, mode: 'arena',\n resultText: () => t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: 0 }),\n onRoom: attach,\n onExit: detach,\n});\nfunction frame(now) {\n const dt = Math.min(.1, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now;\n if (active() && predicted) {\n accumulator += dt;\n while (accumulator + 1e-9 >= RULES.step) {\n accumulator -= RULES.step;\n // Il limite interrompe la previsione dopo un lungo silenzio invece di accumulare secondi di comandi arretrati.\n if (pending.length >= RULES.history) continue;\n const command = { seq: ++seq, ...control() };\n if (room.status === 'playing') pending.push(command);\n stepEntity(predicted, command);\n }\n const period = 1000 / Math.min(12, room.tickRate || 12);\n if (room.status === 'playing' && now - lastSend >= period) {\n lastSend = now;\n room.input({ type: 'move', round, commands: pending.slice(-RULES.history) });\n if (action && now - lastPulse >= 300) { try { room.send(action); lastPulse = now; } catch {} }\n }\n }\n const decay = Math.exp(-16 * dt); offset.x *= decay; offset.y *= decay;\n visual = predicted ? { ...predicted, x: predicted.x + offset.x, y: predicted.y + offset.y } : null;\n ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, width, height); ctx.save(); ctx.translate(layout.x, layout.y); ctx.scale(layout.scale, layout.scale);\n ctx.fillStyle = '#808080'; ctx.fillRect(0, 0, RULES.width, RULES.height);\n ctx.strokeStyle = '#ffffff0b'; ctx.lineWidth = 1;\n for (let x = 0; x < RULES.width; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, RULES.height); ctx.stroke(); }\n for (let y = 0; y < RULES.height; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(RULES.width, y); ctx.stroke(); }\n const target = beacon(state?.step ?? 0); ctx.fillStyle = '#ffffff1c'; ctx.beginPath(); ctx.arc(target.x, target.y, 90, 0, Math.PI * 2); ctx.fill();\n ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(target.x, target.y, 12 + Math.sin(now / 220) * 2, 0, Math.PI * 2); ctx.fill();\n const delay = room ? Math.max(100, (room.latency ?? 0) / 2 + 2000 / Math.max(1, room.tickRate)) : 100;\n // Il buffer usa il tempo dei campioni, cosi' gli altri corpi non saltano fra due aggiornamenti.\n const at = room ? room.serverTime() - delay : 0;\n const bodies = room?.status === 'waiting' && predicted ? [predicted] : state ? Object.values(state.entities) : [entity('demo', 0), entity('demo2', 1)];\n rendered = [];\n bodies.forEach((body, index) => {\n const own = room !== null && body.id === room.you;\n const shown = own && visual ? visual : interpolate(samples, at, body.id) ?? body;\n rendered.push({ id: body.id, x: shown.x, y: shown.y });\n const color = ['#ff0000', '#0066ff', '#ffff00', '#00cc00'][index % 4];\n ctx.fillStyle = color; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius, 0, Math.PI * 2); ctx.fill();\n ctx.strokeStyle = own ? '#ffffff' : color; ctx.lineWidth = own ? 3 : 1; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius + 6 + (room?.status === 'waiting' && own && now - lastPulse < 600 ? (now - lastPulse) / 10 : body.flash ? (18 - body.flash) * 3 : 0), 0, Math.PI * 2); ctx.stroke();\n ctx.fillStyle = '#ffffff'; ctx.font = '14px system-ui'; ctx.textAlign = 'center'; ctx.fillText(own ? t('you') : String(index + 1), shown.x, shown.y - 32);\n });\n ctx.restore();\n score.textContent = t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: Math.max(0, Math.ceil(RULES.seconds - (state?.step ?? 0) * RULES.step)) });\n if (room?.status === 'waiting') { const min = room.metadata.configuration.players.min, count = room.players.filter(player => player.connected).length; score.textContent = t('waiting', { n: Math.max(0, min - count), players: count, min }); }\n hud.hidden = !active(); button.disabled = !active() || !!action;\n requestAnimationFrame(frame);\n}\n// La sonda esiste solo in sviluppo per misurare previsione, geometria e stato senza creare una seconda connessione.\nif (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c, get room() { return room; }, get playing() { return active(); }, get motion() { return { predicted, visual, pending: pending.length, samples: samples.length, rendered, layout }; } };\nrequestAnimationFrame(frame);\n";
|
|
5116
|
+
var game_js_default = "import { caisual } from '/__caisual/kit/v1.js?v=0.25.1';\nimport { createMenu } from './menu.js';\nimport { RULES, entity, stepEntity, reconcile, beacon, interpolate } from './physics.js';\nconst c = await caisual.connect(), t = await c.text();\ndocument.documentElement.lang = c.player.language; document.title = t('title');\nconst canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), hud = document.querySelector('#hud');\nconst score = document.querySelector('#score'), hint = document.querySelector('#hint'), button = document.querySelector('#pulse');\ncanvas.setAttribute('aria-label', t('controls')); button.textContent = t('pulse'); hint.textContent = t('hint');\nlet room = null, state = null;\nlet stops = [], pending = [], samples = [], predicted = null, seq = 0, actionSeq = 0, action = null, round = null;\nlet accumulator = 0, lastFrame = performance.now(), lastSend = 0, lastPulse = -Infinity, visual = null, offset = { x: 0, y: 0 };\nlet rendered = [];\nlet keys = new Set(), pointer = null, layout = { x: 0, y: 0, scale: 1 }, width = innerWidth, height = innerHeight;\nconst active = () => room !== null && ['waiting', 'playing'].includes(room.status) && room.connection === 'connected';\nfunction clearControls() { keys.clear(); pointer = null; }\nfunction read(next, tick, at = room.serverTime()) {\n if (!next?.entities) return;\n const newRound = next.round !== round;\n state = next;\n if (newRound) { round = next.round; pending = []; samples = []; predicted = visual = null; offset = { x: 0, y: 0 }; seq = actionSeq = 0; action = null; accumulator = 0; clearControls(); }\n const mine = state.entities[room.you];\n if (mine) {\n seq = Math.max(seq, mine.ack); actionSeq = Math.max(actionSeq, mine.actionAck);\n if (action && mine.actionAck >= action.seq) action = null;\n const before = predicted;\n ({ predicted, pending } = reconcile(mine, pending));\n // La correzione cambia subito la simulazione; solo il disegno assorbe lo scarto in pochi fotogrammi.\n if (before && !newRound) { offset.x += before.x - predicted.x; offset.y += before.y - predicted.y; }\n }\n samples.push({ at, entities: structuredClone(next.entities) });\n samples = samples.filter(sample => at - sample.at < 2500).slice(-120);\n}\nfunction attach(next) {\n stops.forEach(stop => stop()); stops = []; room = next;\n state = null; round = null; pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n read(room.state);\n if (room.status === 'waiting') predicted = entity(room.you, 0);\n stops.push(room.onState(read), room.onConnection(() => {\n pending = []; action = null; accumulator = 0; offset = { x: 0, y: 0 }; clearControls();\n const mine = room.state?.entities?.[room.you];\n if (mine) { predicted = { ...mine }; seq = mine.ack; }\n // Un valore neutro sostituisce anche l'ultimo input conservato dal kit durante la riconnessione.\n if (room) room.input({ type: 'move', round, commands: [] });\n }), room.onStatus(() => { clearControls(); if (room.status === 'waiting') predicted = entity(room.you, 0); }));\n}\nfunction detach() {\n stops.forEach(stop => stop()); stops = []; room = null; state = null; round = null;\n pending = []; samples = []; predicted = visual = null; action = null; clearControls();\n}\nfunction resize() {\n width = innerWidth; height = innerHeight;\n const ratio = Math.min(devicePixelRatio || 1, 2); canvas.width = width * ratio; canvas.height = height * ratio; ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n // Il campo occupa tutta la finestra: il margine serve solo a non finire sotto la tacca.\n const style = getComputedStyle(document.documentElement);\n const inset = side => parseFloat(style.getPropertyValue('--safe-' + side)) || 0;\n const availableWidth = width - inset('left') - inset('right'), availableHeight = height - inset('top') - inset('bottom');\n const scale = Math.max(.05, Math.min((availableWidth - 24) / RULES.width, (availableHeight - 24) / RULES.height));\n layout = { scale, x: inset('left') + (availableWidth - RULES.width * scale) / 2, y: inset('top') + (availableHeight - RULES.height * scale) / 2 };\n}\nfunction control() {\n if (!active()) return { x: 0, y: 0 };\n if (pointer && predicted) {\n const dx = pointer.x - predicted.x, dy = pointer.y - predicted.y, length = Math.hypot(dx, dy);\n return length < 8 ? { x: 0, y: 0 } : { x: dx / Math.max(36, length), y: dy / Math.max(36, length) };\n }\n return { x: Number(keys.has('ArrowRight') || keys.has('KeyD')) - Number(keys.has('ArrowLeft') || keys.has('KeyA')),\n y: Number(keys.has('ArrowDown') || keys.has('KeyS')) - Number(keys.has('ArrowUp') || keys.has('KeyW')) };\n}\nfunction pulse() {\n const now = performance.now();\n if (!active() || now - lastPulse < 650 || action) return;\n if (room.status === 'waiting') { lastPulse = now; return; }\n action = { type: 'pulse', round, seq: ++actionSeq }; lastPulse = now;\n try { room.send(action); } catch { action = null; }\n}\nbutton.addEventListener('pointerdown', event => { event.preventDefault(); pulse(); });\nbutton.addEventListener('click', pulse);\ncanvas.addEventListener('pointerdown', event => { if (!active()) return; canvas.focus(); canvas.setPointerCapture(event.pointerId); pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointermove', event => { if (pointer) pointer = { x: (event.clientX - layout.x) / layout.scale, y: (event.clientY - layout.y) / layout.scale }; });\ncanvas.addEventListener('pointerup', () => { pointer = null; }); canvas.addEventListener('pointercancel', clearControls);\naddEventListener('keydown', event => { if (!active() || event.target.closest?.('input,select,textarea')) return; if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','KeyW','KeyA','KeyS','KeyD','Space'].includes(event.code)) { event.preventDefault(); keys.add(event.code); if (event.code === 'Space' && !event.repeat) pulse(); } });\naddEventListener('keyup', event => keys.delete(event.code)); addEventListener('blur', clearControls); document.addEventListener('visibilitychange', clearControls);\naddEventListener('resize', resize); resize();\n// Menu, lobby e risultato li disegna il gioco: la piattaforma da' solo le funzioni.\ncreateMenu({\n c, t, online: true, solo: false, mode: 'arena',\n resultText: () => t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: 0 }),\n onRoom: attach,\n onExit: detach,\n});\nfunction frame(now) {\n const dt = Math.min(.1, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now;\n if (active() && predicted) {\n accumulator += dt;\n while (accumulator + 1e-9 >= RULES.step) {\n accumulator -= RULES.step;\n // Il limite interrompe la previsione dopo un lungo silenzio invece di accumulare secondi di comandi arretrati.\n if (pending.length >= RULES.history) continue;\n const command = { seq: ++seq, ...control() };\n if (room.status === 'playing') pending.push(command);\n stepEntity(predicted, command);\n }\n const period = 1000 / Math.min(12, room.tickRate || 12);\n if (room.status === 'playing' && now - lastSend >= period) {\n lastSend = now;\n room.input({ type: 'move', round, commands: pending.slice(-RULES.history) });\n if (action && now - lastPulse >= 300) { try { room.send(action); lastPulse = now; } catch {} }\n }\n }\n const decay = Math.exp(-16 * dt); offset.x *= decay; offset.y *= decay;\n visual = predicted ? { ...predicted, x: predicted.x + offset.x, y: predicted.y + offset.y } : null;\n ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, width, height); ctx.save(); ctx.translate(layout.x, layout.y); ctx.scale(layout.scale, layout.scale);\n ctx.fillStyle = '#808080'; ctx.fillRect(0, 0, RULES.width, RULES.height);\n ctx.strokeStyle = '#ffffff0b'; ctx.lineWidth = 1;\n for (let x = 0; x < RULES.width; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, RULES.height); ctx.stroke(); }\n for (let y = 0; y < RULES.height; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(RULES.width, y); ctx.stroke(); }\n const target = beacon(state?.step ?? 0); ctx.fillStyle = '#ffffff1c'; ctx.beginPath(); ctx.arc(target.x, target.y, 90, 0, Math.PI * 2); ctx.fill();\n ctx.fillStyle = '#ffffff'; ctx.beginPath(); ctx.arc(target.x, target.y, 12 + Math.sin(now / 220) * 2, 0, Math.PI * 2); ctx.fill();\n const delay = room ? Math.max(100, (room.latency ?? 0) / 2 + 2000 / Math.max(1, room.tickRate)) : 100;\n // Il buffer usa il tempo dei campioni, cosi' gli altri corpi non saltano fra due aggiornamenti.\n const at = room ? room.serverTime() - delay : 0;\n const bodies = room?.status === 'waiting' && predicted ? [predicted] : state ? Object.values(state.entities) : [entity('demo', 0), entity('demo2', 1)];\n rendered = [];\n bodies.forEach((body, index) => {\n const own = room !== null && body.id === room.you;\n const shown = own && visual ? visual : interpolate(samples, at, body.id) ?? body;\n rendered.push({ id: body.id, x: shown.x, y: shown.y });\n const color = ['#ff0000', '#0066ff', '#ffff00', '#00cc00'][index % 4];\n ctx.fillStyle = color; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius, 0, Math.PI * 2); ctx.fill();\n ctx.strokeStyle = own ? '#ffffff' : color; ctx.lineWidth = own ? 3 : 1; ctx.beginPath(); ctx.arc(shown.x, shown.y, RULES.radius + 6 + (room?.status === 'waiting' && own && now - lastPulse < 600 ? (now - lastPulse) / 10 : body.flash ? (18 - body.flash) * 3 : 0), 0, Math.PI * 2); ctx.stroke();\n ctx.fillStyle = '#ffffff'; ctx.font = '14px system-ui'; ctx.textAlign = 'center'; ctx.fillText(own ? t('you') : String(index + 1), shown.x, shown.y - 32);\n });\n ctx.restore();\n score.textContent = t('score', { n: state?.entities?.[room?.you]?.score ?? 0, seconds: Math.max(0, Math.ceil(RULES.seconds - (state?.step ?? 0) * RULES.step)) });\n if (room?.status === 'waiting') { const min = room.metadata.configuration.players.min, count = room.players.filter(player => player.connected).length; score.textContent = t('waiting', { n: Math.max(0, min - count), players: count, min }); }\n hud.hidden = !active(); button.disabled = !active() || !!action;\n requestAnimationFrame(frame);\n}\n// La sonda esiste solo in sviluppo per misurare previsione, geometria e stato senza creare una seconda connessione.\nif (location.hostname === 'localhost' || location.hostname.endsWith('.localhost')) window.caisualDebug = { c, get room() { return room; }, get playing() { return active(); }, get motion() { return { predicted, visual, pending: pending.length, samples: samples.length, rendered, layout }; } };\nrequestAnimationFrame(frame);\n";
|
|
5291
5117
|
|
|
5292
5118
|
// src/arcade/physics.js.txt
|
|
5293
5119
|
var physics_js_default = "export const RULES = Object.freeze({ step: 1 / 60, width: 800, height: 600, radius: 18, speed: 220, seconds: 45, history: 60 });\nexport const clamp = (n, min, max) => Math.max(min, Math.min(max, n));\nexport function entity(id, index) {\n return { id, x: 220 + index % 2 * 360, y: 200 + Math.floor(index / 2) * 200, vx: 0, vy: 0, ack: 0, actionAck: 0, score: 0, cooldown: 0, flash: 0, queue: [] };\n}\nexport function stepEntity(body, control = { x: 0, y: 0 }) {\n const length = Math.max(1, Math.hypot(control.x, control.y));\n const blend = 1 - Math.exp(-18 * RULES.step);\n body.vx += (control.x / length * RULES.speed - body.vx) * blend;\n body.vy += (control.y / length * RULES.speed - body.vy) * blend;\n body.x = clamp(body.x + body.vx * RULES.step, RULES.radius, RULES.width - RULES.radius);\n body.y = clamp(body.y + body.vy * RULES.step, RULES.radius, RULES.height - RULES.radius);\n}\nexport function reconcile(authoritative, pending) {\n // Le conferme eliminano anche i comandi ritrasmessi, cosi' un movimento non viene applicato due volte.\n const remaining = pending.filter(command => command.seq > authoritative.ack).slice(-RULES.history);\n const predicted = { ...authoritative, queue: [] };\n for (const command of remaining) stepEntity(predicted, command);\n return { predicted, pending: remaining };\n}\nexport function beacon(step) {\n const places = [[400, 300], [170, 150], [630, 450], [630, 150], [170, 450]];\n const [x, y] = places[Math.floor(step * RULES.step / 5) % places.length];\n return { x, y };\n}\nexport function acceptControls(body, commands) {\n if (!Array.isArray(commands) || commands.length > RULES.history) return;\n const queued = new Map(body.queue.map(command => [command.seq, command]));\n for (const command of commands) {\n if (!command || !Number.isSafeInteger(command.seq) || command.seq <= body.ack || command.seq > body.ack + 600 ||\n !Number.isFinite(command.x) || !Number.isFinite(command.y) || Math.abs(command.x) > 1 || Math.abs(command.y) > 1) continue;\n if (!queued.has(command.seq)) queued.set(command.seq, { seq: command.seq, x: command.x, y: command.y });\n }\n // Il limite contiene memoria e ritardo; il server consuma al massimo un comando per passo, mai tempo inviato dal browser.\n body.queue = [...queued.values()].sort((a, b) => a.seq - b.seq).slice(-RULES.history);\n}\nexport function advance(state, deltaSeconds) {\n // Accumulare il tempo mantiene la stessa velocita' anche quando cambia la frequenza effettiva della stanza.\n state.accumulator += clamp(deltaSeconds, 0, .25);\n while (state.accumulator + 1e-9 >= RULES.step && state.step < RULES.seconds / RULES.step) {\n state.accumulator -= RULES.step; state.step++;\n for (const body of Object.values(state.entities)) {\n const command = body.queue.shift();\n stepEntity(body, command);\n if (command) body.ack = command.seq;\n body.cooldown = Math.max(0, body.cooldown - 1);\n body.flash = Math.max(0, body.flash - 1);\n }\n }\n}\nexport function pulse(state, body, seq) {\n if (!Number.isSafeInteger(seq) || seq <= body.actionAck || seq > body.actionAck + 600) return;\n body.actionAck = seq;\n // Una conferma vale anche per un tentativo rifiutato, per evitare ritrasmissioni infinite durante il recupero.\n if (body.cooldown > 0) return;\n body.cooldown = 36; body.flash = 18;\n const target = beacon(state.step);\n if (Math.hypot(body.x - target.x, body.y - target.y) <= 90) body.score++;\n}\nexport function standings(entities) {\n const order = Object.values(entities).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return order.map((body, i) => ({ playerId: body.id, score: body.score, rank: order.findIndex(other => other.score === body.score) + 1 }));\n}\nexport function interpolate(samples, at, id) {\n if (!samples.length) return null;\n let before = samples[0], after = samples.at(-1);\n for (const sample of samples) { if (sample.at <= at) before = sample; if (sample.at >= at) { after = sample; break; } }\n const a = before.entities[id], b = after.entities[id];\n if (!a || !b) return b ?? a ?? null;\n const alpha = clamp((at - before.at) / Math.max(1, after.at - before.at), 0, 1);\n return { ...b, x: a.x + (b.x - a.x) * alpha, y: a.y + (b.y - a.y) * alpha };\n}\n";
|
|
@@ -5885,7 +5711,7 @@ var ApiError = class extends Error {
|
|
|
5885
5711
|
hints;
|
|
5886
5712
|
};
|
|
5887
5713
|
function help() {
|
|
5888
|
-
return `Caisual ${"0.
|
|
5714
|
+
return `Caisual ${"0.25.1"}
|
|
5889
5715
|
|
|
5890
5716
|
Usage:
|
|
5891
5717
|
caisual init [--multiplayer | --arcade] [folder]
|
|
@@ -5901,6 +5727,10 @@ Usage:
|
|
|
5901
5727
|
caisual --help
|
|
5902
5728
|
caisual --version
|
|
5903
5729
|
|
|
5730
|
+
Agent guides:
|
|
5731
|
+
skill and init install SKILL.md, publish.md and kit.md in .claude/skills/caisual/
|
|
5732
|
+
and update the managed Caisual rules in AGENTS.md.
|
|
5733
|
+
|
|
5904
5734
|
Development:
|
|
5905
5735
|
--latency ms Added room WebSocket delay in each direction, integer 0-60000.
|
|
5906
5736
|
--jitter ms Delay variation, integer 0-60000. Requires --latency.
|
|
@@ -5908,7 +5738,7 @@ Development:
|
|
|
5908
5738
|
/__caisual/players?n=4 Independent guests, Drop and Spectate controls.
|
|
5909
5739
|
|
|
5910
5740
|
Environment:
|
|
5911
|
-
CAISUAL_KEY Required by publish, unlist, relist, and delete. Never accepted as a flag.
|
|
5741
|
+
CAISUAL_KEY Required by publish, versions, rollback, unlist, relist, and delete. Never accepted as a flag.
|
|
5912
5742
|
CAISUAL_ORIGIN Portal origin for development. Defaults to ${DEFAULT_ORIGIN}.
|
|
5913
5743
|
`;
|
|
5914
5744
|
}
|
|
@@ -5979,7 +5809,7 @@ Put game text in client/i18n/ and localize description in caisual.json. Run cais
|
|
|
5979
5809
|
`);
|
|
5980
5810
|
}
|
|
5981
5811
|
async function sha256(path) {
|
|
5982
|
-
const hash =
|
|
5812
|
+
const hash = createHash3("sha256");
|
|
5983
5813
|
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
|
5984
5814
|
return hash.digest("hex");
|
|
5985
5815
|
}
|
|
@@ -6139,7 +5969,7 @@ async function apiError(response) {
|
|
|
6139
5969
|
}
|
|
6140
5970
|
function intestazioniPortale(init2) {
|
|
6141
5971
|
const headers = new Headers(init2);
|
|
6142
|
-
headers.set("Caisual-Cli-Version", "0.
|
|
5972
|
+
headers.set("Caisual-Cli-Version", "0.25.1");
|
|
6143
5973
|
return headers;
|
|
6144
5974
|
}
|
|
6145
5975
|
async function requestJson(url, init2) {
|
|
@@ -6313,33 +6143,7 @@ function parseUploads(payload, files, server, wasm = []) {
|
|
|
6313
6143
|
serverTarget
|
|
6314
6144
|
};
|
|
6315
6145
|
}
|
|
6316
|
-
|
|
6317
|
-
{ percorso: "overlay", motivo: "the platform no longer draws anything over the game; the game draws its own menu" },
|
|
6318
|
-
{ percorso: "replays", motivo: "replays were removed" },
|
|
6319
|
-
{ percorso: "modes[].label", motivo: "only the game shows mode names now" },
|
|
6320
|
-
{ percorso: "modes[].instructions", motivo: "the game explains itself" },
|
|
6321
|
-
{ percorso: "roles[].label", motivo: "only the game shows role names now" }
|
|
6322
|
-
];
|
|
6323
|
-
function campiRimossi(value) {
|
|
6324
|
-
const manifest = object2(value);
|
|
6325
|
-
if (manifest === null) return [];
|
|
6326
|
-
const elenco = (chiave) => Array.isArray(manifest[chiave]) ? manifest[chiave].flatMap((voce) => {
|
|
6327
|
-
const record2 = object2(voce);
|
|
6328
|
-
return record2 === null ? [] : [record2];
|
|
6329
|
-
}) : [];
|
|
6330
|
-
const presenti = /* @__PURE__ */ new Set();
|
|
6331
|
-
for (const campo of ["overlay", "replays"]) {
|
|
6332
|
-
if (Object.hasOwn(manifest, campo)) presenti.add(campo);
|
|
6333
|
-
}
|
|
6334
|
-
for (const mode of elenco("modes")) {
|
|
6335
|
-
for (const campo of ["label", "instructions"]) if (Object.hasOwn(mode, campo)) presenti.add(`modes[].${campo}`);
|
|
6336
|
-
}
|
|
6337
|
-
for (const role of elenco("roles")) {
|
|
6338
|
-
if (Object.hasOwn(role, "label")) presenti.add("roles[].label");
|
|
6339
|
-
}
|
|
6340
|
-
return CAMPI_RIMOSSI2.filter((campo) => presenti.has(campo.percorso)).map((campo) => `remove ${campo.percorso}: ${campo.motivo}`);
|
|
6341
|
-
}
|
|
6342
|
-
async function readManifest(root, warn, pubblicazione = true) {
|
|
6146
|
+
async function readManifest(root) {
|
|
6343
6147
|
const path = join4(root, "caisual.json");
|
|
6344
6148
|
let source;
|
|
6345
6149
|
try {
|
|
@@ -6353,17 +6157,11 @@ async function readManifest(root, warn, pubblicazione = true) {
|
|
|
6353
6157
|
} catch {
|
|
6354
6158
|
throw new CliError(2, "caisual.json: must contain valid JSON.");
|
|
6355
6159
|
}
|
|
6356
|
-
const
|
|
6357
|
-
if (rimossi.length > 0) {
|
|
6358
|
-
throw new CliError(2, `caisual.json uses fields the platform removed:
|
|
6359
|
-
${rimossi.map((voce) => `- ${voce}`).join("\n")}`);
|
|
6360
|
-
}
|
|
6361
|
-
const result = pubblicazione ? validaManifestPubblicazione(value) : validaManifest(value);
|
|
6160
|
+
const result = validaManifest(value);
|
|
6362
6161
|
if (!result.ok) {
|
|
6363
6162
|
throw new CliError(2, `caisual.json is not valid:
|
|
6364
6163
|
${result.errori.map((error) => `- ${error}`).join("\n")}`);
|
|
6365
6164
|
}
|
|
6366
|
-
for (const warning of avvisiManifest(value)) warn?.(warning);
|
|
6367
6165
|
return result.manifest;
|
|
6368
6166
|
}
|
|
6369
6167
|
async function captureGameError(errors, operation) {
|
|
@@ -6401,7 +6199,7 @@ async function checkGame(root) {
|
|
|
6401
6199
|
report.errors.push(`The game path is not a folder: ${root}`);
|
|
6402
6200
|
return finishReport(report);
|
|
6403
6201
|
}
|
|
6404
|
-
const manifest = await captureGameError(report.errors, () => readManifest(root
|
|
6202
|
+
const manifest = await captureGameError(report.errors, () => readManifest(root));
|
|
6405
6203
|
if (manifest === null) return finishReport(report);
|
|
6406
6204
|
report.manifest = {
|
|
6407
6205
|
id: manifest.id,
|
|
@@ -6513,13 +6311,13 @@ async function check(folderArgument, json) {
|
|
|
6513
6311
|
if (!report.ok) process.exitCode = 2;
|
|
6514
6312
|
}
|
|
6515
6313
|
async function publish(folderArgument) {
|
|
6516
|
-
void verificaAggiornamenti({ versione: "0.
|
|
6314
|
+
void verificaAggiornamenti({ versione: "0.25.1", fetch, scrivi: (riga) => process.stderr.write(riga), env: process.env });
|
|
6517
6315
|
const root = resolve3(process.cwd(), folderArgument);
|
|
6518
6316
|
const report = await checkGame(root);
|
|
6519
6317
|
for (const warning of report.warnings) process.stderr.write(`Warning: ${warning}
|
|
6520
6318
|
`);
|
|
6521
6319
|
if (!report.ok) throw new CliError(2, report.errors.join("\n"));
|
|
6522
|
-
const manifest = await readManifest(root
|
|
6320
|
+
const manifest = await readManifest(root);
|
|
6523
6321
|
const files = await listClientFiles(join4(root, "client"));
|
|
6524
6322
|
const serverResult = await readServerFile(root);
|
|
6525
6323
|
const server = serverResult.file;
|
|
@@ -6595,7 +6393,7 @@ async function publish(folderArgument) {
|
|
|
6595
6393
|
async function gameIdFromTarget(target) {
|
|
6596
6394
|
const path = resolve3(process.cwd(), target);
|
|
6597
6395
|
try {
|
|
6598
|
-
if ((await fs4.stat(path)).isDirectory()) return (await readManifest(path
|
|
6396
|
+
if ((await fs4.stat(path)).isDirectory()) return (await readManifest(path)).id;
|
|
6599
6397
|
} catch (error) {
|
|
6600
6398
|
if (error.code !== "ENOENT") {
|
|
6601
6399
|
throw new CliError(2, `The game target could not be read: ${target}`);
|
|
@@ -6661,34 +6459,65 @@ var SITO = "https://caisual.com";
|
|
|
6661
6459
|
function guidesSection() {
|
|
6662
6460
|
const guides = JSON.parse(`[{"slug":"overview","title":"What Caisual is","description":"A free home for small browser games, with multiplayer built in."},{"slug":"quick-start","title":"Quick start","description":"From an empty folder to a permanent link."},{"slug":"manifest","title":"The manifest","description":"caisual.json is everything the portal knows about your game."},{"slug":"rooms","title":"Rooms","description":"Server-owned state for up to 24 players."},{"slug":"voice","title":"Voice","description":"Room voice in one manifest field, with gains owned by your server."},{"slug":"matchmaking","title":"Matchmaking","description":"Enter a room immediately. Play while other players arrive."},{"slug":"friends-and-parties","title":"Friends","description":"The player's friends, their party and their invitations, inside your game."},{"slug":"player-identity","title":"Identity","description":"Every player has a stable id before your game draws a frame."},{"slug":"saves","title":"Saves","description":"Cloud saves and one daily seed, single player included."},{"slug":"local-development","title":"Local dev","description":"The production handshake, multiple guests and network simulation."},{"slug":"device-requirements","title":"Devices","description":"Declare what you need, then read what the machine has."},{"slug":"versions","title":"Game versions","description":"Updates, rooms, rollback and compatible player data."},{"slug":"limits-and-rules","title":"Limits","description":"Every ceiling, every rule, in one page."},{"slug":"faq","title":"FAQ","description":"Short answers, in one place."}]`);
|
|
6663
6461
|
return [
|
|
6664
|
-
"
|
|
6462
|
+
"## Guides",
|
|
6665
6463
|
"",
|
|
6666
|
-
`
|
|
6464
|
+
`Fetch the Markdown guide for the topic you are working on. The full guide index is at ${SITO}/llms.txt.`,
|
|
6667
6465
|
"",
|
|
6668
6466
|
...guides.map((guide) => `- [${guide.title}](${SITO}/docs/${guide.slug}.md): ${guide.description}`),
|
|
6669
6467
|
""
|
|
6670
6468
|
].join("\n");
|
|
6671
6469
|
}
|
|
6470
|
+
function guideHeadings(document) {
|
|
6471
|
+
return Array.from(document.matchAll(/^## (.+)$/gm), ([, title]) => `- ${title}`).join("\n");
|
|
6472
|
+
}
|
|
6672
6473
|
async function installSkill(root) {
|
|
6673
|
-
const skillPath = join4(root, ".claude", "skills", "caisual", "SKILL.md");
|
|
6674
6474
|
const skill = `---
|
|
6675
6475
|
name: caisual
|
|
6676
|
-
description:
|
|
6476
|
+
description: Use when creating, testing or publishing a browser game on Caisual, including multiplayer rooms, matchmaking, friends, voice and cloud saves.
|
|
6677
6477
|
---
|
|
6678
6478
|
|
|
6679
|
-
|
|
6479
|
+
# Caisual
|
|
6480
|
+
|
|
6481
|
+
${AGENT_RULES}
|
|
6482
|
+
|
|
6483
|
+
## Commands
|
|
6484
|
+
|
|
6485
|
+
- \`caisual init [--multiplayer | --arcade] [folder]\` creates a game folder and installs these guides.
|
|
6486
|
+
- \`caisual dev\` runs the game locally. \`caisual check --json\` reports local validation results.
|
|
6487
|
+
- \`caisual publish\` creates a new version. Use \`caisual versions\` to list versions and \`caisual rollback --to <n>\` to restore one.
|
|
6488
|
+
- \`caisual unlist\` hides the game from the catalog. \`caisual relist\` lists it again. \`caisual delete --yes\` permanently removes it.
|
|
6489
|
+
|
|
6490
|
+
Set \`CAISUAL_KEY\` in the environment to publish or manage a published game.
|
|
6680
6491
|
|
|
6681
|
-
|
|
6492
|
+
## Which file to read
|
|
6493
|
+
|
|
6494
|
+
### [publish.md](./publish.md)
|
|
6495
|
+
|
|
6496
|
+
Read for the game folder, manifest, required images and publishing rules.
|
|
6497
|
+
|
|
6498
|
+
${guideHeadings(publish_default)}
|
|
6499
|
+
|
|
6500
|
+
### [kit.md](./kit.md)
|
|
6501
|
+
|
|
6502
|
+
Read for everything the game calls at runtime, in the browser and on the room server.
|
|
6503
|
+
|
|
6504
|
+
${guideHeadings(kit_default)}
|
|
6505
|
+
|
|
6506
|
+
These files are the copy included in CLI ${"0.25.1"}. The current versions are at ${SITO}/publish.md and ${SITO}/kit.md.
|
|
6682
6507
|
|
|
6683
6508
|
${guidesSection()}`;
|
|
6684
|
-
|
|
6685
|
-
|
|
6686
|
-
|
|
6687
|
-
|
|
6688
|
-
|
|
6689
|
-
|
|
6509
|
+
const directory = join4(root, ".claude", "skills", "caisual");
|
|
6510
|
+
await fs4.mkdir(directory, { recursive: true });
|
|
6511
|
+
for (const [name, content] of Object.entries({ "publish.md": publish_default, "kit.md": kit_default, "SKILL.md": skill })) {
|
|
6512
|
+
const path = join4(directory, name);
|
|
6513
|
+
let current;
|
|
6514
|
+
try {
|
|
6515
|
+
current = await fs4.readFile(path, "utf8");
|
|
6516
|
+
} catch (error) {
|
|
6517
|
+
if (error.code !== "ENOENT") throw error;
|
|
6518
|
+
}
|
|
6519
|
+
if (current !== content) await fs4.writeFile(path, content, "utf8");
|
|
6690
6520
|
}
|
|
6691
|
-
if (currentSkill !== skill) await fs4.writeFile(skillPath, skill, "utf8");
|
|
6692
6521
|
const agentsPath = join4(root, "AGENTS.md");
|
|
6693
6522
|
let agents = "";
|
|
6694
6523
|
try {
|
|
@@ -6698,7 +6527,7 @@ ${guidesSection()}`;
|
|
|
6698
6527
|
}
|
|
6699
6528
|
const updated = updateAgentInstructions(agents, SITO);
|
|
6700
6529
|
if (updated !== agents) await fs4.writeFile(agentsPath, updated, "utf8");
|
|
6701
|
-
return
|
|
6530
|
+
return join4(directory, "SKILL.md");
|
|
6702
6531
|
}
|
|
6703
6532
|
async function run(argumentsList) {
|
|
6704
6533
|
const [command, ...argumentsAfterCommand] = argumentsList;
|
|
@@ -6707,7 +6536,7 @@ async function run(argumentsList) {
|
|
|
6707
6536
|
return;
|
|
6708
6537
|
}
|
|
6709
6538
|
if (command === "--version" || command === "-V") {
|
|
6710
|
-
process.stdout.write(`${"0.
|
|
6539
|
+
process.stdout.write(`${"0.25.1"}
|
|
6711
6540
|
`);
|
|
6712
6541
|
return;
|
|
6713
6542
|
}
|